blob: ed7908dfc924105c1e7a2df8d2246470b145fa27 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000041#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000042#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner58258242008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattnerb0d38442008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 public:
Mike Stump11289f42009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 };
Chris Lattner58258242008-04-10 02:22:51 +000071
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000078 }
79
Chris Lattnerb0d38442008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106
Douglas Gregor8e12c382008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109
Douglas Gregor97a9c812008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000118 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000119
John McCall7353c862013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0d49512012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner58258242008-04-10 02:22:51 +0000147}
148
Richard Smithb7151b92013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith938f40b2011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
Anders Carlssonf1c26952009-08-25 01:02:06 +0000320 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 Param->setInvalidDecl();
324 return;
325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
John McCallb268a282010-08-23 23:25:46 +0000327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000328}
329
Douglas Gregor58354032008-12-24 00:01:03 +0000330/// ActOnParamUnparsedDefaultArgument - We've seen a default
331/// argument for a function parameter, but we can't parse it yet
332/// because we're inside a class definition. Note that this default
333/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000335 SourceLocation EqualLoc,
336 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000337 if (!param)
338 return;
Mike Stump11289f42009-09-09 15:08:12 +0000339
John McCall48871652010-08-21 09:40:31 +0000340 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000341 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000342 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000343}
344
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000348 if (!param)
349 return;
Mike Stump11289f42009-09-09 15:08:12 +0000350
John McCall48871652010-08-21 09:40:31 +0000351 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000352 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000354}
355
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000356/// CheckExtraCXXDefaultArguments - Check for any extra default
357/// arguments in the declarator, which is not a function declaration
358/// or definition and therefore is not permitted to have default
359/// arguments. This routine should be invoked for every declarator
360/// that is not a function declaration or definition.
361void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
362 // C++ [dcl.fct.default]p3
363 // A default argument expression shall be specified only in the
364 // parameter-declaration-clause of a function declaration or in a
365 // template-parameter (14.1). It shall not be specified for a
366 // parameter pack. If it is specified in a
367 // parameter-declaration-clause, it shall not occur within a
368 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000369 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000370 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000371 DeclaratorChunk &chunk = D.getTypeObject(i);
372 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000373 if (MightBeFunction) {
374 // This is a function declaration. It can have default arguments, but
375 // keep looking in case its return type is a function type with default
376 // arguments.
377 MightBeFunction = false;
378 continue;
379 }
Alp Tokerc5350722014-02-26 22:27:52 +0000380 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
381 ++argIdx) {
382 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000383 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000384 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000385 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000386 << SourceRange((*Toks)[1].getLocation(),
387 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000389 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000390 } else if (Param->getDefaultArg()) {
391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
392 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000393 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000394 }
395 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000396 } else if (chunk.Kind != DeclaratorChunk::Paren) {
397 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000398 }
399 }
400}
401
David Majnemer502b0ed2013-06-25 23:09:30 +0000402static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
403 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
404 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
405 if (!PVD->hasDefaultArg())
406 return false;
407 if (!PVD->hasInheritedDefaultArg())
408 return true;
409 }
410 return false;
411}
412
Craig Toppere4794282012-09-21 04:33:26 +0000413/// MergeCXXFunctionDecl - Merge two declarations of the same C++
414/// function, once we already know that they have the same
415/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
416/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000417bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
418 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000419 bool Invalid = false;
420
Chris Lattner199abbc2008-04-08 05:04:30 +0000421 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // For non-template functions, default arguments can be added in
423 // later declarations of a function in the same
424 // scope. Declarations in different scopes have completely
425 // distinct sets of default arguments. That is, declarations in
426 // inner scopes do not acquire default arguments from
427 // declarations in outer scopes, and vice versa. In a given
428 // function declaration, all parameters subsequent to a
429 // parameter with a default argument shall have default
430 // arguments supplied in this or previous declarations. A
431 // default argument shall not be redefined by a later
432 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000433 //
434 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000435 // Except for member functions of class templates, the default arguments
436 // in a member function definition that appears outside of the class
437 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000438 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000439 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
440 ParmVarDecl *OldParam = Old->getParamDecl(p);
441 ParmVarDecl *NewParam = New->getParamDecl(p);
442
James Molloye9430032012-03-13 08:55:35 +0000443 bool OldParamHasDfl = OldParam->hasDefaultArg();
444 bool NewParamHasDfl = NewParam->hasDefaultArg();
445
446 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000447
448 // The declaration context corresponding to the scope is the semantic
449 // parent, unless this is a local function declaration, in which case
450 // it is that surrounding function.
451 DeclContext *ScopeDC = New->getLexicalDeclContext();
452 if (!ScopeDC->isFunctionOrMethod())
453 ScopeDC = New->getDeclContext();
454 if (S && !isDeclInScope(ND, ScopeDC, S) &&
455 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000456 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000457 // the same scope and this is not an out-of-line definition of
458 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000459 OldParamHasDfl = false;
460
461 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000462
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000463 unsigned DiagDefaultParamID =
464 diag::err_param_default_argument_redefinition;
465
466 // MSVC accepts that default parameters be redefined for member functions
467 // of template class. The new default parameter's value is ignored.
468 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000469 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000470 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
471 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000472 // Merge the old default argument into the new parameter.
473 NewParam->setHasInheritedDefaultArg();
474 if (OldParam->hasUninstantiatedDefaultArg())
475 NewParam->setUninstantiatedDefaultArg(
476 OldParam->getUninstantiatedDefaultArg());
477 else
478 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000479 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000480 Invalid = false;
481 }
482 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000483
Francois Pichet8cb243a2011-04-10 04:58:30 +0000484 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
485 // hint here. Alternatively, we could walk the type-source information
486 // for NewParam to find the last source location in the type... but it
487 // isn't worth the effort right now. This is the kind of test case that
488 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000489 // int f(int);
490 // void g(int (*fp)(int) = f);
491 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000492 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000493 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000494
495 // Look for the function declaration where the default argument was
496 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000497 for (FunctionDecl *Older = Old->getPreviousDecl();
498 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000499 if (!Older->getParamDecl(p)->hasDefaultArg())
500 break;
501
502 OldParam = Older->getParamDecl(p);
503 }
504
505 Diag(OldParam->getLocation(), diag::note_previous_definition)
506 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000507 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000508 // Merge the old default argument into the new parameter.
509 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000510 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000511 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000512 if (OldParam->hasUninstantiatedDefaultArg())
513 NewParam->setUninstantiatedDefaultArg(
514 OldParam->getUninstantiatedDefaultArg());
515 else
John McCalle61b02b2010-05-04 01:53:42 +0000516 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000517 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000518 if (New->getDescribedFunctionTemplate()) {
519 // Paragraph 4, quoted above, only applies to non-template functions.
520 Diag(NewParam->getLocation(),
521 diag::err_param_default_argument_template_redecl)
522 << NewParam->getDefaultArgRange();
523 Diag(Old->getLocation(), diag::note_template_prev_declaration)
524 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000525 } else if (New->getTemplateSpecializationKind()
526 != TSK_ImplicitInstantiation &&
527 New->getTemplateSpecializationKind() != TSK_Undeclared) {
528 // C++ [temp.expr.spec]p21:
529 // Default function arguments shall not be specified in a declaration
530 // or a definition for one of the following explicit specializations:
531 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000532 // - the explicit specialization of a member function template;
533 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000534 // template where the class template specialization to which the
535 // member function specialization belongs is implicitly
536 // instantiated.
537 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
538 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
539 << New->getDeclName()
540 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000541 } else if (New->getDeclContext()->isDependentContext()) {
542 // C++ [dcl.fct.default]p6 (DR217):
543 // Default arguments for a member function of a class template shall
544 // be specified on the initial declaration of the member function
545 // within the class template.
546 //
547 // Reading the tea leaves a bit in DR217 and its reference to DR205
548 // leads me to the conclusion that one cannot add default function
549 // arguments for an out-of-line definition of a member function of a
550 // dependent type.
551 int WhichKind = 2;
552 if (CXXRecordDecl *Record
553 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
554 if (Record->getDescribedClassTemplate())
555 WhichKind = 0;
556 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
557 WhichKind = 1;
558 else
559 WhichKind = 2;
560 }
561
562 Diag(NewParam->getLocation(),
563 diag::err_param_default_argument_member_template_redecl)
564 << WhichKind
565 << NewParam->getDefaultArgRange();
566 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000567 }
568 }
569
Richard Smith58c3cc12012-11-28 03:45:24 +0000570 // DR1344: If a default argument is added outside a class definition and that
571 // default argument makes the function a special member function, the program
572 // is ill-formed. This can only happen for constructors.
573 if (isa<CXXConstructorDecl>(New) &&
574 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
575 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
576 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
577 if (NewSM != OldSM) {
578 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
579 assert(NewParam->hasDefaultArg());
580 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
581 << NewParam->getDefaultArgRange() << NewSM;
582 Diag(Old->getLocation(), diag::note_previous_declaration);
583 }
584 }
585
David Majnemeree4f4022014-03-30 06:44:54 +0000586 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000587 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000588 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000589 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 if (New->isConstexpr() != Old->isConstexpr()) {
591 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
592 << New << New->isConstexpr();
593 Diag(Old->getLocation(), diag::note_previous_declaration);
594 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000595 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
596 // C++11 [dcl.fcn.spec]p4:
597 // If the definition of a function appears in a translation unit before its
598 // first declaration as inline, the program is ill-formed.
599 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
600 Diag(Def->getLocation(), diag::note_previous_definition);
601 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000602 }
603
David Majnemer502b0ed2013-06-25 23:09:30 +0000604 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000605 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000606 // the only declaration of the function or function template in the
607 // translation unit.
608 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
609 functionDeclHasDefaultArgument(Old)) {
610 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
611 Diag(Old->getLocation(), diag::note_previous_declaration);
612 Invalid = true;
613 }
614
Douglas Gregorf40863c2010-02-12 07:32:17 +0000615 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000616 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000617
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000618 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000619}
620
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000621/// \brief Merge the exception specifications of two variable declarations.
622///
623/// This is called when there's a redeclaration of a VarDecl. The function
624/// checks if the redeclaration might have an exception specification and
625/// validates compatibility and merges the specs if necessary.
626void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
627 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000628 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000629 return;
630
631 assert(Context.hasSameType(New->getType(), Old->getType()) &&
632 "Should only be called if types are otherwise the same.");
633
634 QualType NewType = New->getType();
635 QualType OldType = Old->getType();
636
637 // We're only interested in pointers and references to functions, as well
638 // as pointers to member functions.
639 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
640 NewType = R->getPointeeType();
641 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
642 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
643 NewType = P->getPointeeType();
644 OldType = OldType->getAs<PointerType>()->getPointeeType();
645 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
646 NewType = M->getPointeeType();
647 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
648 }
649
650 if (!NewType->isFunctionProtoType())
651 return;
652
653 // There's lots of special cases for functions. For function pointers, system
654 // libraries are hopefully not as broken so that we don't need these
655 // workarounds.
656 if (CheckEquivalentExceptionSpec(
657 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
658 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
659 New->setInvalidDecl();
660 }
661}
662
Chris Lattner199abbc2008-04-08 05:04:30 +0000663/// CheckCXXDefaultArguments - Verify that the default arguments for a
664/// function declaration are well-formed according to C++
665/// [dcl.fct.default].
666void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
667 unsigned NumParams = FD->getNumParams();
668 unsigned p;
669
670 // Find first parameter with a default argument
671 for (p = 0; p < NumParams; ++p) {
672 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000673 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000674 break;
675 }
676
677 // C++ [dcl.fct.default]p4:
678 // In a given function declaration, all parameters
679 // subsequent to a parameter with a default argument shall
680 // have default arguments supplied in this or previous
681 // declarations. A default argument shall not be redefined
682 // by a later declaration (not even to the same value).
683 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000684 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000685 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000686 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000687 if (Param->isInvalidDecl())
688 /* We already complained about this parameter. */;
689 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000690 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000691 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000692 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000693 else
Mike Stump11289f42009-09-09 15:08:12 +0000694 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000695 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000696
Chris Lattner199abbc2008-04-08 05:04:30 +0000697 LastMissingDefaultArg = p;
698 }
699 }
700
701 if (LastMissingDefaultArg > 0) {
702 // Some default arguments were missing. Clear out all of the
703 // default arguments up to (and including) the last missing
704 // default argument, so that we leave the function parameters
705 // in a semantically valid state.
706 for (p = 0; p <= LastMissingDefaultArg; ++p) {
707 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000708 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000709 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 }
711 }
712 }
713}
Douglas Gregor556877c2008-04-13 21:30:24 +0000714
Richard Smitheb3c10c2011-10-01 02:31:28 +0000715// CheckConstexprParameterTypes - Check whether a function's parameter types
716// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000717// diagnostic and return false.
718static bool CheckConstexprParameterTypes(Sema &SemaRef,
719 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000720 unsigned ArgIndex = 0;
721 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000722 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
723 e = FT->param_type_end();
724 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000725 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
726 SourceLocation ParamLoc = PD->getLocation();
727 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000728 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000729 diag::err_constexpr_non_literal_param,
730 ArgIndex+1, PD->getSourceRange(),
731 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000732 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000733 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000734 return true;
735}
736
737/// \brief Get diagnostic %select index for tag kind for
738/// record diagnostic message.
739/// WARNING: Indexes apply to particular diagnostics only!
740///
741/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000742static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000743 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000744 case TTK_Struct: return 0;
745 case TTK_Interface: return 1;
746 case TTK_Class: return 2;
747 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000748 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000749}
750
751// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
752// the requirements of a constexpr function definition or a constexpr
753// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000754// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000755//
Richard Smith3607ffe2012-02-13 03:54:03 +0000756// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
757bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000758 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
759 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000760 // C++11 [dcl.constexpr]p4:
761 // The definition of a constexpr constructor shall satisfy the following
762 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000763 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000764 const CXXRecordDecl *RD = MD->getParent();
765 if (RD->getNumVBases()) {
766 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
767 << isa<CXXConstructorDecl>(NewFD)
768 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000769 for (const auto &I : RD->vbases())
770 Diag(I.getLocStart(),
771 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000772 return false;
773 }
Richard Smith7971b692012-01-13 04:54:00 +0000774 }
775
776 if (!isa<CXXConstructorDecl>(NewFD)) {
777 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778 // The definition of a constexpr function shall satisfy the following
779 // constraints:
780 // - it shall not be virtual;
781 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
782 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000783 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000784
Richard Smith3607ffe2012-02-13 03:54:03 +0000785 // If it's not obvious why this function is virtual, find an overridden
786 // function which uses the 'virtual' keyword.
787 const CXXMethodDecl *WrittenVirtual = Method;
788 while (!WrittenVirtual->isVirtualAsWritten())
789 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
790 if (WrittenVirtual != Method)
791 Diag(WrittenVirtual->getLocation(),
792 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793 return false;
794 }
795
796 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000797 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000798 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000799 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000800 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 }
803
Richard Smith7971b692012-01-13 04:54:00 +0000804 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000805 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000806 return false;
807
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808 return true;
809}
810
811/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000812/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000813///
Richard Smithd9f663b2013-04-22 15:31:51 +0000814/// \return true if the body is OK (maybe only as an extension), false if we
815/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000817 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
818 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
820 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000821 for (const auto *DclIt : DS->decls()) {
822 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823 case Decl::StaticAssert:
824 case Decl::Using:
825 case Decl::UsingShadow:
826 case Decl::UsingDirective:
827 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000828 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000829 // - static_assert-declarations
830 // - using-declarations,
831 // - using-directives,
832 continue;
833
834 case Decl::Typedef:
835 case Decl::TypeAlias: {
836 // - typedef declarations and alias-declarations that do not define
837 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000838 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000839 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
840 // Don't allow variably-modified types in constexpr functions.
841 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
842 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
843 << TL.getSourceRange() << TL.getType()
844 << isa<CXXConstructorDecl>(Dcl);
845 return false;
846 }
847 continue;
848 }
849
850 case Decl::Enum:
851 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000852 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000853 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000854 SemaRef.Diag(DS->getLocStart(),
855 SemaRef.getLangOpts().CPlusPlus1y
856 ? diag::warn_cxx11_compat_constexpr_type_definition
857 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000858 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000859 continue;
860
Richard Smithd9f663b2013-04-22 15:31:51 +0000861 case Decl::EnumConstant:
862 case Decl::IndirectField:
863 case Decl::ParmVar:
864 // These can only appear with other declarations which are banned in
865 // C++11 and permitted in C++1y, so ignore them.
866 continue;
867
868 case Decl::Var: {
869 // C++1y [dcl.constexpr]p3 allows anything except:
870 // a definition of a variable of non-literal type or of static or
871 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000872 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000873 if (VD->isThisDeclarationADefinition()) {
874 if (VD->isStaticLocal()) {
875 SemaRef.Diag(VD->getLocation(),
876 diag::err_constexpr_local_var_static)
877 << isa<CXXConstructorDecl>(Dcl)
878 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
879 return false;
880 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000881 if (!VD->getType()->isDependentType() &&
882 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000883 VD->getLocation(), VD->getType(),
884 diag::err_constexpr_local_var_non_literal_type,
885 isa<CXXConstructorDecl>(Dcl)))
886 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000887 if (!VD->getType()->isDependentType() &&
888 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000889 SemaRef.Diag(VD->getLocation(),
890 diag::err_constexpr_local_var_no_init)
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894 }
895 SemaRef.Diag(VD->getLocation(),
896 SemaRef.getLangOpts().CPlusPlus1y
897 ? diag::warn_cxx11_compat_constexpr_local_var
898 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000899 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000900 continue;
901 }
902
903 case Decl::NamespaceAlias:
904 case Decl::Function:
905 // These are disallowed in C++11 and permitted in C++1y. Allow them
906 // everywhere as an extension.
907 if (!Cxx1yLoc.isValid())
908 Cxx1yLoc = DS->getLocStart();
909 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000910
911 default:
912 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
913 << isa<CXXConstructorDecl>(Dcl);
914 return false;
915 }
916 }
917
918 return true;
919}
920
921/// Check that the given field is initialized within a constexpr constructor.
922///
923/// \param Dcl The constexpr constructor being checked.
924/// \param Field The field being checked. This may be a member of an anonymous
925/// struct or union nested within the class being checked.
926/// \param Inits All declarations, including anonymous struct/union members and
927/// indirect members, for which any initialization was provided.
928/// \param Diagnosed Set to true if an error is produced.
929static void CheckConstexprCtorInitializer(Sema &SemaRef,
930 const FunctionDecl *Dcl,
931 FieldDecl *Field,
932 llvm::SmallSet<Decl*, 16> &Inits,
933 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000934 if (Field->isInvalidDecl())
935 return;
936
Douglas Gregor556e5862011-10-10 17:22:13 +0000937 if (Field->isUnnamedBitfield())
938 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000939
Richard Smithab44d5b2013-12-10 08:25:00 +0000940 // Anonymous unions with no variant members and empty anonymous structs do not
941 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
942 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000943 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000944 (Field->getType()->isUnionType()
945 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
946 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000947 return;
948
Richard Smitheb3c10c2011-10-01 02:31:28 +0000949 if (!Inits.count(Field)) {
950 if (!Diagnosed) {
951 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
952 Diagnosed = true;
953 }
954 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
955 } else if (Field->isAnonymousStructOrUnion()) {
956 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000957 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000958 // If an anonymous union contains an anonymous struct of which any member
959 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000960 if (!RD->isUnion() || Inits.count(I))
961 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000962 }
963}
964
Richard Smithd9f663b2013-04-22 15:31:51 +0000965/// Check the provided statement is allowed in a constexpr function
966/// definition.
967static bool
968CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000969 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000970 SourceLocation &Cxx1yLoc) {
971 // - its function-body shall be [...] a compound-statement that contains only
972 switch (S->getStmtClass()) {
973 case Stmt::NullStmtClass:
974 // - null statements,
975 return true;
976
977 case Stmt::DeclStmtClass:
978 // - static_assert-declarations
979 // - using-declarations,
980 // - using-directives,
981 // - typedef declarations and alias-declarations that do not define
982 // classes or enumerations,
983 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
984 return false;
985 return true;
986
987 case Stmt::ReturnStmtClass:
988 // - and exactly one return statement;
989 if (isa<CXXConstructorDecl>(Dcl)) {
990 // C++1y allows return statements in constexpr constructors.
991 if (!Cxx1yLoc.isValid())
992 Cxx1yLoc = S->getLocStart();
993 return true;
994 }
995
996 ReturnStmts.push_back(S->getLocStart());
997 return true;
998
999 case Stmt::CompoundStmtClass: {
1000 // C++1y allows compound-statements.
1001 if (!Cxx1yLoc.isValid())
1002 Cxx1yLoc = S->getLocStart();
1003
1004 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001005 for (auto *BodyIt : CompStmt->body()) {
1006 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001007 Cxx1yLoc))
1008 return false;
1009 }
1010 return true;
1011 }
1012
1013 case Stmt::AttributedStmtClass:
1014 if (!Cxx1yLoc.isValid())
1015 Cxx1yLoc = S->getLocStart();
1016 return true;
1017
1018 case Stmt::IfStmtClass: {
1019 // C++1y allows if-statements.
1020 if (!Cxx1yLoc.isValid())
1021 Cxx1yLoc = S->getLocStart();
1022
1023 IfStmt *If = cast<IfStmt>(S);
1024 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1025 Cxx1yLoc))
1026 return false;
1027 if (If->getElse() &&
1028 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1029 Cxx1yLoc))
1030 return false;
1031 return true;
1032 }
1033
1034 case Stmt::WhileStmtClass:
1035 case Stmt::DoStmtClass:
1036 case Stmt::ForStmtClass:
1037 case Stmt::CXXForRangeStmtClass:
1038 case Stmt::ContinueStmtClass:
1039 // C++1y allows all of these. We don't allow them as extensions in C++11,
1040 // because they don't make sense without variable mutation.
1041 if (!SemaRef.getLangOpts().CPlusPlus1y)
1042 break;
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045 for (Stmt::child_range Children = S->children(); Children; ++Children)
1046 if (*Children &&
1047 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 return true;
1051
1052 case Stmt::SwitchStmtClass:
1053 case Stmt::CaseStmtClass:
1054 case Stmt::DefaultStmtClass:
1055 case Stmt::BreakStmtClass:
1056 // C++1y allows switch-statements, and since they don't need variable
1057 // mutation, we can reasonably allow them in C++11 as an extension.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 for (Stmt::child_range Children = S->children(); Children; ++Children)
1061 if (*Children &&
1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063 Cxx1yLoc))
1064 return false;
1065 return true;
1066
1067 default:
1068 if (!isa<Expr>(S))
1069 break;
1070
1071 // C++1y allows expression-statements.
1072 if (!Cxx1yLoc.isValid())
1073 Cxx1yLoc = S->getLocStart();
1074 return true;
1075 }
1076
1077 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1078 << isa<CXXConstructorDecl>(Dcl);
1079 return false;
1080}
1081
Richard Smitheb3c10c2011-10-01 02:31:28 +00001082/// Check the body for the given constexpr function declaration only contains
1083/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1084///
1085/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001086bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001087 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001088 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001089 // The definition of a constexpr function shall satisfy the following
1090 // constraints: [...]
1091 // - its function-body shall be = delete, = default, or a
1092 // compound-statement
1093 //
Richard Smith74388b42012-02-04 00:33:54 +00001094 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001095 // In the definition of a constexpr constructor, [...]
1096 // - its function-body shall not be a function-try-block;
1097 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1098 << isa<CXXConstructorDecl>(Dcl);
1099 return false;
1100 }
1101
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001102 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001103
1104 // - its function-body shall be [...] a compound-statement that contains only
1105 // [... list of cases ...]
1106 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1107 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001108 for (auto *BodyIt : CompBody->body()) {
1109 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001110 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001111 }
1112
Richard Smithd9f663b2013-04-22 15:31:51 +00001113 if (Cxx1yLoc.isValid())
1114 Diag(Cxx1yLoc,
1115 getLangOpts().CPlusPlus1y
1116 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1117 : diag::ext_constexpr_body_invalid_stmt)
1118 << isa<CXXConstructorDecl>(Dcl);
1119
Richard Smitheb3c10c2011-10-01 02:31:28 +00001120 if (const CXXConstructorDecl *Constructor
1121 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1122 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001123 // DR1359:
1124 // - every non-variant non-static data member and base class sub-object
1125 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001126 // DR1460:
1127 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001128 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001130 if (Constructor->getNumCtorInitializers() == 0 &&
1131 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1133 return false;
1134 }
Richard Smithf368fb42011-10-10 16:38:04 +00001135 } else if (!Constructor->isDependentContext() &&
1136 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001137 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1138
1139 // Skip detailed checking if we have enough initializers, and we would
1140 // allow at most one initializer per member.
1141 bool AnyAnonStructUnionMembers = false;
1142 unsigned Fields = 0;
1143 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1144 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001145 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001146 AnyAnonStructUnionMembers = true;
1147 break;
1148 }
1149 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001150 // DR1460:
1151 // - if the class is a union-like class, but is not a union, for each of
1152 // its anonymous union members having variant members, exactly one of
1153 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001154 if (AnyAnonStructUnionMembers ||
1155 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1156 // Check initialization of non-static data members. Base classes are
1157 // always initialized so do not need to be checked. Dependent bases
1158 // might not have initializers in the member initializer list.
1159 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001160 for (const auto *I: Constructor->inits()) {
1161 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001162 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001163 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001164 Inits.insert(ID->chain_begin(), ID->chain_end());
1165 }
1166
1167 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001168 for (auto *I : RD->fields())
1169 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001170 if (Diagnosed)
1171 return false;
1172 }
1173 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001174 } else {
1175 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001176 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001177 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001178 // otherwise if there's no return statement, the function cannot
1179 // be used in a core constant expression.
Richard Smith06ffb452014-04-22 23:14:23 +00001180 bool OK = getLangOpts().CPlusPlus1y &&
1181 (Dcl->getReturnType()->isVoidType() ||
1182 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001183 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001184 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1185 : diag::err_constexpr_body_no_return);
1186 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001187 }
1188 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001189 Diag(ReturnStmts.back(),
1190 getLangOpts().CPlusPlus1y
1191 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1192 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001193 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1194 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001195 }
1196 }
1197
Richard Smith74388b42012-02-04 00:33:54 +00001198 // C++11 [dcl.constexpr]p5:
1199 // if no function argument values exist such that the function invocation
1200 // substitution would produce a constant expression, the program is
1201 // ill-formed; no diagnostic required.
1202 // C++11 [dcl.constexpr]p3:
1203 // - every constructor call and implicit conversion used in initializing the
1204 // return value shall be one of those allowed in a constant expression.
1205 // C++11 [dcl.constexpr]p4:
1206 // - every constructor involved in initializing non-static data members and
1207 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001208 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001209 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001210 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001211 << isa<CXXConstructorDecl>(Dcl);
1212 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1213 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001214 // Don't return false here: we allow this for compatibility in
1215 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001216 }
1217
Richard Smitheb3c10c2011-10-01 02:31:28 +00001218 return true;
1219}
1220
Douglas Gregor61956c42008-10-31 09:07:45 +00001221/// isCurrentClassName - Determine whether the identifier II is the
1222/// name of the class type currently being defined. In the case of
1223/// nested classes, this will only return true if II is the name of
1224/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001225bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1226 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001227 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001228
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001229 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001230 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001231 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001232 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1233 } else
1234 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1235
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001236 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001237 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001238 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001239}
1240
Richard Smithfb8b7b92013-10-15 00:00:26 +00001241/// \brief Determine whether the identifier II is a typo for the name of
1242/// the class type currently being defined. If so, update it to the identifier
1243/// that should have been used.
1244bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1245 assert(getLangOpts().CPlusPlus && "No class names in C!");
1246
1247 if (!getLangOpts().SpellChecking)
1248 return false;
1249
1250 CXXRecordDecl *CurDecl;
1251 if (SS && SS->isSet() && !SS->isInvalid()) {
1252 DeclContext *DC = computeDeclContext(*SS, true);
1253 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1254 } else
1255 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1256
1257 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1258 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1259 < II->getLength()) {
1260 II = CurDecl->getIdentifier();
1261 return true;
1262 }
1263
1264 return false;
1265}
1266
Douglas Gregordc974572012-11-10 07:24:09 +00001267/// \brief Determine whether the given class is a base class of the given
1268/// class, including looking at dependent bases.
1269static bool findCircularInheritance(const CXXRecordDecl *Class,
1270 const CXXRecordDecl *Current) {
1271 SmallVector<const CXXRecordDecl*, 8> Queue;
1272
1273 Class = Class->getCanonicalDecl();
1274 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001275 for (const auto &I : Current->bases()) {
1276 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001277 if (!Base)
1278 continue;
1279
1280 Base = Base->getDefinition();
1281 if (!Base)
1282 continue;
1283
1284 if (Base->getCanonicalDecl() == Class)
1285 return true;
1286
1287 Queue.push_back(Base);
1288 }
1289
1290 if (Queue.empty())
1291 return false;
1292
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001293 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001294 }
1295
1296 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001297}
1298
Mike Stump11289f42009-09-09 15:08:12 +00001299/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001300///
1301/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1302/// and returns NULL otherwise.
1303CXXBaseSpecifier *
1304Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1305 SourceRange SpecifierRange,
1306 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001307 TypeSourceInfo *TInfo,
1308 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001309 QualType BaseType = TInfo->getType();
1310
Douglas Gregor463421d2009-03-03 04:44:36 +00001311 // C++ [class.union]p1:
1312 // A union shall not have base classes.
1313 if (Class->isUnion()) {
1314 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1315 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001316 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001317 }
1318
Douglas Gregor752a5952011-01-03 22:36:02 +00001319 if (EllipsisLoc.isValid() &&
1320 !TInfo->getType()->containsUnexpandedParameterPack()) {
1321 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1322 << TInfo->getTypeLoc().getSourceRange();
1323 EllipsisLoc = SourceLocation();
1324 }
Douglas Gregor62004702012-11-10 01:18:17 +00001325
1326 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1327
1328 if (BaseType->isDependentType()) {
1329 // Make sure that we don't have circular inheritance among our dependent
1330 // bases. For non-dependent bases, the check for completeness below handles
1331 // this.
1332 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1333 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1334 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001335 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001336 Diag(BaseLoc, diag::err_circular_inheritance)
1337 << BaseType << Context.getTypeDeclType(Class);
1338
1339 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1340 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1341 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001342
1343 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001344 }
1345 }
1346
Mike Stump11289f42009-09-09 15:08:12 +00001347 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001348 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001349 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001350 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001351
1352 // Base specifiers must be record types.
1353 if (!BaseType->isRecordType()) {
1354 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001355 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001356 }
1357
1358 // C++ [class.union]p1:
1359 // A union shall not be used as a base class.
1360 if (BaseType->isUnionType()) {
1361 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001362 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001363 }
1364
1365 // C++ [class.derived]p2:
1366 // The class-name in a base-specifier shall not be an incompletely
1367 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001368 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001369 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001370 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001371 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001372 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001373
Eli Friedmanc96d4962009-08-15 21:55:26 +00001374 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001375 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001376 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001377 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001378 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001379 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001380 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001381
David Majnemer9b1754d2013-11-02 12:00:36 +00001382 // A class which contains a flexible array member is not suitable for use as a
1383 // base class:
1384 // - If the layout determines that a base comes before another base,
1385 // the flexible array member would index into the subsequent base.
1386 // - If the layout determines that base comes before the derived class,
1387 // the flexible array member would index into the derived class.
1388 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1389 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1390 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001391 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001392 }
1393
Anders Carlsson65c76d32011-03-25 14:55:14 +00001394 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001395 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001396 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001397 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001398 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001399 << CXXBaseDecl->getDeclName()
1400 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001401 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1402 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001403 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001404 }
1405
John McCall3696dcb2010-08-17 07:23:57 +00001406 if (BaseDecl->isInvalidDecl())
1407 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001408
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001409 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001410 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001411 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001412 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001413}
1414
Douglas Gregor556877c2008-04-13 21:30:24 +00001415/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1416/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001417/// example:
1418/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001419/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001420BaseResult
John McCall48871652010-08-21 09:40:31 +00001421Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001422 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001423 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001424 ParsedType basetype, SourceLocation BaseLoc,
1425 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001426 if (!classdecl)
1427 return true;
1428
Douglas Gregorc40290e2009-03-09 23:48:35 +00001429 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001430 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001431 if (!Class)
1432 return true;
1433
David Majnemer5ef4fe72014-06-13 06:43:46 +00001434 // We haven't yet attached the base specifiers.
1435 Class->setIsParsingBaseSpecifiers();
1436
Richard Smith4c96e992013-02-19 23:47:15 +00001437 // We do not support any C++11 attributes on base-specifiers yet.
1438 // Diagnose any attributes we see.
1439 if (!Attributes.empty()) {
1440 for (AttributeList *Attr = Attributes.getList(); Attr;
1441 Attr = Attr->getNext()) {
1442 if (Attr->isInvalid() ||
1443 Attr->getKind() == AttributeList::IgnoredAttribute)
1444 continue;
1445 Diag(Attr->getLoc(),
1446 Attr->getKind() == AttributeList::UnknownAttribute
1447 ? diag::warn_unknown_attribute_ignored
1448 : diag::err_base_specifier_attribute)
1449 << Attr->getName();
1450 }
1451 }
1452
Craig Topperc3ec1492014-05-26 06:22:03 +00001453 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001454 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001455
Douglas Gregor752a5952011-01-03 22:36:02 +00001456 if (EllipsisLoc.isInvalid() &&
1457 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001458 UPPC_BaseType))
1459 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001460
Douglas Gregor463421d2009-03-03 04:44:36 +00001461 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001462 Virtual, Access, TInfo,
1463 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001464 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001465 else
1466 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001467
Douglas Gregor463421d2009-03-03 04:44:36 +00001468 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001469}
Douglas Gregor556877c2008-04-13 21:30:24 +00001470
Douglas Gregor463421d2009-03-03 04:44:36 +00001471/// \brief Performs the actual work of attaching the given base class
1472/// specifiers to a C++ class.
1473bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1474 unsigned NumBases) {
1475 if (NumBases == 0)
1476 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001477
1478 // Used to keep track of which base types we have already seen, so
1479 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001480 // that the key is always the unqualified canonical type of the base
1481 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001482 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1483
1484 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001485 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001486 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001487 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001488 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001489 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001490 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001491
1492 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1493 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001494 // C++ [class.mi]p3:
1495 // A class shall not be specified as a direct base class of a
1496 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001497 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001498 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001499 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001500 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001501
1502 // Delete the duplicate base class specifier; we're going to
1503 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001504 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001505
1506 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001507 } else {
1508 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001509 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001510 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001511 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1512 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1513 if (Class->isInterface() &&
1514 (!RD->isInterface() ||
1515 KnownBase->getAccessSpecifier() != AS_public)) {
1516 // The Microsoft extension __interface does not permit bases that
1517 // are not themselves public interfaces.
1518 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1519 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1520 << RD->getSourceRange();
1521 Invalid = true;
1522 }
1523 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001524 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001525 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001526 }
1527 }
1528
1529 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001530 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001531
1532 // Delete the remaining (good) base class specifiers, since their
1533 // data has been copied into the CXXRecordDecl.
1534 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001535 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001536
1537 return Invalid;
1538}
1539
1540/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1541/// class, after checking whether there are any duplicate base
1542/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001543void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001544 unsigned NumBases) {
1545 if (!ClassDecl || !Bases || !NumBases)
1546 return;
1547
1548 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001549 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001550}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001551
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552/// \brief Determine whether the type \p Derived is a C++ class that is
1553/// derived from the type \p Base.
1554bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001555 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001556 return false;
John McCalle78aac42010-03-10 03:28:59 +00001557
Douglas Gregor45bb4832013-03-26 23:36:30 +00001558 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001559 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001560 return false;
1561
Douglas Gregor45bb4832013-03-26 23:36:30 +00001562 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001563 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001564 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001565
1566 // If either the base or the derived type is invalid, don't try to
1567 // check whether one is derived from the other.
1568 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1569 return false;
1570
John McCall67da35c2010-02-04 22:26:26 +00001571 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1572 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001573}
1574
1575/// \brief Determine whether the type \p Derived is a C++ class that is
1576/// derived from the type \p Base.
1577bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001579 return false;
1580
Douglas Gregor45bb4832013-03-26 23:36:30 +00001581 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001582 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001583 return false;
1584
Douglas Gregor45bb4832013-03-26 23:36:30 +00001585 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001586 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001587 return false;
1588
Douglas Gregor36d1b142009-10-06 17:59:45 +00001589 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1590}
1591
Anders Carlssona70cff62010-04-24 19:06:50 +00001592void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001593 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001594 assert(BasePathArray.empty() && "Base path array must be empty!");
1595 assert(Paths.isRecordingPaths() && "Must record paths!");
1596
1597 const CXXBasePath &Path = Paths.front();
1598
1599 // We first go backward and check if we have a virtual base.
1600 // FIXME: It would be better if CXXBasePath had the base specifier for
1601 // the nearest virtual base.
1602 unsigned Start = 0;
1603 for (unsigned I = Path.size(); I != 0; --I) {
1604 if (Path[I - 1].Base->isVirtual()) {
1605 Start = I - 1;
1606 break;
1607 }
1608 }
1609
1610 // Now add all bases.
1611 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001612 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001613}
1614
Douglas Gregor88d292c2010-05-13 16:44:06 +00001615/// \brief Determine whether the given base path includes a virtual
1616/// base class.
John McCallcf142162010-08-07 06:22:56 +00001617bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1618 for (CXXCastPath::const_iterator B = BasePath.begin(),
1619 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001620 B != BEnd; ++B)
1621 if ((*B)->isVirtual())
1622 return true;
1623
1624 return false;
1625}
1626
Douglas Gregor36d1b142009-10-06 17:59:45 +00001627/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1628/// conversion (where Derived and Base are class types) is
1629/// well-formed, meaning that the conversion is unambiguous (and
1630/// that all of the base classes are accessible). Returns true
1631/// and emits a diagnostic if the code is ill-formed, returns false
1632/// otherwise. Loc is the location where this routine should point to
1633/// if there is an error, and Range is the source range to highlight
1634/// if there is an error.
1635bool
1636Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001637 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638 unsigned AmbigiousBaseConvID,
1639 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001640 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001641 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001642 // First, determine whether the path from Derived to Base is
1643 // ambiguous. This is slightly more expensive than checking whether
1644 // the Derived to Base conversion exists, because here we need to
1645 // explore multiple paths to determine if there is an ambiguity.
1646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1647 /*DetectVirtual=*/false);
1648 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1649 assert(DerivationOkay &&
1650 "Can only be used with a derived-to-base conversion");
1651 (void)DerivationOkay;
1652
1653 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001654 if (InaccessibleBaseID) {
1655 // Check that the base class can be accessed.
1656 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1657 InaccessibleBaseID)) {
1658 case AR_inaccessible:
1659 return true;
1660 case AR_accessible:
1661 case AR_dependent:
1662 case AR_delayed:
1663 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001664 }
John McCall5b0829a2010-02-10 09:31:12 +00001665 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001666
1667 // Build a base path if necessary.
1668 if (BasePath)
1669 BuildBasePathArray(Paths, *BasePath);
1670 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001671 }
1672
David Majnemer626032f2013-06-22 06:43:58 +00001673 if (AmbigiousBaseConvID) {
1674 // We know that the derived-to-base conversion is ambiguous, and
1675 // we're going to produce a diagnostic. Perform the derived-to-base
1676 // search just one more time to compute all of the possible paths so
1677 // that we can print them out. This is more expensive than any of
1678 // the previous derived-to-base checks we've done, but at this point
1679 // performance isn't as much of an issue.
1680 Paths.clear();
1681 Paths.setRecordingPaths(true);
1682 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1683 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1684 (void)StillOkay;
1685
1686 // Build up a textual representation of the ambiguous paths, e.g.,
1687 // D -> B -> A, that will be used to illustrate the ambiguous
1688 // conversions in the diagnostic. We only print one of the paths
1689 // to each base class subobject.
1690 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1691
1692 Diag(Loc, AmbigiousBaseConvID)
1693 << Derived << Base << PathDisplayStr << Range << Name;
1694 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001695 return true;
1696}
1697
1698bool
1699Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001700 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001701 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001702 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001704 IgnoreAccess ? 0
1705 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001706 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001707 Loc, Range, DeclarationName(),
1708 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709}
1710
1711
1712/// @brief Builds a string representing ambiguous paths from a
1713/// specific derived class to different subobjects of the same base
1714/// class.
1715///
1716/// This function builds a string that can be used in error messages
1717/// to show the different paths that one can take through the
1718/// inheritance hierarchy to go from the derived class to different
1719/// subobjects of a base class. The result looks something like this:
1720/// @code
1721/// struct D -> struct B -> struct A
1722/// struct D -> struct C -> struct A
1723/// @endcode
1724std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1725 std::string PathDisplayStr;
1726 std::set<unsigned> DisplayedPaths;
1727 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1728 Path != Paths.end(); ++Path) {
1729 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1730 // We haven't displayed a path to this particular base
1731 // class subobject yet.
1732 PathDisplayStr += "\n ";
1733 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1734 for (CXXBasePath::const_iterator Element = Path->begin();
1735 Element != Path->end(); ++Element)
1736 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1737 }
1738 }
1739
1740 return PathDisplayStr;
1741}
1742
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001743//===----------------------------------------------------------------------===//
1744// C++ class member Handling
1745//===----------------------------------------------------------------------===//
1746
Abramo Bagnarad7340582010-06-05 05:09:32 +00001747/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001748bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1749 SourceLocation ASLoc,
1750 SourceLocation ColonLoc,
1751 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001752 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001753 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001754 ASLoc, ColonLoc);
1755 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001756 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001757}
1758
Richard Smith18f07db2012-08-06 03:25:17 +00001759/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001760void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001761 if (D->isInvalidDecl())
1762 return;
1763
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001764 // We only care about "override" and "final" declarations.
1765 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1766 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001767
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001768 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001769
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001770 // We can't check dependent instance methods.
1771 if (MD && MD->isInstance() &&
1772 (MD->getParent()->hasAnyDependentBases() ||
1773 MD->getType()->isDependentType()))
1774 return;
1775
1776 if (MD && !MD->isVirtual()) {
1777 // If we have a non-virtual method, check if if hides a virtual method.
1778 // (In that case, it's most likely the method has the wrong type.)
1779 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1780 FindHiddenVirtualMethods(MD, OverloadedMethods);
1781
1782 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001783 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1784 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001785 diag::override_keyword_hides_virtual_member_function)
1786 << "override" << (OverloadedMethods.size() > 1);
1787 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001788 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001789 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001790 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1791 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001792 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001793 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1794 MD->setInvalidDecl();
1795 return;
1796 }
1797 // Fall through into the general case diagnostic.
1798 // FIXME: We might want to attempt typo correction here.
1799 }
1800
1801 if (!MD || !MD->isVirtual()) {
1802 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1803 Diag(OA->getLocation(),
1804 diag::override_keyword_only_allowed_on_virtual_member_functions)
1805 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1806 D->dropAttr<OverrideAttr>();
1807 }
1808 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1809 Diag(FA->getLocation(),
1810 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001811 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1812 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001813 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001814 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001815 return;
1816 }
Richard Smith18f07db2012-08-06 03:25:17 +00001817
Richard Smith18f07db2012-08-06 03:25:17 +00001818 // C++11 [class.virtual]p5:
1819 // If a virtual function is marked with the virt-specifier override and
1820 // does not override a member function of a base class, the program is
1821 // ill-formed.
1822 bool HasOverriddenMethods =
1823 MD->begin_overridden_methods() != MD->end_overridden_methods();
1824 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1825 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1826 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001827}
1828
Richard Smith18f07db2012-08-06 03:25:17 +00001829/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001830/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001831/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001832bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1833 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001834 FinalAttr *FA = Old->getAttr<FinalAttr>();
1835 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001836 return false;
1837
1838 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001839 << New->getDeclName()
1840 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1842 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001843}
1844
Daniel Jasper0baec5492012-06-06 08:32:04 +00001845static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001846 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1847 // FIXME: Destruction of ObjC lifetime types has side-effects.
1848 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1849 return !RD->isCompleteDefinition() ||
1850 !RD->hasTrivialDefaultConstructor() ||
1851 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001852 return false;
1853}
1854
John McCall5e77d762013-04-16 07:28:30 +00001855static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001856 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001857 if (it->isDeclspecPropertyAttribute())
1858 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001859 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001860}
1861
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001862/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1863/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001864/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001865/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1866/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001867NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001868Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001869 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001870 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001871 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001872 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001873 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1874 DeclarationName Name = NameInfo.getName();
1875 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001876
1877 // For anonymous bitfields, the location should point to the type.
1878 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001879 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001880
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001881 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001882
John McCallb1cd7da2010-06-04 08:34:12 +00001883 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001884 assert(!DS.isFriendSpecified());
1885
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001886 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001887
John McCalldb632ac2012-09-25 07:32:39 +00001888 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1889 // The Microsoft extension __interface only permits public member functions
1890 // and prohibits constructors, destructors, operators, non-public member
1891 // functions, static methods and data members.
1892 unsigned InvalidDecl;
1893 bool ShowDeclName = true;
1894 if (!isFunc)
1895 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1896 else if (AS != AS_public)
1897 InvalidDecl = 2;
1898 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1899 InvalidDecl = 3;
1900 else switch (Name.getNameKind()) {
1901 case DeclarationName::CXXConstructorName:
1902 InvalidDecl = 4;
1903 ShowDeclName = false;
1904 break;
1905
1906 case DeclarationName::CXXDestructorName:
1907 InvalidDecl = 5;
1908 ShowDeclName = false;
1909 break;
1910
1911 case DeclarationName::CXXOperatorName:
1912 case DeclarationName::CXXConversionFunctionName:
1913 InvalidDecl = 6;
1914 break;
1915
1916 default:
1917 InvalidDecl = 0;
1918 break;
1919 }
1920
1921 if (InvalidDecl) {
1922 if (ShowDeclName)
1923 Diag(Loc, diag::err_invalid_member_in_interface)
1924 << (InvalidDecl-1) << Name;
1925 else
1926 Diag(Loc, diag::err_invalid_member_in_interface)
1927 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001928 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001929 }
1930 }
1931
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001932 // C++ 9.2p6: A member shall not be declared to have automatic storage
1933 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001934 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1935 // data members and cannot be applied to names declared const or static,
1936 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001938 case DeclSpec::SCS_unspecified:
1939 case DeclSpec::SCS_typedef:
1940 case DeclSpec::SCS_static:
1941 break;
1942 case DeclSpec::SCS_mutable:
1943 if (isFunc) {
1944 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Richard Smithb4a9e862013-04-12 22:46:28 +00001946 // FIXME: It would be nicer if the keyword was ignored only for this
1947 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001948 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001949 }
1950 break;
1951 default:
1952 Diag(DS.getStorageClassSpecLoc(),
1953 diag::err_storageclass_invalid_for_member);
1954 D.getMutableDeclSpec().ClearStorageClassSpecs();
1955 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001956 }
1957
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001958 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1959 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001960 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001961
David Blaikie35506f82013-01-30 01:22:18 +00001962 if (DS.isConstexprSpecified() && isInstField) {
1963 SemaDiagnosticBuilder B =
1964 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1965 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1966 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00001967 B << 0 << 0;
1968 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1969 B << FixItHint::CreateRemoval(ConstexprLoc);
1970 else {
1971 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1972 D.getMutableDeclSpec().ClearConstexprSpec();
1973 const char *PrevSpec;
1974 unsigned DiagID;
1975 bool Failed = D.getMutableDeclSpec().SetTypeQual(
1976 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1977 (void)Failed;
1978 assert(!Failed && "Making a constexpr member const shouldn't fail");
1979 }
David Blaikie35506f82013-01-30 01:22:18 +00001980 } else {
1981 B << 1;
1982 const char *PrevSpec;
1983 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001984 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001985 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1986 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001987 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001988 "This is the only DeclSpec that should fail to be applied");
1989 B << 1;
1990 } else {
1991 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1992 isInstField = false;
1993 }
1994 }
1995 }
1996
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001997 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001998 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001999 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002000
2001 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002002 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002003 Diag(Loc, diag::err_bad_variable_name)
2004 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002005 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002006 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002007
Benjamin Kramer365082d2012-05-19 16:34:46 +00002008 IdentifierInfo *II = Name.getAsIdentifierInfo();
2009
Douglas Gregor7c26c042011-09-21 14:40:46 +00002010 // Member field could not be with "template" keyword.
2011 // So TemplateParameterLists should be empty in this case.
2012 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002013 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002014 if (TemplateParams->size()) {
2015 // There is no such thing as a member field template.
2016 Diag(D.getIdentifierLoc(), diag::err_template_member)
2017 << II
2018 << SourceRange(TemplateParams->getTemplateLoc(),
2019 TemplateParams->getRAngleLoc());
2020 } else {
2021 // There is an extraneous 'template<>' for this member.
2022 Diag(TemplateParams->getTemplateLoc(),
2023 diag::err_template_member_noparams)
2024 << II
2025 << SourceRange(TemplateParams->getTemplateLoc(),
2026 TemplateParams->getRAngleLoc());
2027 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002028 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002029 }
2030
Douglas Gregora007d362010-10-13 22:19:53 +00002031 if (SS.isSet() && !SS.isInvalid()) {
2032 // The user provided a superfluous scope specifier inside a class
2033 // definition:
2034 //
2035 // class X {
2036 // int X::member;
2037 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002038 if (DeclContext *DC = computeDeclContext(SS, false))
2039 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002040 else
2041 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2042 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002043
Douglas Gregora007d362010-10-13 22:19:53 +00002044 SS.clear();
2045 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002046
John McCall5e77d762013-04-16 07:28:30 +00002047 AttributeList *MSPropertyAttr =
2048 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002049 if (MSPropertyAttr) {
2050 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2051 BitWidth, InitStyle, AS, MSPropertyAttr);
2052 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002053 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002054 isInstField = false;
2055 } else {
2056 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2057 BitWidth, InitStyle, AS);
2058 assert(Member && "HandleField never returns null");
2059 }
2060 } else {
2061 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2062
2063 Member = HandleDeclarator(S, D, TemplateParameterLists);
2064 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002065 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002066
2067 // Non-instance-fields can't have a bitfield.
2068 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002069 if (Member->isInvalidDecl()) {
2070 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002071 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002072 // C++ 9.6p3: A bit-field shall not be a static member.
2073 // "static member 'A' cannot be a bit-field"
2074 Diag(Loc, diag::err_static_not_bitfield)
2075 << Name << BitWidth->getSourceRange();
2076 } else if (isa<TypedefDecl>(Member)) {
2077 // "typedef member 'x' cannot be a bit-field"
2078 Diag(Loc, diag::err_typedef_not_bitfield)
2079 << Name << BitWidth->getSourceRange();
2080 } else {
2081 // A function typedef ("typedef int f(); f a;").
2082 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2083 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002084 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002085 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002086 }
Mike Stump11289f42009-09-09 15:08:12 +00002087
Craig Topperc3ec1492014-05-26 06:22:03 +00002088 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002089 Member->setInvalidDecl();
2090 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002091
2092 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002093
Larisse Voufo39a1e502013-08-06 01:03:05 +00002094 // If we have declared a member function template or static data member
2095 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002096 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2097 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002098 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2099 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002100 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002101
Richard Smith18f07db2012-08-06 03:25:17 +00002102 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002103 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002104 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002105 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2106 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002107
Douglas Gregorf2f08062011-03-08 17:10:18 +00002108 if (VS.getLastLocation().isValid()) {
2109 // Update the end location of a method that has a virt-specifiers.
2110 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2111 MD->setRangeEnd(VS.getLastLocation());
2112 }
Richard Smith18f07db2012-08-06 03:25:17 +00002113
Anders Carlssonc87f8612011-01-20 06:29:02 +00002114 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002115
Douglas Gregor92751d42008-11-17 22:58:34 +00002116 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002117
Daniel Jasper0baec5492012-06-06 08:32:04 +00002118 if (isInstField) {
2119 FieldDecl *FD = cast<FieldDecl>(Member);
2120 FieldCollector->Add(FD);
2121
2122 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2123 FD->getLocation())
2124 != DiagnosticsEngine::Ignored) {
2125 // Remember all explicit private FieldDecls that have a name, no side
2126 // effects and are not part of a dependent type declaration.
2127 if (!FD->isImplicit() && FD->getDeclName() &&
2128 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002129 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002130 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002131 !InitializationHasSideEffects(*FD))
2132 UnusedPrivateFields.insert(FD);
2133 }
2134 }
2135
John McCall48871652010-08-21 09:40:31 +00002136 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002137}
2138
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002139namespace {
2140 class UninitializedFieldVisitor
2141 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2142 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002143 // List of Decls to generate a warning on. Also remove Decls that become
2144 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002145 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002146 // If non-null, add a note to the warning pointing back to the constructor.
2147 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002148 public:
2149 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002150 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002151 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002152 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002153 : Inherited(S.Context), S(S), Decls(Decls),
2154 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002155
Richard Trieufd687772013-09-16 20:46:50 +00002156 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002157 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2158 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002159
Richard Trieu1bc22c12013-09-13 03:20:53 +00002160 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2161 // or union.
2162 MemberExpr *FieldME = ME;
2163
2164 Expr *Base = ME;
2165 while (isa<MemberExpr>(Base)) {
2166 ME = cast<MemberExpr>(Base);
2167
2168 if (isa<VarDecl>(ME->getMemberDecl()))
2169 return;
2170
2171 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2172 if (!FD->isAnonymousStructOrUnion())
2173 FieldME = ME;
2174
2175 Base = ME->getBase();
2176 }
2177
Richard Trieufd687772013-09-16 20:46:50 +00002178 if (!isa<CXXThisExpr>(Base))
2179 return;
2180
Richard Trieu406e65c2013-09-20 03:03:06 +00002181 ValueDecl* FoundVD = FieldME->getMemberDecl();
2182
Richard Trieuef64e942013-10-25 00:56:00 +00002183 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002184 return;
2185
Richard Trieuef64e942013-10-25 00:56:00 +00002186 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002187
Richard Trieuef64e942013-10-25 00:56:00 +00002188 // Prevent double warnings on use of unbounded references.
2189 if (IsReference != CheckReferenceOnly)
2190 return;
2191
2192 unsigned diag = IsReference
2193 ? diag::warn_reference_field_is_uninit
2194 : diag::warn_field_is_uninit;
2195 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2196 if (Constructor)
2197 S.Diag(Constructor->getLocation(),
2198 diag::note_uninit_in_this_constructor)
2199 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2200
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002201 }
2202
2203 void HandleValue(Expr *E) {
2204 E = E->IgnoreParens();
2205
2206 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002207 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002208 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002209 }
2210
2211 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2212 HandleValue(CO->getTrueExpr());
2213 HandleValue(CO->getFalseExpr());
2214 return;
2215 }
2216
2217 if (BinaryConditionalOperator *BCO =
2218 dyn_cast<BinaryConditionalOperator>(E)) {
2219 HandleValue(BCO->getCommon());
2220 HandleValue(BCO->getFalseExpr());
2221 return;
2222 }
2223
2224 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2225 switch (BO->getOpcode()) {
2226 default:
2227 return;
2228 case(BO_PtrMemD):
2229 case(BO_PtrMemI):
2230 HandleValue(BO->getLHS());
2231 return;
2232 case(BO_Comma):
2233 HandleValue(BO->getRHS());
2234 return;
2235 }
2236 }
2237 }
2238
Richard Trieu1bc22c12013-09-13 03:20:53 +00002239 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002240 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002241 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002242
2243 Inherited::VisitMemberExpr(ME);
2244 }
2245
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002246 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2247 if (E->getCastKind() == CK_LValueToRValue)
2248 HandleValue(E->getSubExpr());
2249
2250 Inherited::VisitImplicitCastExpr(E);
2251 }
2252
Richard Trieu1bc22c12013-09-13 03:20:53 +00002253 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002254 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002255 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2256 if (ICE->getCastKind() == CK_NoOp)
2257 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002258 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002259
2260 Inherited::VisitCXXConstructExpr(E);
2261 }
2262
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002263 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2264 Expr *Callee = E->getCallee();
2265 if (isa<MemberExpr>(Callee))
2266 HandleValue(Callee);
2267
2268 Inherited::VisitCXXMemberCallExpr(E);
2269 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002270
2271 void VisitBinaryOperator(BinaryOperator *E) {
2272 // If a field assignment is detected, remove the field from the
2273 // uninitiailized field set.
2274 if (E->getOpcode() == BO_Assign)
2275 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2276 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002277 if (!FD->getType()->isReferenceType())
2278 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002279
2280 Inherited::VisitBinaryOperator(E);
2281 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002282 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002283 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002284 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2285 const CXXConstructorDecl *Constructor) {
2286 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002287 return;
2288
Richard Trieuef64e942013-10-25 00:56:00 +00002289 if (!E)
2290 return;
2291
2292 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2293 E = Default->getExpr();
2294 if (!E)
2295 return;
2296 // In class initializers will point to the constructor.
2297 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2298 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002299 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieuef64e942013-10-25 00:56:00 +00002300 }
2301 }
2302
2303 // Diagnose value-uses of fields to initialize themselves, e.g.
2304 // foo(foo)
2305 // where foo is not also a parameter to the constructor.
2306 // Also diagnose across field uninitialized use such as
2307 // x(y), y(x)
2308 // TODO: implement -Wuninitialized and fold this into that framework.
2309 static void DiagnoseUninitializedFields(
2310 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2311
2312 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2313 Constructor->getLocation())
2314 == DiagnosticsEngine::Ignored) {
2315 return;
2316 }
2317
2318 if (Constructor->isInvalidDecl())
2319 return;
2320
2321 const CXXRecordDecl *RD = Constructor->getParent();
2322
2323 // Holds fields that are uninitialized.
2324 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2325
2326 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002327 for (auto *I : RD->decls()) {
2328 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002329 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002330 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002331 UninitializedFields.insert(IFD->getAnonField());
2332 }
2333 }
2334
Aaron Ballman0ad78302014-03-13 17:34:31 +00002335 for (const auto *FieldInit : Constructor->inits()) {
2336 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002337
2338 CheckInitExprContainsUninitializedFields(
2339 SemaRef, InitExpr, UninitializedFields, Constructor);
2340
Aaron Ballman0ad78302014-03-13 17:34:31 +00002341 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002342 UninitializedFields.erase(Field);
2343 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002344 }
2345} // namespace
2346
Richard Smith74108172014-01-17 03:11:34 +00002347/// \brief Enter a new C++ default initializer scope. After calling this, the
2348/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2349/// parsing or instantiating the initializer failed.
2350void Sema::ActOnStartCXXInClassMemberInitializer() {
2351 // Create a synthetic function scope to represent the call to the constructor
2352 // that notionally surrounds a use of this initializer.
2353 PushFunctionScope();
2354}
2355
2356/// \brief This is invoked after parsing an in-class initializer for a
2357/// non-static C++ class member, and after instantiating an in-class initializer
2358/// in a class template. Such actions are deferred until the class is complete.
2359void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2360 SourceLocation InitLoc,
2361 Expr *InitExpr) {
2362 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002363 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002364
Richard Smith938f40b2011-06-11 17:19:42 +00002365 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002366 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2367 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002368
2369 if (!InitExpr) {
2370 FD->setInvalidDecl();
2371 FD->removeInClassInitializer();
2372 return;
2373 }
2374
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002375 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2376 FD->setInvalidDecl();
2377 FD->removeInClassInitializer();
2378 return;
2379 }
2380
Richard Smith938f40b2011-06-11 17:19:42 +00002381 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002382 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002383 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002384 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002385 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002386 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002387 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2388 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002389 if (Init.isInvalid()) {
2390 FD->setInvalidDecl();
2391 return;
2392 }
Richard Smith938f40b2011-06-11 17:19:42 +00002393 }
2394
Richard Smith945f8d32013-01-14 22:39:08 +00002395 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002396 // The initialization of each base and member constitutes a
2397 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002398 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002399 if (Init.isInvalid()) {
2400 FD->setInvalidDecl();
2401 return;
2402 }
2403
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002404 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002405
2406 FD->setInClassInitializer(InitExpr);
2407}
2408
Douglas Gregor15e77a22009-12-31 09:10:24 +00002409/// \brief Find the direct and/or virtual base specifiers that
2410/// correspond to the given base type, for use in base initialization
2411/// within a constructor.
2412static bool FindBaseInitializer(Sema &SemaRef,
2413 CXXRecordDecl *ClassDecl,
2414 QualType BaseType,
2415 const CXXBaseSpecifier *&DirectBaseSpec,
2416 const CXXBaseSpecifier *&VirtualBaseSpec) {
2417 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002418 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002419 for (const auto &Base : ClassDecl->bases()) {
2420 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002421 // We found a direct base of this type. That's what we're
2422 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002423 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002424 break;
2425 }
2426 }
2427
2428 // Check for a virtual base class.
2429 // FIXME: We might be able to short-circuit this if we know in advance that
2430 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002431 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002432 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2433 // We haven't found a base yet; search the class hierarchy for a
2434 // virtual base class.
2435 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2436 /*DetectVirtual=*/false);
2437 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2438 BaseType, Paths)) {
2439 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2440 Path != Paths.end(); ++Path) {
2441 if (Path->back().Base->isVirtual()) {
2442 VirtualBaseSpec = Path->back().Base;
2443 break;
2444 }
2445 }
2446 }
2447 }
2448
2449 return DirectBaseSpec || VirtualBaseSpec;
2450}
2451
Sebastian Redla74948d2011-09-24 17:48:25 +00002452/// \brief Handle a C++ member initializer using braced-init-list syntax.
2453MemInitResult
2454Sema::ActOnMemInitializer(Decl *ConstructorD,
2455 Scope *S,
2456 CXXScopeSpec &SS,
2457 IdentifierInfo *MemberOrBase,
2458 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002459 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002460 SourceLocation IdLoc,
2461 Expr *InitList,
2462 SourceLocation EllipsisLoc) {
2463 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002464 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002465 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002466}
2467
2468/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002469MemInitResult
John McCall48871652010-08-21 09:40:31 +00002470Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002471 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002472 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002473 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002474 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002475 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002476 SourceLocation IdLoc,
2477 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002478 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002479 SourceLocation RParenLoc,
2480 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002481 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002482 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002483 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002484 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002485}
2486
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002487namespace {
2488
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002489// Callback to only accept typo corrections that can be a valid C++ member
2490// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002491class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002492public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002493 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2494 : ClassDecl(ClassDecl) {}
2495
Craig Toppera798a9d2014-03-02 09:32:10 +00002496 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002497 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2498 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2499 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002500 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002501 }
2502 return false;
2503 }
2504
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002505private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002506 CXXRecordDecl *ClassDecl;
2507};
2508
2509}
2510
Sebastian Redla74948d2011-09-24 17:48:25 +00002511/// \brief Handle a C++ member initializer.
2512MemInitResult
2513Sema::BuildMemInitializer(Decl *ConstructorD,
2514 Scope *S,
2515 CXXScopeSpec &SS,
2516 IdentifierInfo *MemberOrBase,
2517 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002518 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002519 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002520 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002521 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002522 if (!ConstructorD)
2523 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002524
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002525 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002526
2527 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002528 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002529 if (!Constructor) {
2530 // The user wrote a constructor initializer on a function that is
2531 // not a C++ constructor. Ignore the error for now, because we may
2532 // have more member initializers coming; we'll diagnose it just
2533 // once in ActOnMemInitializers.
2534 return true;
2535 }
2536
2537 CXXRecordDecl *ClassDecl = Constructor->getParent();
2538
2539 // C++ [class.base.init]p2:
2540 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002541 // constructor's class and, if not found in that scope, are looked
2542 // up in the scope containing the constructor's definition.
2543 // [Note: if the constructor's class contains a member with the
2544 // same name as a direct or virtual base class of the class, a
2545 // mem-initializer-id naming the member or base class and composed
2546 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002547 // mem-initializer-id for the hidden base class may be specified
2548 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002549 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002550 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002551 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002552 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002553 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002554 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002555 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2556 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002557 if (EllipsisLoc.isValid())
2558 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002559 << MemberOrBase
2560 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002561
Sebastian Redla9351792012-02-11 23:51:47 +00002562 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002563 }
Francois Pichetd583da02010-12-04 09:14:42 +00002564 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002565 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002566 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002567 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002568 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002569
2570 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002571 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002572 } else if (DS.getTypeSpecType() == TST_decltype) {
2573 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002574 } else {
2575 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2576 LookupParsedName(R, S, &SS);
2577
2578 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2579 if (!TyD) {
2580 if (R.isAmbiguous()) return true;
2581
John McCallda6841b2010-04-09 19:01:14 +00002582 // We don't want access-control diagnostics here.
2583 R.suppressDiagnostics();
2584
Douglas Gregora3b624a2010-01-19 06:46:48 +00002585 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2586 bool NotUnknownSpecialization = false;
2587 DeclContext *DC = computeDeclContext(SS, false);
2588 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2589 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2590
2591 if (!NotUnknownSpecialization) {
2592 // When the scope specifier can refer to a member of an unknown
2593 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002594 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2595 SS.getWithLocInContext(Context),
2596 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002597 if (BaseType.isNull())
2598 return true;
2599
Douglas Gregora3b624a2010-01-19 06:46:48 +00002600 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002601 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002602 }
2603 }
2604
Douglas Gregor15e77a22009-12-31 09:10:24 +00002605 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002606 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002607 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002608 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002609 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002610 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002611 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002612 // We have found a non-static data member with a similar
2613 // name to what was typed; complain and initialize that
2614 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002615 diagnoseTypo(Corr,
2616 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2617 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002618 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002619 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002620 const CXXBaseSpecifier *DirectBaseSpec;
2621 const CXXBaseSpecifier *VirtualBaseSpec;
2622 if (FindBaseInitializer(*this, ClassDecl,
2623 Context.getTypeDeclType(Type),
2624 DirectBaseSpec, VirtualBaseSpec)) {
2625 // We have found a direct or virtual base class with a
2626 // similar name to what was typed; complain and initialize
2627 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002628 diagnoseTypo(Corr,
2629 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2630 << MemberOrBase << false,
2631 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002632
Richard Smithf9b15102013-08-17 00:46:16 +00002633 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2634 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002635 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002636 diag::note_base_class_specified_here)
2637 << BaseSpec->getType()
2638 << BaseSpec->getSourceRange();
2639
Douglas Gregor15e77a22009-12-31 09:10:24 +00002640 TyD = Type;
2641 }
2642 }
2643 }
2644
Douglas Gregora3b624a2010-01-19 06:46:48 +00002645 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002646 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002647 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002648 return true;
2649 }
John McCallb5a0d312009-12-21 10:41:20 +00002650 }
2651
Douglas Gregora3b624a2010-01-19 06:46:48 +00002652 if (BaseType.isNull()) {
2653 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002654 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002655 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002656 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2657 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002658 }
2659 }
Mike Stump11289f42009-09-09 15:08:12 +00002660
John McCallbcd03502009-12-07 02:54:59 +00002661 if (!TInfo)
2662 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002663
Sebastian Redla9351792012-02-11 23:51:47 +00002664 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002665}
2666
Chandler Carruth599deef2011-09-03 01:14:15 +00002667/// Checks a member initializer expression for cases where reference (or
2668/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002669static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2670 Expr *Init,
2671 SourceLocation IdLoc) {
2672 QualType MemberTy = Member->getType();
2673
2674 // We only handle pointers and references currently.
2675 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2676 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2677 return;
2678
2679 const bool IsPointer = MemberTy->isPointerType();
2680 if (IsPointer) {
2681 if (const UnaryOperator *Op
2682 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2683 // The only case we're worried about with pointers requires taking the
2684 // address.
2685 if (Op->getOpcode() != UO_AddrOf)
2686 return;
2687
2688 Init = Op->getSubExpr();
2689 } else {
2690 // We only handle address-of expression initializers for pointers.
2691 return;
2692 }
2693 }
2694
Richard Smithe3b28bc2013-06-12 21:51:50 +00002695 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002696 // We only warn when referring to a non-reference parameter declaration.
2697 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2698 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002699 return;
2700
2701 S.Diag(Init->getExprLoc(),
2702 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2703 : diag::warn_bind_ref_member_to_parameter)
2704 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002705 } else {
2706 // Other initializers are fine.
2707 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002708 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002709
2710 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2711 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002712}
2713
John McCallfaf5fb42010-08-26 23:41:50 +00002714MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002715Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002716 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002717 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2718 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2719 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002720 "Member must be a FieldDecl or IndirectFieldDecl");
2721
Sebastian Redla9351792012-02-11 23:51:47 +00002722 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002723 return true;
2724
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002725 if (Member->isInvalidDecl())
2726 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002727
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002728 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002729 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002730 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002731 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002732 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002733 } else {
2734 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002735 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002736 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002737
Sebastian Redla9351792012-02-11 23:51:47 +00002738 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002739
Sebastian Redla9351792012-02-11 23:51:47 +00002740 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002741 // Can't check initialization for a member of dependent type or when
2742 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002743 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002744 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002745 bool InitList = false;
2746 if (isa<InitListExpr>(Init)) {
2747 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002748 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002749 }
2750
Chandler Carruthd44c3102010-12-06 09:23:57 +00002751 // Initialize the member.
2752 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002753 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2754 : InitializedEntity::InitializeMember(IndirectMember,
2755 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002756 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002757 InitList ? InitializationKind::CreateDirectList(IdLoc)
2758 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2759 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002760
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002761 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002762 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2763 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002764 if (MemberInit.isInvalid())
2765 return true;
2766
Richard Smith736a9472013-06-12 20:42:33 +00002767 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2768
Richard Smith945f8d32013-01-14 22:39:08 +00002769 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002770 // The initialization of each base and member constitutes a
2771 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002772 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002773 if (MemberInit.isInvalid())
2774 return true;
2775
Richard Smithd59b8322012-12-19 01:39:02 +00002776 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002777 }
2778
Chandler Carruthd44c3102010-12-06 09:23:57 +00002779 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002780 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2781 InitRange.getBegin(), Init,
2782 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002783 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002784 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2785 InitRange.getBegin(), Init,
2786 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002787 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002788}
2789
John McCallfaf5fb42010-08-26 23:41:50 +00002790MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002791Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002792 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002793 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002794 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002795 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002796 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002797 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002798
Sebastian Redl0501c632012-02-12 16:37:36 +00002799 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002801 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2802 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002804 }
2805
Sebastian Redla9351792012-02-11 23:51:47 +00002806 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002807 // Initialize the object.
2808 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2809 QualType(ClassDecl->getTypeForDecl(), 0));
2810 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002811 InitList ? InitializationKind::CreateDirectList(NameLoc)
2812 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2813 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002814 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002815 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002816 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002817 if (DelegationInit.isInvalid())
2818 return true;
2819
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002820 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2821 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002822
Richard Smith945f8d32013-01-14 22:39:08 +00002823 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002824 // The initialization of each base and member constitutes a
2825 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002826 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2827 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002828 if (DelegationInit.isInvalid())
2829 return true;
2830
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002831 // If we are in a dependent context, template instantiation will
2832 // perform this type-checking again. Just save the arguments that we
2833 // received in a ParenListExpr.
2834 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2835 // of the information that we have about the base
2836 // initializer. However, deconstructing the ASTs is a dicey process,
2837 // and this approach is far more likely to get the corner cases right.
2838 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002839 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002840
Sebastian Redla9351792012-02-11 23:51:47 +00002841 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002842 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002843 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002844}
2845
2846MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002847Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002848 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002849 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002850 SourceLocation BaseLoc
2851 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002852
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002853 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2854 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2855 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2856
2857 // C++ [class.base.init]p2:
2858 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002859 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002860 // of that class, the mem-initializer is ill-formed. A
2861 // mem-initializer-list can initialize a base class using any
2862 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002863 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002864
Sebastian Redla9351792012-02-11 23:51:47 +00002865 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002866 if (EllipsisLoc.isValid()) {
2867 // This is a pack expansion.
2868 if (!BaseType->containsUnexpandedParameterPack()) {
2869 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002870 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002871
Douglas Gregor44e7df62011-01-04 00:32:56 +00002872 EllipsisLoc = SourceLocation();
2873 }
2874 } else {
2875 // Check for any unexpanded parameter packs.
2876 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2877 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002878
Sebastian Redla9351792012-02-11 23:51:47 +00002879 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002880 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002881 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002882
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002883 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2885 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002886 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002887 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2888 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002889 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002890
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002891 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2892 VirtualBaseSpec);
2893
2894 // C++ [base.class.init]p2:
2895 // Unless the mem-initializer-id names a nonstatic data member of the
2896 // constructor's class or a direct or virtual base of that class, the
2897 // mem-initializer is ill-formed.
2898 if (!DirectBaseSpec && !VirtualBaseSpec) {
2899 // If the class has any dependent bases, then it's possible that
2900 // one of those types will resolve to the same type as
2901 // BaseType. Therefore, just treat this as a dependent base
2902 // class initialization. FIXME: Should we try to check the
2903 // initialization anyway? It seems odd.
2904 if (ClassDecl->hasAnyDependentBases())
2905 Dependent = true;
2906 else
2907 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2908 << BaseType << Context.getTypeDeclType(ClassDecl)
2909 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2910 }
2911 }
2912
2913 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002914 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002915
Sebastian Redla74948d2011-09-24 17:48:25 +00002916 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2917 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002918 InitRange.getBegin(), Init,
2919 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002920 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002921
2922 // C++ [base.class.init]p2:
2923 // If a mem-initializer-id is ambiguous because it designates both
2924 // a direct non-virtual base class and an inherited virtual base
2925 // class, the mem-initializer is ill-formed.
2926 if (DirectBaseSpec && VirtualBaseSpec)
2927 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002928 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002929
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002930 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002931 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002932 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002933
2934 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002935 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002936 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002937 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002938 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002939 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002940 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002941
2942 InitializedEntity BaseEntity =
2943 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2944 InitializationKind Kind =
2945 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2946 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2947 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002948 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002949 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002950 if (BaseInit.isInvalid())
2951 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002952
Richard Smith945f8d32013-01-14 22:39:08 +00002953 // C++11 [class.base.init]p7:
2954 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002955 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002956 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002957 if (BaseInit.isInvalid())
2958 return true;
2959
2960 // If we are in a dependent context, template instantiation will
2961 // perform this type-checking again. Just save the arguments that we
2962 // received in a ParenListExpr.
2963 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2964 // of the information that we have about the base
2965 // initializer. However, deconstructing the ASTs is a dicey process,
2966 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002967 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002968 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002969
Alexis Hunt1d792652011-01-08 20:30:50 +00002970 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002971 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002972 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002973 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002974 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002975}
2976
Sebastian Redl22653ba2011-08-30 19:58:05 +00002977// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002978static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2979 if (T.isNull()) T = E->getType();
2980 QualType TargetType = SemaRef.BuildReferenceType(
2981 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002982 SourceLocation ExprLoc = E->getLocStart();
2983 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2984 TargetType, ExprLoc);
2985
2986 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2987 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002988 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002989}
2990
Anders Carlsson1b00e242010-04-23 03:10:23 +00002991/// ImplicitInitializerKind - How an implicit base or member initializer should
2992/// initialize its base or member.
2993enum ImplicitInitializerKind {
2994 IIK_Default,
2995 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002996 IIK_Move,
2997 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002998};
2999
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003000static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003001BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003002 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003003 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003004 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003005 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003006 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003007 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3008 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003009
John McCalldadc5752010-08-24 06:29:42 +00003010 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003011
3012 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003013 case IIK_Inherit: {
3014 const CXXRecordDecl *Inherited =
3015 Constructor->getInheritedConstructor()->getParent();
3016 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3017 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3018 // C++11 [class.inhctor]p8:
3019 // Each expression in the expression-list is of the form
3020 // static_cast<T&&>(p), where p is the name of the corresponding
3021 // constructor parameter and T is the declared type of p.
3022 SmallVector<Expr*, 16> Args;
3023 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3024 ParmVarDecl *PD = Constructor->getParamDecl(I);
3025 ExprResult ArgExpr =
3026 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3027 VK_LValue, SourceLocation());
3028 if (ArgExpr.isInvalid())
3029 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003030 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003031 }
3032
3033 InitializationKind InitKind = InitializationKind::CreateDirect(
3034 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003035 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003036 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3037 break;
3038 }
3039 }
3040 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003041 case IIK_Default: {
3042 InitializationKind InitKind
3043 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003044 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3045 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003046 break;
3047 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003048
Sebastian Redl22653ba2011-08-30 19:58:05 +00003049 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003050 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003051 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003052 ParmVarDecl *Param = Constructor->getParamDecl(0);
3053 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003054
Anders Carlsson1b00e242010-04-23 03:10:23 +00003055 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003056 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003057 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003058 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003059 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003060
Eli Friedmanfa0df832012-02-02 03:46:19 +00003061 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3062
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003063 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003064 QualType ArgTy =
3065 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3066 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003067
Sebastian Redl22653ba2011-08-30 19:58:05 +00003068 if (Moving) {
3069 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3070 }
3071
John McCallcf142162010-08-07 06:22:56 +00003072 CXXCastPath BasePath;
3073 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003074 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3075 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003076 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003077 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003078
Anders Carlsson1b00e242010-04-23 03:10:23 +00003079 InitializationKind InitKind
3080 = InitializationKind::CreateDirect(Constructor->getLocation(),
3081 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003082 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3083 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003084 break;
3085 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003086 }
John McCallb268a282010-08-23 23:25:46 +00003087
Douglas Gregora40433a2010-12-07 00:41:46 +00003088 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003089 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003090 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003091
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003092 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003093 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003094 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3095 SourceLocation()),
3096 BaseSpec->isVirtual(),
3097 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003098 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003099 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003100 SourceLocation());
3101
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003102 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003103}
3104
Sebastian Redl22653ba2011-08-30 19:58:05 +00003105static bool RefersToRValueRef(Expr *MemRef) {
3106 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3107 return Referenced->getType()->isRValueReferenceType();
3108}
3109
Anders Carlsson3c1db572010-04-23 02:15:47 +00003110static bool
3111BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003112 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003113 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003114 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003115 if (Field->isInvalidDecl())
3116 return true;
3117
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003118 SourceLocation Loc = Constructor->getLocation();
3119
Sebastian Redl22653ba2011-08-30 19:58:05 +00003120 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3121 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003122 ParmVarDecl *Param = Constructor->getParamDecl(0);
3123 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003124
3125 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003126 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3127 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003128
Anders Carlsson423f5d82010-04-23 16:04:08 +00003129 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003130 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003131 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003132 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003133
Eli Friedmanfa0df832012-02-02 03:46:19 +00003134 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3135
Sebastian Redl22653ba2011-08-30 19:58:05 +00003136 if (Moving) {
3137 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3138 }
3139
Douglas Gregor94f9a482010-05-05 05:51:00 +00003140 // Build a reference to this field within the parameter.
3141 CXXScopeSpec SS;
3142 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3143 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003144 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3145 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003146 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003147 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003148 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003149 ParamType, Loc,
3150 /*IsArrow=*/false,
3151 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003152 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003153 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003154 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003155 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003156 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003157 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003158
3159 // C++11 [class.copy]p15:
3160 // - if a member m has rvalue reference type T&&, it is direct-initialized
3161 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003162 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003163 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003164 }
3165
Douglas Gregor94f9a482010-05-05 05:51:00 +00003166 // When the field we are copying is an array, create index variables for
3167 // each dimension of the array. We use these index variables to subscript
3168 // the source array, and other clients (e.g., CodeGen) will perform the
3169 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003170 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003171 QualType BaseType = Field->getType();
3172 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003173 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003174 while (const ConstantArrayType *Array
3175 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003176 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003177 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003178 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003179 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003180 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003181 llvm::raw_svector_ostream OS(Str);
3182 OS << "__i" << IndexVariables.size();
3183 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3184 }
3185 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003186 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 IterationVarName, SizeType,
3188 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003189 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003190 IndexVariables.push_back(IterationVar);
3191
3192 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003193 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003194 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003195 assert(!IterationVarRef.isInvalid() &&
3196 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003197 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003198 assert(!IterationVarRef.isInvalid() &&
3199 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003200
Douglas Gregor94f9a482010-05-05 05:51:00 +00003201 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003202 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3203 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003204 Loc);
3205 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003206 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003207
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 BaseType = Array->getElementType();
3209 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003210
3211 // The array subscript expression is an lvalue, which is wrong for moving.
3212 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003213 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003214
Douglas Gregor94f9a482010-05-05 05:51:00 +00003215 // Construct the entity that we will be initializing. For an array, this
3216 // will be first element in the array, which may require several levels
3217 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003218 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003219 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003220 if (Indirect)
3221 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3222 else
3223 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003224 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3225 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3226 0,
3227 Entities.back()));
3228
3229 // Direct-initialize to use the copy constructor.
3230 InitializationKind InitKind =
3231 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3232
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003233 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003234 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003235
John McCalldadc5752010-08-24 06:29:42 +00003236 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003237 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003238 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003239 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003240 if (MemberInit.isInvalid())
3241 return true;
3242
Douglas Gregor493627b2011-08-10 15:22:55 +00003243 if (Indirect) {
3244 assert(IndexVariables.size() == 0 &&
3245 "Indirect field improperly initialized");
3246 CXXMemberInit
3247 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3248 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003249 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003250 Loc);
3251 } else
3252 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003253 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003254 Loc,
3255 IndexVariables.data(),
3256 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003257 return false;
3258 }
3259
Richard Smithc2bc61b2013-03-18 21:12:30 +00003260 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3261 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003262
Anders Carlsson3c1db572010-04-23 02:15:47 +00003263 QualType FieldBaseElementType =
3264 SemaRef.Context.getBaseElementType(Field->getType());
3265
Anders Carlsson3c1db572010-04-23 02:15:47 +00003266 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003267 InitializedEntity InitEntity
3268 = Indirect? InitializedEntity::InitializeMember(Indirect)
3269 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003270 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003271 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003272
3273 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3274 ExprResult MemberInit =
3275 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003276
Douglas Gregora40433a2010-12-07 00:41:46 +00003277 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003278 if (MemberInit.isInvalid())
3279 return true;
3280
Douglas Gregor493627b2011-08-10 15:22:55 +00003281 if (Indirect)
3282 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3283 Indirect, Loc,
3284 Loc,
3285 MemberInit.get(),
3286 Loc);
3287 else
3288 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3289 Field, Loc, Loc,
3290 MemberInit.get(),
3291 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003292 return false;
3293 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003294
Alexis Hunt8b455182011-05-17 00:19:05 +00003295 if (!Field->getParent()->isUnion()) {
3296 if (FieldBaseElementType->isReferenceType()) {
3297 SemaRef.Diag(Constructor->getLocation(),
3298 diag::err_uninitialized_member_in_ctor)
3299 << (int)Constructor->isImplicit()
3300 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3301 << 0 << Field->getDeclName();
3302 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3303 return true;
3304 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003305
Alexis Hunt8b455182011-05-17 00:19:05 +00003306 if (FieldBaseElementType.isConstQualified()) {
3307 SemaRef.Diag(Constructor->getLocation(),
3308 diag::err_uninitialized_member_in_ctor)
3309 << (int)Constructor->isImplicit()
3310 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3311 << 1 << Field->getDeclName();
3312 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3313 return true;
3314 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003315 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003316
David Blaikiebbafb8a2012-03-11 07:00:24 +00003317 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003318 FieldBaseElementType->isObjCRetainableType() &&
3319 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3320 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003321 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003322 // Default-initialize Objective-C pointers to NULL.
3323 CXXMemberInit
3324 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3325 Loc, Loc,
3326 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3327 Loc);
3328 return false;
3329 }
3330
Anders Carlsson3c1db572010-04-23 02:15:47 +00003331 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003332 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003333 return false;
3334}
John McCallbc83b3f2010-05-20 23:23:51 +00003335
3336namespace {
3337struct BaseAndFieldInfo {
3338 Sema &S;
3339 CXXConstructorDecl *Ctor;
3340 bool AnyErrorsInInits;
3341 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003342 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003343 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003344 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003345
3346 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3347 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003348 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3349 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003350 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003351 else if (Generated && Ctor->isMoveConstructor())
3352 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003353 else if (Ctor->getInheritedConstructor())
3354 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003355 else
3356 IIK = IIK_Default;
3357 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003358
3359 bool isImplicitCopyOrMove() const {
3360 switch (IIK) {
3361 case IIK_Copy:
3362 case IIK_Move:
3363 return true;
3364
3365 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003366 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003367 return false;
3368 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003369
3370 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003371 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003372
3373 bool addFieldInitializer(CXXCtorInitializer *Init) {
3374 AllToInit.push_back(Init);
3375
3376 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003377 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003378 S.UnusedPrivateFields.remove(Init->getAnyMember());
3379
3380 return false;
3381 }
John McCallbc83b3f2010-05-20 23:23:51 +00003382
Richard Smithab44d5b2013-12-10 08:25:00 +00003383 bool isInactiveUnionMember(FieldDecl *Field) {
3384 RecordDecl *Record = Field->getParent();
3385 if (!Record->isUnion())
3386 return false;
3387
Richard Smith8d183852013-12-10 20:56:03 +00003388 if (FieldDecl *Active =
3389 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003390 return Active != Field->getCanonicalDecl();
3391
3392 // In an implicit copy or move constructor, ignore any in-class initializer.
3393 if (isImplicitCopyOrMove())
3394 return true;
3395
3396 // If there's no explicit initialization, the field is active only if it
3397 // has an in-class initializer...
3398 if (Field->hasInClassInitializer())
3399 return false;
3400 // ... or it's an anonymous struct or union whose class has an in-class
3401 // initializer.
3402 if (!Field->isAnonymousStructOrUnion())
3403 return true;
3404 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3405 return !FieldRD->hasInClassInitializer();
3406 }
3407
3408 /// \brief Determine whether the given field is, or is within, a union member
3409 /// that is inactive (because there was an initializer given for a different
3410 /// member of the union, or because the union was not initialized at all).
3411 bool isWithinInactiveUnionMember(FieldDecl *Field,
3412 IndirectFieldDecl *Indirect) {
3413 if (!Indirect)
3414 return isInactiveUnionMember(Field);
3415
Aaron Ballman29c94602014-03-07 18:36:15 +00003416 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003417 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003418 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003419 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003420 }
3421 return false;
3422 }
3423};
Richard Smithc94ec842011-09-19 13:34:43 +00003424}
3425
Douglas Gregor10f939c2011-11-02 23:04:16 +00003426/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3427/// array type.
3428static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3429 if (T->isIncompleteArrayType())
3430 return true;
3431
3432 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3433 if (!ArrayT->getSize())
3434 return true;
3435
3436 T = ArrayT->getElementType();
3437 }
3438
3439 return false;
3440}
3441
Richard Smith938f40b2011-06-11 17:19:42 +00003442static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003443 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003444 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003445 if (Field->isInvalidDecl())
3446 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003447
Chandler Carruth139e9622010-06-30 02:59:29 +00003448 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003449 if (CXXCtorInitializer *Init =
3450 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003451 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003452
Richard Smithab44d5b2013-12-10 08:25:00 +00003453 // C++11 [class.base.init]p8:
3454 // if the entity is a non-static data member that has a
3455 // brace-or-equal-initializer and either
3456 // -- the constructor's class is a union and no other variant member of that
3457 // union is designated by a mem-initializer-id or
3458 // -- the constructor's class is not a union, and, if the entity is a member
3459 // of an anonymous union, no other member of that union is designated by
3460 // a mem-initializer-id,
3461 // the entity is initialized as specified in [dcl.init].
3462 //
3463 // We also apply the same rules to handle anonymous structs within anonymous
3464 // unions.
3465 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3466 return false;
3467
Douglas Gregor7db3e952011-11-28 20:03:15 +00003468 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003469 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3470 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003471 CXXCtorInitializer *Init;
3472 if (Indirect)
3473 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3474 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003475 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003476 SourceLocation());
3477 else
3478 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3479 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003480 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003481 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003482 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003483 }
3484
Douglas Gregor10f939c2011-11-02 23:04:16 +00003485 // Don't initialize incomplete or zero-length arrays.
3486 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3487 return false;
3488
John McCallbc83b3f2010-05-20 23:23:51 +00003489 // Don't try to build an implicit initializer if there were semantic
3490 // errors in any of the initializers (and therefore we might be
3491 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003492 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003493 return false;
3494
Craig Topperc3ec1492014-05-26 06:22:03 +00003495 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003496 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3497 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003498 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003499
Richard Smith0a8cfc72012-08-07 21:30:42 +00003500 if (!Init)
3501 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003502
Richard Smith0a8cfc72012-08-07 21:30:42 +00003503 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003504}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003505
3506bool
3507Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3508 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003509 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003510 Constructor->setNumCtorInitializers(1);
3511 CXXCtorInitializer **initializer =
3512 new (Context) CXXCtorInitializer*[1];
3513 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3514 Constructor->setCtorInitializers(initializer);
3515
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003516 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003517 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003518 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3519 }
3520
Alexis Hunte2622992011-05-05 00:05:47 +00003521 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003522
Alexis Hunt61bc1732011-05-01 07:04:31 +00003523 return false;
3524}
Douglas Gregor493627b2011-08-10 15:22:55 +00003525
David Blaikie3fc2f912013-01-17 05:26:25 +00003526bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3527 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003528 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003529 // Just store the initializers as written, they will be checked during
3530 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003531 if (!Initializers.empty()) {
3532 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003533 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003534 new (Context) CXXCtorInitializer*[Initializers.size()];
3535 memcpy(baseOrMemberInitializers, Initializers.data(),
3536 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003537 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003538 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003539
3540 // Let template instantiation know whether we had errors.
3541 if (AnyErrors)
3542 Constructor->setInvalidDecl();
3543
Anders Carlssondb0a9652010-04-02 06:26:44 +00003544 return false;
3545 }
3546
John McCallbc83b3f2010-05-20 23:23:51 +00003547 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003548
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003549 // We need to build the initializer AST according to order of construction
3550 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003551 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003552 if (!ClassDecl)
3553 return true;
3554
Eli Friedman9cf6b592009-11-09 19:20:36 +00003555 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003556
David Blaikie3fc2f912013-01-17 05:26:25 +00003557 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003558 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003559
Anders Carlssondb0a9652010-04-02 06:26:44 +00003560 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003561 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003562 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003563 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003564
3565 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003566 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003567 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003568 if (FD && FD->getParent()->isUnion())
3569 Info.ActiveUnionMember.insert(std::make_pair(
3570 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3571 }
3572 } else if (FieldDecl *FD = Member->getMember()) {
3573 if (FD->getParent()->isUnion())
3574 Info.ActiveUnionMember.insert(std::make_pair(
3575 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3576 }
3577 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003578 }
3579
Anders Carlsson43c64af2010-04-21 19:52:01 +00003580 // Keep track of the direct virtual bases.
3581 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003582 for (auto &I : ClassDecl->bases()) {
3583 if (I.isVirtual())
3584 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003585 }
3586
Anders Carlssondb0a9652010-04-02 06:26:44 +00003587 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003588 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003589 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003590 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003591 // [class.base.init]p7, per DR257:
3592 // A mem-initializer where the mem-initializer-id names a virtual base
3593 // class is ignored during execution of a constructor of any class that
3594 // is not the most derived class.
3595 if (ClassDecl->isAbstract()) {
3596 // FIXME: Provide a fixit to remove the base specifier. This requires
3597 // tracking the location of the associated comma for a base specifier.
3598 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003599 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003600 DiagnoseAbstractType(ClassDecl);
3601 }
3602
John McCallbc83b3f2010-05-20 23:23:51 +00003603 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003604 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3605 // [class.base.init]p8, per DR257:
3606 // If a given [...] base class is not named by a mem-initializer-id
3607 // [...] and the entity is not a virtual base class of an abstract
3608 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003609 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003610 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003611 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003612 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003613 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003614 HadError = true;
3615 continue;
3616 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003617
John McCallbc83b3f2010-05-20 23:23:51 +00003618 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003619 }
3620 }
Mike Stump11289f42009-09-09 15:08:12 +00003621
John McCallbc83b3f2010-05-20 23:23:51 +00003622 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003623 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003624 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003625 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003626 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003627
Alexis Hunt1d792652011-01-08 20:30:50 +00003628 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003629 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003630 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003631 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003632 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003633 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003634 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003635 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003636 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003637 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003638 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003639
John McCallbc83b3f2010-05-20 23:23:51 +00003640 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003641 }
3642 }
Mike Stump11289f42009-09-09 15:08:12 +00003643
John McCallbc83b3f2010-05-20 23:23:51 +00003644 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003645 for (auto *Mem : ClassDecl->decls()) {
3646 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003647 // C++ [class.bit]p2:
3648 // A declaration for a bit-field that omits the identifier declares an
3649 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3650 // initialized.
3651 if (F->isUnnamedBitfield())
3652 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003653
Sebastian Redl22653ba2011-08-30 19:58:05 +00003654 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003655 // handle anonymous struct/union fields based on their individual
3656 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003657 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003658 continue;
3659
3660 if (CollectFieldInitializer(*this, Info, F))
3661 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003662 continue;
3663 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003664
3665 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003666 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003667 continue;
3668
Aaron Ballman629afae2014-03-07 19:56:05 +00003669 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003670 if (F->getType()->isIncompleteArrayType()) {
3671 assert(ClassDecl->hasFlexibleArrayMember() &&
3672 "Incomplete array type is not valid");
3673 continue;
3674 }
3675
Douglas Gregor493627b2011-08-10 15:22:55 +00003676 // Initialize each field of an anonymous struct individually.
3677 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3678 HadError = true;
3679
3680 continue;
3681 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003682 }
Mike Stump11289f42009-09-09 15:08:12 +00003683
David Blaikie3fc2f912013-01-17 05:26:25 +00003684 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003685 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003686 Constructor->setNumCtorInitializers(NumInitializers);
3687 CXXCtorInitializer **baseOrMemberInitializers =
3688 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003689 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003690 NumInitializers * sizeof(CXXCtorInitializer*));
3691 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003692
John McCalla6309952010-03-16 21:39:52 +00003693 // Constructors implicitly reference the base and member
3694 // destructors.
3695 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3696 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003697 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003698
3699 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003700}
3701
David Blaikieb61b8152013-01-17 08:49:22 +00003702static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003703 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003704 const RecordDecl *RD = RT->getDecl();
3705 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003706 for (auto *Field : RD->fields())
3707 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003708 return;
3709 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003710 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003711 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003712}
3713
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003714static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3715 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003716}
3717
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003718static const void *GetKeyForMember(ASTContext &Context,
3719 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003720 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003721 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003722
Richard Smithcd45dbc2014-04-19 03:48:30 +00003723 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003724}
3725
David Blaikie3fc2f912013-01-17 05:26:25 +00003726static void DiagnoseBaseOrMemInitializerOrder(
3727 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3728 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003729 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003730 return;
Mike Stump11289f42009-09-09 15:08:12 +00003731
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003732 // Don't check initializers order unless the warning is enabled at the
3733 // location of at least one initializer.
3734 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003735 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003736 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003737 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3738 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003739 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003740 ShouldCheckOrder = true;
3741 break;
3742 }
3743 }
3744 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003745 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003746
John McCallbb7b6582010-04-10 07:37:23 +00003747 // Build the list of bases and members in the order that they'll
3748 // actually be initialized. The explicit initializers should be in
3749 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003750 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003751
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003752 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3753
John McCallbb7b6582010-04-10 07:37:23 +00003754 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003755 for (const auto &VBase : ClassDecl->vbases())
3756 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003757
John McCallbb7b6582010-04-10 07:37:23 +00003758 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003759 for (const auto &Base : ClassDecl->bases()) {
3760 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003761 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003762 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003763 }
Mike Stump11289f42009-09-09 15:08:12 +00003764
John McCallbb7b6582010-04-10 07:37:23 +00003765 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003766 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003767 if (Field->isUnnamedBitfield())
3768 continue;
3769
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003770 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003771 }
3772
John McCallbb7b6582010-04-10 07:37:23 +00003773 unsigned NumIdealInits = IdealInitKeys.size();
3774 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003775
Craig Topperc3ec1492014-05-26 06:22:03 +00003776 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003777 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003778 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003779 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003780
3781 // Scan forward to try to find this initializer in the idealized
3782 // initializers list.
3783 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3784 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003785 break;
John McCallbb7b6582010-04-10 07:37:23 +00003786
3787 // If we didn't find this initializer, it must be because we
3788 // scanned past it on a previous iteration. That can only
3789 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003790 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003791 Sema::SemaDiagnosticBuilder D =
3792 SemaRef.Diag(PrevInit->getSourceLocation(),
3793 diag::warn_initializer_out_of_order);
3794
Francois Pichetd583da02010-12-04 09:14:42 +00003795 if (PrevInit->isAnyMemberInitializer())
3796 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003797 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003798 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003799
Francois Pichetd583da02010-12-04 09:14:42 +00003800 if (Init->isAnyMemberInitializer())
3801 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003802 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003803 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003804
3805 // Move back to the initializer's location in the ideal list.
3806 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3807 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003808 break;
John McCallbb7b6582010-04-10 07:37:23 +00003809
3810 assert(IdealIndex != NumIdealInits &&
3811 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003812 }
John McCallbb7b6582010-04-10 07:37:23 +00003813
3814 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003815 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003816}
3817
John McCall23eebd92010-04-10 09:28:51 +00003818namespace {
3819bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003820 CXXCtorInitializer *Init,
3821 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003822 if (!PrevInit) {
3823 PrevInit = Init;
3824 return false;
3825 }
3826
Douglas Gregorea306a12013-03-25 23:28:23 +00003827 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003828 S.Diag(Init->getSourceLocation(),
3829 diag::err_multiple_mem_initialization)
3830 << Field->getDeclName()
3831 << Init->getSourceRange();
3832 else {
John McCall424cec92011-01-19 06:33:43 +00003833 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003834 assert(BaseClass && "neither field nor base");
3835 S.Diag(Init->getSourceLocation(),
3836 diag::err_multiple_base_initialization)
3837 << QualType(BaseClass, 0)
3838 << Init->getSourceRange();
3839 }
3840 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3841 << 0 << PrevInit->getSourceRange();
3842
3843 return true;
3844}
3845
Alexis Hunt1d792652011-01-08 20:30:50 +00003846typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003847typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3848
3849bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003850 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003851 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003852 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003853 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003854 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003855
3856 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003857 if (Parent->isUnion()) {
3858 UnionEntry &En = Unions[Parent];
3859 if (En.first && En.first != Child) {
3860 S.Diag(Init->getSourceLocation(),
3861 diag::err_multiple_mem_union_initialization)
3862 << Field->getDeclName()
3863 << Init->getSourceRange();
3864 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3865 << 0 << En.second->getSourceRange();
3866 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003867 }
3868 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003869 En.first = Child;
3870 En.second = Init;
3871 }
David Blaikie0f65d592011-11-17 06:01:57 +00003872 if (!Parent->isAnonymousStructOrUnion())
3873 return false;
John McCall23eebd92010-04-10 09:28:51 +00003874 }
3875
3876 Child = Parent;
3877 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003878 }
John McCall23eebd92010-04-10 09:28:51 +00003879
3880 return false;
3881}
3882}
3883
Anders Carlssone857b292010-04-02 03:37:03 +00003884/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003885void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003886 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003887 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003888 bool AnyErrors) {
3889 if (!ConstructorDecl)
3890 return;
3891
3892 AdjustDeclIfTemplate(ConstructorDecl);
3893
3894 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003895 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003896
3897 if (!Constructor) {
3898 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3899 return;
3900 }
3901
John McCall23eebd92010-04-10 09:28:51 +00003902 // Mapping for the duplicate initializers check.
3903 // For member initializers, this is keyed with a FieldDecl*.
3904 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003905 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003906
3907 // Mapping for the inconsistent anonymous-union initializers check.
3908 RedundantUnionMap MemberUnions;
3909
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003910 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003911 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003912 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003913
Abramo Bagnara341d7832010-05-26 18:09:23 +00003914 // Set the source order index.
3915 Init->setSourceOrder(i);
3916
Francois Pichetd583da02010-12-04 09:14:42 +00003917 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003918 const void *Key = GetKeyForMember(Context, Init);
3919 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003920 CheckRedundantUnionInit(*this, Init, MemberUnions))
3921 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003922 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003923 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003924 if (CheckRedundantInit(*this, Init, Members[Key]))
3925 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003926 } else {
3927 assert(Init->isDelegatingInitializer());
3928 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003929 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003930 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003931 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003932 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003933 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003934 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003935 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003936 // Return immediately as the initializer is set.
3937 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003938 }
Anders Carlssone857b292010-04-02 03:37:03 +00003939 }
3940
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003941 if (HadError)
3942 return;
3943
David Blaikie3fc2f912013-01-17 05:26:25 +00003944 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003945
David Blaikie3fc2f912013-01-17 05:26:25 +00003946 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003947
Richard Trieuef64e942013-10-25 00:56:00 +00003948 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003949}
3950
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003951void
John McCalla6309952010-03-16 21:39:52 +00003952Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3953 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003954 // Ignore dependent contexts. Also ignore unions, since their members never
3955 // have destructors implicitly called.
3956 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003957 return;
John McCall1064d7e2010-03-16 05:22:47 +00003958
3959 // FIXME: all the access-control diagnostics are positioned on the
3960 // field/base declaration. That's probably good; that said, the
3961 // user might reasonably want to know why the destructor is being
3962 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003963
Anders Carlssondee9a302009-11-17 04:44:12 +00003964 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003965 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003966 if (Field->isInvalidDecl())
3967 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003968
3969 // Don't destroy incomplete or zero-length arrays.
3970 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3971 continue;
3972
Anders Carlssondee9a302009-11-17 04:44:12 +00003973 QualType FieldType = Context.getBaseElementType(Field->getType());
3974
3975 const RecordType* RT = FieldType->getAs<RecordType>();
3976 if (!RT)
3977 continue;
3978
3979 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003980 if (FieldClassDecl->isInvalidDecl())
3981 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003982 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003983 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003984 // The destructor for an implicit anonymous union member is never invoked.
3985 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3986 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003987
Douglas Gregore71edda2010-07-01 22:47:18 +00003988 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003989 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003990 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003991 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003992 << Field->getDeclName()
3993 << FieldType);
3994
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003995 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003996 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003997 }
3998
John McCall1064d7e2010-03-16 05:22:47 +00003999 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4000
Anders Carlssondee9a302009-11-17 04:44:12 +00004001 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004002 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004003 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004004 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004005
4006 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004007 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004008 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004009
John McCall1064d7e2010-03-16 05:22:47 +00004010 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004011 // If our base class is invalid, we probably can't get its dtor anyway.
4012 if (BaseClassDecl->isInvalidDecl())
4013 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004014 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004015 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004016
Douglas Gregore71edda2010-07-01 22:47:18 +00004017 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004018 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004019
4020 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004021 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004022 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004023 << Base.getType()
4024 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004025 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004026
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004027 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004028 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004029 }
4030
4031 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004032 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004033 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004034 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004035
4036 // Ignore direct virtual bases.
4037 if (DirectVirtualBases.count(RT))
4038 continue;
4039
John McCall1064d7e2010-03-16 05:22:47 +00004040 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004041 // If our base class is invalid, we probably can't get its dtor anyway.
4042 if (BaseClassDecl->isInvalidDecl())
4043 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004044 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004045 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004046
Douglas Gregore71edda2010-07-01 22:47:18 +00004047 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004048 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004049 if (CheckDestructorAccess(
4050 ClassDecl->getLocation(), Dtor,
4051 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004052 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004053 Context.getTypeDeclType(ClassDecl)) ==
4054 AR_accessible) {
4055 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004056 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004057 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004058 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004059 }
John McCall1064d7e2010-03-16 05:22:47 +00004060
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004061 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004062 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004063 }
4064}
4065
John McCall48871652010-08-21 09:40:31 +00004066void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004067 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004068 return;
Mike Stump11289f42009-09-09 15:08:12 +00004069
Mike Stump11289f42009-09-09 15:08:12 +00004070 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004071 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004072 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004073 DiagnoseUninitializedFields(*this, Constructor);
4074 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004075}
4076
Mike Stump11289f42009-09-09 15:08:12 +00004077bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004078 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004079 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4080 unsigned DiagID;
4081 AbstractDiagSelID SelID;
4082
4083 public:
4084 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4085 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004086
Craig Toppera798a9d2014-03-02 09:32:10 +00004087 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004088 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004089 if (SelID == -1)
4090 S.Diag(Loc, DiagID) << T;
4091 else
4092 S.Diag(Loc, DiagID) << SelID << T;
4093 }
4094 } Diagnoser(DiagID, SelID);
4095
4096 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004097}
4098
Anders Carlssoneabf7702009-08-27 00:13:57 +00004099bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004100 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004101 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004102 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004103
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004104 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004105 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004106
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004107 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004108 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004109 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004110 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004111
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004112 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004113 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004114 }
Mike Stump11289f42009-09-09 15:08:12 +00004115
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004116 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004117 if (!RT)
4118 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004119
John McCall67da35c2010-02-04 22:26:26 +00004120 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004121
John McCall02db245d2010-08-18 09:41:07 +00004122 // We can't answer whether something is abstract until it has a
4123 // definition. If it's currently being defined, we'll walk back
4124 // over all the declarations when we have a full definition.
4125 const CXXRecordDecl *Def = RD->getDefinition();
4126 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004127 return false;
4128
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004129 if (!RD->isAbstract())
4130 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004131
Douglas Gregorae298422012-05-04 17:09:59 +00004132 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004133 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004134
John McCall02db245d2010-08-18 09:41:07 +00004135 return true;
4136}
4137
4138void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4139 // Check if we've already emitted the list of pure virtual functions
4140 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004141 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004142 return;
Mike Stump11289f42009-09-09 15:08:12 +00004143
Richard Smithbc46e432013-07-22 02:56:56 +00004144 // If the diagnostic is suppressed, don't emit the notes. We're only
4145 // going to emit them once, so try to attach them to a diagnostic we're
4146 // actually going to show.
4147 if (Diags.isLastDiagnosticIgnored())
4148 return;
4149
Douglas Gregor4165bd62010-03-23 23:47:56 +00004150 CXXFinalOverriderMap FinalOverriders;
4151 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004152
Anders Carlssona2f74f32010-06-03 01:00:02 +00004153 // Keep a set of seen pure methods so we won't diagnose the same method
4154 // more than once.
4155 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4156
Douglas Gregor4165bd62010-03-23 23:47:56 +00004157 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4158 MEnd = FinalOverriders.end();
4159 M != MEnd;
4160 ++M) {
4161 for (OverridingMethods::iterator SO = M->second.begin(),
4162 SOEnd = M->second.end();
4163 SO != SOEnd; ++SO) {
4164 // C++ [class.abstract]p4:
4165 // A class is abstract if it contains or inherits at least one
4166 // pure virtual function for which the final overrider is pure
4167 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004168
Douglas Gregor4165bd62010-03-23 23:47:56 +00004169 //
4170 if (SO->second.size() != 1)
4171 continue;
4172
4173 if (!SO->second.front().Method->isPure())
4174 continue;
4175
Anders Carlssona2f74f32010-06-03 01:00:02 +00004176 if (!SeenPureMethods.insert(SO->second.front().Method))
4177 continue;
4178
Douglas Gregor4165bd62010-03-23 23:47:56 +00004179 Diag(SO->second.front().Method->getLocation(),
4180 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004181 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004182 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004183 }
4184
4185 if (!PureVirtualClassDiagSet)
4186 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4187 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004188}
4189
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004190namespace {
John McCall02db245d2010-08-18 09:41:07 +00004191struct AbstractUsageInfo {
4192 Sema &S;
4193 CXXRecordDecl *Record;
4194 CanQualType AbstractType;
4195 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004196
John McCall02db245d2010-08-18 09:41:07 +00004197 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4198 : S(S), Record(Record),
4199 AbstractType(S.Context.getCanonicalType(
4200 S.Context.getTypeDeclType(Record))),
4201 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004202
John McCall02db245d2010-08-18 09:41:07 +00004203 void DiagnoseAbstractType() {
4204 if (Invalid) return;
4205 S.DiagnoseAbstractType(Record);
4206 Invalid = true;
4207 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004208
John McCall02db245d2010-08-18 09:41:07 +00004209 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4210};
4211
4212struct CheckAbstractUsage {
4213 AbstractUsageInfo &Info;
4214 const NamedDecl *Ctx;
4215
4216 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4217 : Info(Info), Ctx(Ctx) {}
4218
4219 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4220 switch (TL.getTypeLocClass()) {
4221#define ABSTRACT_TYPELOC(CLASS, PARENT)
4222#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004223 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004224#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004225 }
John McCall02db245d2010-08-18 09:41:07 +00004226 }
Mike Stump11289f42009-09-09 15:08:12 +00004227
John McCall02db245d2010-08-18 09:41:07 +00004228 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004229 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004230 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4231 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004232 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004233
4234 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004235 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004236 }
John McCall02db245d2010-08-18 09:41:07 +00004237 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004238
John McCall02db245d2010-08-18 09:41:07 +00004239 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4240 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4241 }
Mike Stump11289f42009-09-09 15:08:12 +00004242
John McCall02db245d2010-08-18 09:41:07 +00004243 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4244 // Visit the type parameters from a permissive context.
4245 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4246 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4247 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4248 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4249 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4250 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004251 }
John McCall02db245d2010-08-18 09:41:07 +00004252 }
Mike Stump11289f42009-09-09 15:08:12 +00004253
John McCall02db245d2010-08-18 09:41:07 +00004254 // Visit pointee types from a permissive context.
4255#define CheckPolymorphic(Type) \
4256 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4257 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4258 }
4259 CheckPolymorphic(PointerTypeLoc)
4260 CheckPolymorphic(ReferenceTypeLoc)
4261 CheckPolymorphic(MemberPointerTypeLoc)
4262 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004263 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004264
John McCall02db245d2010-08-18 09:41:07 +00004265 /// Handle all the types we haven't given a more specific
4266 /// implementation for above.
4267 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4268 // Every other kind of type that we haven't called out already
4269 // that has an inner type is either (1) sugar or (2) contains that
4270 // inner type in some way as a subobject.
4271 if (TypeLoc Next = TL.getNextTypeLoc())
4272 return Visit(Next, Sel);
4273
4274 // If there's no inner type and we're in a permissive context,
4275 // don't diagnose.
4276 if (Sel == Sema::AbstractNone) return;
4277
4278 // Check whether the type matches the abstract type.
4279 QualType T = TL.getType();
4280 if (T->isArrayType()) {
4281 Sel = Sema::AbstractArrayType;
4282 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004283 }
John McCall02db245d2010-08-18 09:41:07 +00004284 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4285 if (CT != Info.AbstractType) return;
4286
4287 // It matched; do some magic.
4288 if (Sel == Sema::AbstractArrayType) {
4289 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4290 << T << TL.getSourceRange();
4291 } else {
4292 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4293 << Sel << T << TL.getSourceRange();
4294 }
4295 Info.DiagnoseAbstractType();
4296 }
4297};
4298
4299void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4300 Sema::AbstractDiagSelID Sel) {
4301 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4302}
4303
4304}
4305
4306/// Check for invalid uses of an abstract type in a method declaration.
4307static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4308 CXXMethodDecl *MD) {
4309 // No need to do the check on definitions, which require that
4310 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004311 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004312 return;
4313
4314 // For safety's sake, just ignore it if we don't have type source
4315 // information. This should never happen for non-implicit methods,
4316 // but...
4317 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4318 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4319}
4320
4321/// Check for invalid uses of an abstract type within a class definition.
4322static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4323 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004324 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004325 if (D->isImplicit()) continue;
4326
4327 // Methods and method templates.
4328 if (isa<CXXMethodDecl>(D)) {
4329 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4330 } else if (isa<FunctionTemplateDecl>(D)) {
4331 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4332 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4333
4334 // Fields and static variables.
4335 } else if (isa<FieldDecl>(D)) {
4336 FieldDecl *FD = cast<FieldDecl>(D);
4337 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4338 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4339 } else if (isa<VarDecl>(D)) {
4340 VarDecl *VD = cast<VarDecl>(D);
4341 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4342 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4343
4344 // Nested classes and class templates.
4345 } else if (isa<CXXRecordDecl>(D)) {
4346 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4347 } else if (isa<ClassTemplateDecl>(D)) {
4348 CheckAbstractClassUsage(Info,
4349 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4350 }
4351 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004352}
4353
Nico Rieck9de0a572014-05-29 16:51:19 +00004354/// \brief Return a DLL attribute from the declaration.
4355static InheritableAttr *getDLLAttr(Decl *D) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004356 assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
4357 "A declaration cannot be both dllimport and dllexport.");
Nico Rieck9de0a572014-05-29 16:51:19 +00004358 if (auto *Import = D->getAttr<DLLImportAttr>())
4359 return Import;
4360 if (auto *Export = D->getAttr<DLLExportAttr>())
4361 return Export;
4362 return nullptr;
4363}
4364
Hans Wennborg853ae942014-05-30 16:59:42 +00004365/// \brief Check class-level dllimport/dllexport attribute.
4366static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4367 Attr *ClassAttr = getDLLAttr(Class);
4368 if (!ClassAttr)
4369 return;
4370
4371 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4372
4373 // Force declaration of implicit members so they can inherit the attribute.
4374 S.ForceDeclarationOfImplicitMembers(Class);
4375
4376 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4377 // seem to be true in practice?
4378
4379 // FIXME: We also need to propagate the attribute upwards to class template
4380 // specialization bases.
4381
4382 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004383 VarDecl *VD = dyn_cast<VarDecl>(Member);
4384 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4385
4386 // Only methods and static fields inherit the attributes.
4387 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004388 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004389
4390 // Don't process deleted methods.
4391 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004392 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004393
Hans Wennborge8ad3832014-06-11 22:44:39 +00004394 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4395 MD->isInlined()) {
4396 // Current MSVC versions don't export the move assignment operators, so
4397 // don't attempt to import them if we have a definition.
4398 continue;
4399 }
4400
Hans Wennborg496524b2014-05-31 02:08:49 +00004401 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4402 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4403 !MemberAttr->isInherited()) {
4404 S.Diag(MemberAttr->getLocation(),
4405 diag::err_attribute_dll_member_of_dll_class)
4406 << MemberAttr << ClassAttr;
4407 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4408 Member->setInvalidDecl();
4409 continue;
4410 }
4411 } else {
4412 auto *NewAttr =
4413 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4414 NewAttr->setInherited(true);
4415 Member->addAttr(NewAttr);
4416 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004417
4418 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
4419 if (ClassExported) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004420 if (MD->isUserProvided()) {
4421 // Instantiate non-default methods.
4422 S.MarkFunctionReferenced(Class->getLocation(), MD);
4423 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4424 MD->isCopyAssignmentOperator() ||
4425 MD->isMoveAssignmentOperator()) {
Alp Toker15e62a32014-06-06 12:02:07 +00004426 // Instantiate non-trivial or explicitly defaulted methods, and the
Hans Wennborg853ae942014-05-30 16:59:42 +00004427 // copy assignment / move assignment operators.
4428 S.MarkFunctionReferenced(Class->getLocation(), MD);
4429 // Resolve its exception specification; CodeGen needs it.
4430 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4431 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4432 S.ActOnFinishInlineMethodDef(MD);
4433 }
4434 }
4435 }
4436 }
4437}
4438
Douglas Gregorc99f1552009-12-03 18:33:45 +00004439/// \brief Perform semantic checks on a class definition that has been
4440/// completing, introducing implicitly-declared members, checking for
4441/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004442void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004443 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004444 return;
4445
John McCall02db245d2010-08-18 09:41:07 +00004446 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4447 AbstractUsageInfo Info(*this, Record);
4448 CheckAbstractClassUsage(Info, Record);
4449 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004450
4451 // If this is not an aggregate type and has no user-declared constructor,
4452 // complain about any non-static data members of reference or const scalar
4453 // type, since they will never get initializers.
4454 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004455 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4456 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004457 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004458 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004459 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004460 continue;
4461
Douglas Gregor454a5b62010-04-15 00:00:53 +00004462 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004463 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004464 if (!Complained) {
4465 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4466 << Record->getTagKind() << Record;
4467 Complained = true;
4468 }
4469
4470 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4471 << F->getType()->isReferenceType()
4472 << F->getDeclName();
4473 }
4474 }
4475 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004476
Anders Carlssone771e762011-01-25 18:08:22 +00004477 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004478 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004479
4480 if (Record->getIdentifier()) {
4481 // C++ [class.mem]p13:
4482 // If T is the name of a class, then each of the following shall have a
4483 // name different from T:
4484 // - every member of every anonymous union that is a member of class T.
4485 //
4486 // C++ [class.mem]p14:
4487 // In addition, if class T has a user-declared constructor (12.1), every
4488 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004489 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4490 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4491 ++I) {
4492 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004493 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4494 isa<IndirectFieldDecl>(D)) {
4495 Diag(D->getLocation(), diag::err_member_name_of_class)
4496 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004497 break;
4498 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004499 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004500 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004501
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004502 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004503 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004504 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004505 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4506 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004507 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4508 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4509 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004510
David Majnemera5433082013-10-18 00:33:31 +00004511 if (Record->isAbstract()) {
4512 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4513 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4514 << FA->isSpelledAsSealed();
4515 DiagnoseAbstractType(Record);
4516 }
David Blaikie348df502012-09-21 03:21:07 +00004517 }
4518
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004519 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004520 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004521 // See if a method overloads virtual methods in a base
4522 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004523 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004524 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004525
4526 // Check whether the explicitly-defaulted special members are valid.
4527 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004528 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004529
4530 // For an explicitly defaulted or deleted special member, we defer
4531 // determining triviality until the class is complete. That time is now!
4532 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004533 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004534 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004535 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004536
4537 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004538 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004539 }
4540 }
4541 }
4542 }
4543
4544 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4545 // function that is not a constructor declares that member function to be
4546 // const. [...] The class of which that function is a member shall be
4547 // a literal type.
4548 //
4549 // If the class has virtual bases, any constexpr members will already have
4550 // been diagnosed by the checks performed on the member declaration, so
4551 // suppress this (less useful) diagnostic.
4552 //
4553 // We delay this until we know whether an explicitly-defaulted (or deleted)
4554 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004555 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004556 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004557 for (const auto *M : Record->methods()) {
4558 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004559 switch (Record->getTemplateSpecializationKind()) {
4560 case TSK_ImplicitInstantiation:
4561 case TSK_ExplicitInstantiationDeclaration:
4562 case TSK_ExplicitInstantiationDefinition:
4563 // If a template instantiates to a non-literal type, but its members
4564 // instantiate to constexpr functions, the template is technically
4565 // ill-formed, but we allow it for sanity.
4566 continue;
4567
4568 case TSK_Undeclared:
4569 case TSK_ExplicitSpecialization:
4570 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4571 diag::err_constexpr_method_non_literal);
4572 break;
4573 }
4574
4575 // Only produce one error per class.
4576 break;
4577 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004578 }
4579 }
Sebastian Redl08905022011-02-05 19:23:19 +00004580
John McCall95833f32014-02-27 20:30:49 +00004581 // ms_struct is a request to use the same ABI rules as MSVC. Check
4582 // whether this class uses any C++ features that are implemented
4583 // completely differently in MSVC, and if so, emit a diagnostic.
4584 // That diagnostic defaults to an error, but we allow projects to
4585 // map it down to a warning (or ignore it). It's a fairly common
4586 // practice among users of the ms_struct pragma to mass-annotate
4587 // headers, sweeping up a bunch of types that the project doesn't
4588 // really rely on MSVC-compatible layout for. We must therefore
4589 // support "ms_struct except for C++ stuff" as a secondary ABI.
4590 if (Record->isMsStruct(Context) &&
4591 (Record->isPolymorphic() || Record->getNumBases())) {
4592 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004593 }
4594
Richard Smithc2bc61b2013-03-18 21:12:30 +00004595 // Declare inheriting constructors. We do this eagerly here because:
4596 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004597 // constructors from different classes.
4598 // - The lazy declaration of the other implicit constructors is so as to not
4599 // waste space and performance on classes that are not meant to be
4600 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004601 // have inheriting constructors.
4602 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004603
4604 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004605}
4606
Richard Smith41c35d62013-11-27 03:39:20 +00004607/// Look up the special member function that would be called by a special
4608/// member function for a subobject of class type.
4609///
4610/// \param Class The class type of the subobject.
4611/// \param CSM The kind of special member function.
4612/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4613/// \param ConstRHS True if this is a copy operation with a const object
4614/// on its RHS, that is, if the argument to the outer special member
4615/// function is 'const' and this is not a field marked 'mutable'.
4616static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4617 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4618 unsigned FieldQuals, bool ConstRHS) {
4619 unsigned LHSQuals = 0;
4620 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4621 LHSQuals = FieldQuals;
4622
4623 unsigned RHSQuals = FieldQuals;
4624 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4625 RHSQuals = 0;
4626 else if (ConstRHS)
4627 RHSQuals |= Qualifiers::Const;
4628
4629 return S.LookupSpecialMember(Class, CSM,
4630 RHSQuals & Qualifiers::Const,
4631 RHSQuals & Qualifiers::Volatile,
4632 false,
4633 LHSQuals & Qualifiers::Const,
4634 LHSQuals & Qualifiers::Volatile);
4635}
4636
Richard Smithb5800092012-06-10 05:43:50 +00004637/// Is the special member function which would be selected to perform the
4638/// specified operation on the specified class type a constexpr constructor?
4639static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4640 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004641 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004642 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004643 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004644 if (!SMOR || !SMOR->getMethod())
4645 // A constructor we wouldn't select can't be "involved in initializing"
4646 // anything.
4647 return true;
4648 return SMOR->getMethod()->isConstexpr();
4649}
4650
4651/// Determine whether the specified special member function would be constexpr
4652/// if it were implicitly defined.
4653static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4654 Sema::CXXSpecialMember CSM,
4655 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004656 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004657 return false;
4658
4659 // C++11 [dcl.constexpr]p4:
4660 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004661 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004662 switch (CSM) {
4663 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004664 // Since default constructor lookup is essentially trivial (and cannot
4665 // involve, for instance, template instantiation), we compute whether a
4666 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4667 //
4668 // This is important for performance; we need to know whether the default
4669 // constructor is constexpr to determine whether the type is a literal type.
4670 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4671
Richard Smithb5800092012-06-10 05:43:50 +00004672 case Sema::CXXCopyConstructor:
4673 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004674 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004675 break;
4676
4677 case Sema::CXXCopyAssignment:
4678 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004679 if (!S.getLangOpts().CPlusPlus1y)
4680 return false;
4681 // In C++1y, we need to perform overload resolution.
4682 Ctor = false;
4683 break;
4684
Richard Smithb5800092012-06-10 05:43:50 +00004685 case Sema::CXXDestructor:
4686 case Sema::CXXInvalid:
4687 return false;
4688 }
4689
4690 // -- if the class is a non-empty union, or for each non-empty anonymous
4691 // union member of a non-union class, exactly one non-static data member
4692 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004693 //
4694 // If we squint, this is guaranteed, since exactly one non-static data member
4695 // will be initialized (if the constructor isn't deleted), we just don't know
4696 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004697 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004698 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004699
4700 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004701 if (Ctor && ClassDecl->getNumVBases())
4702 return false;
4703
4704 // C++1y [class.copy]p26:
4705 // -- [the class] is a literal type, and
4706 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004707 return false;
4708
4709 // -- every constructor involved in initializing [...] base class
4710 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004711 // -- the assignment operator selected to copy/move each direct base
4712 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004713 for (const auto &B : ClassDecl->bases()) {
4714 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004715 if (!BaseType) continue;
4716
4717 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004718 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004719 return false;
4720 }
4721
4722 // -- every constructor involved in initializing non-static data members
4723 // [...] shall be a constexpr constructor;
4724 // -- every non-static data member and base class sub-object shall be
4725 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004726 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004727 // thereof), the assignment operator selected to copy/move that member is
4728 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004729 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004730 if (F->isInvalidDecl())
4731 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004732 QualType BaseType = S.Context.getBaseElementType(F->getType());
4733 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004734 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004735 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4736 BaseType.getCVRQualifiers(),
4737 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004738 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004739 }
4740 }
4741
4742 // All OK, it's constexpr!
4743 return true;
4744}
4745
Richard Smithd3b5c9082012-07-27 04:22:15 +00004746static Sema::ImplicitExceptionSpecification
4747computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4748 switch (S.getSpecialMember(MD)) {
4749 case Sema::CXXDefaultConstructor:
4750 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4751 case Sema::CXXCopyConstructor:
4752 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4753 case Sema::CXXCopyAssignment:
4754 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4755 case Sema::CXXMoveConstructor:
4756 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4757 case Sema::CXXMoveAssignment:
4758 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4759 case Sema::CXXDestructor:
4760 return S.ComputeDefaultedDtorExceptionSpec(MD);
4761 case Sema::CXXInvalid:
4762 break;
4763 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004764 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4765 "only special members have implicit exception specs");
4766 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004767}
4768
Reid Kleckner78af0702013-08-27 23:08:25 +00004769static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4770 CXXMethodDecl *MD) {
4771 FunctionProtoType::ExtProtoInfo EPI;
4772
4773 // Build an exception specification pointing back at this member.
4774 EPI.ExceptionSpecType = EST_Unevaluated;
4775 EPI.ExceptionSpecDecl = MD;
4776
4777 // Set the calling convention to the default for C++ instance methods.
4778 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4779 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4780 /*IsCXXMethod=*/true));
4781 return EPI;
4782}
4783
Richard Smithd3b5c9082012-07-27 04:22:15 +00004784void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4785 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4786 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4787 return;
4788
Richard Smith7f782272012-07-30 23:48:14 +00004789 // Evaluate the exception specification.
4790 ImplicitExceptionSpecification ExceptSpec =
4791 computeImplicitExceptionSpec(*this, Loc, MD);
4792
Richard Smith564417a2014-03-20 21:47:22 +00004793 FunctionProtoType::ExtProtoInfo EPI;
4794 ExceptSpec.getEPI(EPI);
4795
Richard Smith7f782272012-07-30 23:48:14 +00004796 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004797 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004798
4799 // A user-provided destructor can be defined outside the class. When that
4800 // happens, be sure to update the exception specification on both
4801 // declarations.
4802 const FunctionProtoType *CanonicalFPT =
4803 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4804 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004805 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004806}
4807
Richard Smithb9e90b12012-05-15 04:39:51 +00004808void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4809 CXXRecordDecl *RD = MD->getParent();
4810 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004811
Richard Smithb9e90b12012-05-15 04:39:51 +00004812 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4813 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004814
4815 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004816 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004817 bool First = MD == MD->getCanonicalDecl();
4818
4819 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004820
4821 // C++11 [dcl.fct.def.default]p1:
4822 // A function that is explicitly defaulted shall
4823 // -- be a special member function (checked elsewhere),
4824 // -- have the same type (except for ref-qualifiers, and except that a
4825 // copy operation can take a non-const reference) as an implicit
4826 // declaration, and
4827 // -- not have default arguments.
4828 unsigned ExpectedParams = 1;
4829 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4830 ExpectedParams = 0;
4831 if (MD->getNumParams() != ExpectedParams) {
4832 // This also checks for default arguments: a copy or move constructor with a
4833 // default argument is classified as a default constructor, and assignment
4834 // operations and destructors can't have default arguments.
4835 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4836 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004837 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004838 } else if (MD->isVariadic()) {
4839 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4840 << CSM << MD->getSourceRange();
4841 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004842 }
4843
Richard Smithb9e90b12012-05-15 04:39:51 +00004844 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004845
Richard Smithb5800092012-06-10 05:43:50 +00004846 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004847 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004848 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004849 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004850 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004851
Richard Smithb9e90b12012-05-15 04:39:51 +00004852 QualType ReturnType = Context.VoidTy;
4853 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4854 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004855 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004856 QualType ExpectedReturnType =
4857 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4858 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4859 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4860 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4861 HadError = true;
4862 }
4863
4864 // A defaulted special member cannot have cv-qualifiers.
4865 if (Type->getTypeQuals()) {
4866 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004867 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004868 HadError = true;
4869 }
4870 }
4871
4872 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004873 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004874 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004875 if (ExpectedParams && ArgType->isReferenceType()) {
4876 // Argument must be reference to possibly-const T.
4877 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004878 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004879
4880 if (ReferentType.isVolatileQualified()) {
4881 Diag(MD->getLocation(),
4882 diag::err_defaulted_special_member_volatile_param) << CSM;
4883 HadError = true;
4884 }
4885
Richard Smithb5800092012-06-10 05:43:50 +00004886 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004887 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4888 Diag(MD->getLocation(),
4889 diag::err_defaulted_special_member_copy_const_param)
4890 << (CSM == CXXCopyAssignment);
4891 // FIXME: Explain why this special member can't be const.
4892 } else {
4893 Diag(MD->getLocation(),
4894 diag::err_defaulted_special_member_move_const_param)
4895 << (CSM == CXXMoveAssignment);
4896 }
4897 HadError = true;
4898 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004899 } else if (ExpectedParams) {
4900 // A copy assignment operator can take its argument by value, but a
4901 // defaulted one cannot.
4902 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004903 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004904 HadError = true;
4905 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004906
Richard Smithcc36f692011-12-22 02:22:31 +00004907 // C++11 [dcl.fct.def.default]p2:
4908 // An explicitly-defaulted function may be declared constexpr only if it
4909 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004910 // Do not apply this rule to members of class templates, since core issue 1358
4911 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004912 // functions which cannot be constexpr (for non-constructors in C++11 and for
4913 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004914 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4915 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004916 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4917 : isa<CXXConstructorDecl>(MD)) &&
4918 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004919 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4920 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004921 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004922 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004923 }
Richard Smithbd305122012-12-11 01:14:52 +00004924
Richard Smithcc36f692011-12-22 02:22:31 +00004925 // and may have an explicit exception-specification only if it is compatible
4926 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004927 if (Type->hasExceptionSpec()) {
4928 // Delay the check if this is the first declaration of the special member,
4929 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004930 if (First) {
4931 // If the exception specification needs to be instantiated, do so now,
4932 // before we clobber it with an EST_Unevaluated specification below.
4933 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4934 InstantiateExceptionSpec(MD->getLocStart(), MD);
4935 Type = MD->getType()->getAs<FunctionProtoType>();
4936 }
Richard Smithbd305122012-12-11 01:14:52 +00004937 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004938 } else
Richard Smithbd305122012-12-11 01:14:52 +00004939 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4940 }
Richard Smithcc36f692011-12-22 02:22:31 +00004941
4942 // If a function is explicitly defaulted on its first declaration,
4943 if (First) {
4944 // -- it is implicitly considered to be constexpr if the implicit
4945 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004946 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004947
Richard Smithb9e90b12012-05-15 04:39:51 +00004948 // -- it is implicitly considered to have the same exception-specification
4949 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004950 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4951 EPI.ExceptionSpecType = EST_Unevaluated;
4952 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004953 MD->setType(Context.getFunctionType(ReturnType,
4954 ArrayRef<QualType>(&ArgType,
4955 ExpectedParams),
4956 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004957 }
4958
Richard Smithb9e90b12012-05-15 04:39:51 +00004959 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004960 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004961 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004962 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004963 // C++11 [dcl.fct.def.default]p4:
4964 // [For a] user-provided explicitly-defaulted function [...] if such a
4965 // function is implicitly defined as deleted, the program is ill-formed.
4966 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004967 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004968 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004969 }
4970 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004971
Richard Smithb9e90b12012-05-15 04:39:51 +00004972 if (HadError)
4973 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004974}
4975
Richard Smithbd305122012-12-11 01:14:52 +00004976/// Check whether the exception specification provided for an
4977/// explicitly-defaulted special member matches the exception specification
4978/// that would have been generated for an implicit special member, per
4979/// C++11 [dcl.fct.def.default]p2.
4980void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4981 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4982 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004983 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4984 /*IsCXXMethod=*/true);
4985 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004986 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4987 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004988 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004989
4990 // Ensure that it matches.
4991 CheckEquivalentExceptionSpec(
4992 PDiag(diag::err_incorrect_defaulted_exception_spec)
4993 << getSpecialMember(MD), PDiag(),
4994 ImplicitType, SourceLocation(),
4995 SpecifiedType, MD->getLocation());
4996}
4997
Alp Tokerae3a9442013-10-18 05:54:19 +00004998void Sema::CheckDelayedMemberExceptionSpecs() {
4999 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5000 2> Checks;
5001 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005002
Alp Tokerae3a9442013-10-18 05:54:19 +00005003 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5004 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5005
5006 // Perform any deferred checking of exception specifications for virtual
5007 // destructors.
5008 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5009 const CXXDestructorDecl *Dtor = Checks[i].first;
5010 assert(!Dtor->getParent()->isDependentType() &&
5011 "Should not ever add destructors of templates into the list.");
5012 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5013 }
5014
5015 // Check that any explicitly-defaulted methods have exception specifications
5016 // compatible with their implicit exception specifications.
5017 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5018 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5019 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005020}
5021
Richard Smithd951a1d2012-02-18 02:02:13 +00005022namespace {
5023struct SpecialMemberDeletionInfo {
5024 Sema &S;
5025 CXXMethodDecl *MD;
5026 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005027 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005028
5029 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005030 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005031 SourceLocation Loc;
5032
5033 bool AllFieldsAreConst;
5034
5035 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005036 Sema::CXXSpecialMember CSM, bool Diagnose)
5037 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005038 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005039 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005040 AllFieldsAreConst(true) {
5041 switch (CSM) {
5042 case Sema::CXXDefaultConstructor:
5043 case Sema::CXXCopyConstructor:
5044 IsConstructor = true;
5045 break;
5046 case Sema::CXXMoveConstructor:
5047 IsConstructor = true;
5048 IsMove = true;
5049 break;
5050 case Sema::CXXCopyAssignment:
5051 IsAssignment = true;
5052 break;
5053 case Sema::CXXMoveAssignment:
5054 IsAssignment = true;
5055 IsMove = true;
5056 break;
5057 case Sema::CXXDestructor:
5058 break;
5059 case Sema::CXXInvalid:
5060 llvm_unreachable("invalid special member kind");
5061 }
5062
5063 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005064 if (const ReferenceType *RT =
5065 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5066 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005067 }
5068 }
5069
5070 bool inUnion() const { return MD->getParent()->isUnion(); }
5071
5072 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005073 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005074 unsigned Quals, bool IsMutable) {
5075 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5076 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005077 }
5078
Richard Smith852265f2012-03-30 20:53:28 +00005079 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005080
Richard Smith852265f2012-03-30 20:53:28 +00005081 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005082 bool shouldDeleteForField(FieldDecl *FD);
5083 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005084
Richard Smithaf136f82012-07-18 03:51:16 +00005085 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5086 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005087 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5088 Sema::SpecialMemberOverloadResult *SMOR,
5089 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005090
5091 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005092};
5093}
5094
John McCalld4274212012-04-09 20:53:23 +00005095/// Is the given special member inaccessible when used on the given
5096/// sub-object.
5097bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5098 CXXMethodDecl *target) {
5099 /// If we're operating on a base class, the object type is the
5100 /// type of this special member.
5101 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005102 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005103 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5104 objectTy = S.Context.getTypeDeclType(MD->getParent());
5105 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5106
5107 // If we're operating on a field, the object type is the type of the field.
5108 } else {
5109 objectTy = S.Context.getTypeDeclType(target->getParent());
5110 }
5111
5112 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5113}
5114
Richard Smith852265f2012-03-30 20:53:28 +00005115/// Check whether we should delete a special member due to the implicit
5116/// definition containing a call to a special member of a subobject.
5117bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5118 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5119 bool IsDtorCallInCtor) {
5120 CXXMethodDecl *Decl = SMOR->getMethod();
5121 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5122
5123 int DiagKind = -1;
5124
5125 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5126 DiagKind = !Decl ? 0 : 1;
5127 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5128 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005129 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005130 DiagKind = 3;
5131 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5132 !Decl->isTrivial()) {
5133 // A member of a union must have a trivial corresponding special member.
5134 // As a weird special case, a destructor call from a union's constructor
5135 // must be accessible and non-deleted, but need not be trivial. Such a
5136 // destructor is never actually called, but is semantically checked as
5137 // if it were.
5138 DiagKind = 4;
5139 }
5140
5141 if (DiagKind == -1)
5142 return false;
5143
5144 if (Diagnose) {
5145 if (Field) {
5146 S.Diag(Field->getLocation(),
5147 diag::note_deleted_special_member_class_subobject)
5148 << CSM << MD->getParent() << /*IsField*/true
5149 << Field << DiagKind << IsDtorCallInCtor;
5150 } else {
5151 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5152 S.Diag(Base->getLocStart(),
5153 diag::note_deleted_special_member_class_subobject)
5154 << CSM << MD->getParent() << /*IsField*/false
5155 << Base->getType() << DiagKind << IsDtorCallInCtor;
5156 }
5157
5158 if (DiagKind == 1)
5159 S.NoteDeletedFunction(Decl);
5160 // FIXME: Explain inaccessibility if DiagKind == 3.
5161 }
5162
5163 return true;
5164}
5165
Richard Smith921bd202012-02-26 09:11:52 +00005166/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005167/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005168bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005169 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005170 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005171 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005172
5173 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005174 // -- any direct or virtual base class, or non-static data member with no
5175 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005176 // either M has no default constructor or overload resolution as applied
5177 // to M's default constructor results in an ambiguity or in a function
5178 // that is deleted or inaccessible
5179 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5180 // -- a direct or virtual base class B that cannot be copied/moved because
5181 // overload resolution, as applied to B's corresponding special member,
5182 // results in an ambiguity or a function that is deleted or inaccessible
5183 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005184 // C++11 [class.dtor]p5:
5185 // -- any direct or virtual base class [...] has a type with a destructor
5186 // that is deleted or inaccessible
5187 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005188 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005189 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5190 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005191 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005192
Richard Smith852265f2012-03-30 20:53:28 +00005193 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5194 // -- any direct or virtual base class or non-static data member has a
5195 // type with a destructor that is deleted or inaccessible
5196 if (IsConstructor) {
5197 Sema::SpecialMemberOverloadResult *SMOR =
5198 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5199 false, false, false, false, false);
5200 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5201 return true;
5202 }
5203
Richard Smith921bd202012-02-26 09:11:52 +00005204 return false;
5205}
5206
5207/// Check whether we should delete a special member function due to the class
5208/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005209bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005210 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005211 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005212}
5213
5214/// Check whether we should delete a special member function due to the class
5215/// having a particular non-static data member.
5216bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5217 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5218 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5219
5220 if (CSM == Sema::CXXDefaultConstructor) {
5221 // For a default constructor, all references must be initialized in-class
5222 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005223 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5224 if (Diagnose)
5225 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5226 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005227 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005228 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005229 // C++11 [class.ctor]p5: any non-variant non-static data member of
5230 // const-qualified type (or array thereof) with no
5231 // brace-or-equal-initializer does not have a user-provided default
5232 // constructor.
5233 if (!inUnion() && FieldType.isConstQualified() &&
5234 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005235 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5236 if (Diagnose)
5237 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005238 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005239 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005240 }
5241
5242 if (inUnion() && !FieldType.isConstQualified())
5243 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005244 } else if (CSM == Sema::CXXCopyConstructor) {
5245 // For a copy constructor, data members must not be of rvalue reference
5246 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005247 if (FieldType->isRValueReferenceType()) {
5248 if (Diagnose)
5249 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5250 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005251 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005252 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005253 } else if (IsAssignment) {
5254 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005255 if (FieldType->isReferenceType()) {
5256 if (Diagnose)
5257 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5258 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005259 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005260 }
5261 if (!FieldRecord && FieldType.isConstQualified()) {
5262 // C++11 [class.copy]p23:
5263 // -- a non-static data member of const non-class type (or array thereof)
5264 if (Diagnose)
5265 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005266 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005267 return true;
5268 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005269 }
5270
5271 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005272 // Some additional restrictions exist on the variant members.
5273 if (!inUnion() && FieldRecord->isUnion() &&
5274 FieldRecord->isAnonymousStructOrUnion()) {
5275 bool AllVariantFieldsAreConst = true;
5276
Richard Smith5704fe82012-03-29 19:00:10 +00005277 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005278 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005279 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005280
5281 if (!UnionFieldType.isConstQualified())
5282 AllVariantFieldsAreConst = false;
5283
Richard Smith921bd202012-02-26 09:11:52 +00005284 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5285 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005286 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005287 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005288 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005289 }
5290
5291 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005292 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005293 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005294 if (Diagnose)
5295 S.Diag(FieldRecord->getLocation(),
5296 diag::note_deleted_default_ctor_all_const)
5297 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005298 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005299 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005300
Richard Smith5704fe82012-03-29 19:00:10 +00005301 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005302 // This is technically non-conformant, but sanity demands it.
5303 return false;
5304 }
5305
Richard Smithaf136f82012-07-18 03:51:16 +00005306 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5307 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005308 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005309 }
5310
5311 return false;
5312}
5313
5314/// C++11 [class.ctor] p5:
5315/// A defaulted default constructor for a class X is defined as deleted if
5316/// X is a union and all of its variant members are of const-qualified type.
5317bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005318 // This is a silly definition, because it gives an empty union a deleted
5319 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005320 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005321 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005322 if (Diagnose)
5323 S.Diag(MD->getParent()->getLocation(),
5324 diag::note_deleted_default_ctor_all_const)
5325 << MD->getParent() << /*not anonymous union*/0;
5326 return true;
5327 }
5328 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005329}
5330
5331/// Determine whether a defaulted special member function should be defined as
5332/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5333/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005334bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5335 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005336 if (MD->isInvalidDecl())
5337 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005338 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005339 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005340 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005341 return false;
5342
Richard Smithd951a1d2012-02-18 02:02:13 +00005343 // C++11 [expr.lambda.prim]p19:
5344 // The closure type associated with a lambda-expression has a
5345 // deleted (8.4.3) default constructor and a deleted copy
5346 // assignment operator.
5347 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005348 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5349 if (Diagnose)
5350 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005351 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005352 }
5353
Richard Smith6f1e2c62012-04-02 20:59:25 +00005354 // For an anonymous struct or union, the copy and assignment special members
5355 // will never be used, so skip the check. For an anonymous union declared at
5356 // namespace scope, the constructor and destructor are used.
5357 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5358 RD->isAnonymousStructOrUnion())
5359 return false;
5360
Richard Smith852265f2012-03-30 20:53:28 +00005361 // C++11 [class.copy]p7, p18:
5362 // If the class definition declares a move constructor or move assignment
5363 // operator, an implicitly declared copy constructor or copy assignment
5364 // operator is defined as deleted.
5365 if (MD->isImplicit() &&
5366 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005367 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005368
5369 // In Microsoft mode, a user-declared move only causes the deletion of the
5370 // corresponding copy operation, not both copy operations.
5371 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005372 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005373 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005374
5375 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005376 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005377 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005378 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005379 break;
5380 }
5381 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005382 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005383 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005384 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005385 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005386
5387 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005388 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005389 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005390 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005391 break;
5392 }
5393 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005394 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005395 }
5396
5397 if (UserDeclaredMove) {
5398 Diag(UserDeclaredMove->getLocation(),
5399 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005400 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005401 << UserDeclaredMove->isMoveAssignmentOperator();
5402 return true;
5403 }
5404 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005405
Richard Smith6f1e2c62012-04-02 20:59:25 +00005406 // Do access control from the special member function
5407 ContextRAII MethodContext(*this, MD);
5408
Richard Smith921bd202012-02-26 09:11:52 +00005409 // C++11 [class.dtor]p5:
5410 // -- for a virtual destructor, lookup of the non-array deallocation function
5411 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005412 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005413 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005414 DeclarationName Name =
5415 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5416 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005417 OperatorDelete, false)) {
5418 if (Diagnose)
5419 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005420 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005421 }
Richard Smith921bd202012-02-26 09:11:52 +00005422 }
5423
Richard Smith852265f2012-03-30 20:53:28 +00005424 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005425
Aaron Ballman574705e2014-03-13 15:41:46 +00005426 for (auto &BI : RD->bases())
5427 if (!BI.isVirtual() &&
5428 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005429 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005430
Richard Smithd1627032013-07-22 18:06:23 +00005431 // Per DR1611, do not consider virtual bases of constructors of abstract
5432 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005433 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005434 for (auto &BI : RD->vbases())
5435 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005436 return true;
5437 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005438
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005439 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005440 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005441 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005442 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005443
Richard Smithd951a1d2012-02-18 02:02:13 +00005444 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005445 return true;
5446
5447 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005448}
5449
Richard Smith92f241f2012-12-08 02:53:02 +00005450/// Perform lookup for a special member of the specified kind, and determine
5451/// whether it is trivial. If the triviality can be determined without the
5452/// lookup, skip it. This is intended for use when determining whether a
5453/// special member of a containing object is trivial, and thus does not ever
5454/// perform overload resolution for default constructors.
5455///
5456/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5457/// member that was most likely to be intended to be trivial, if any.
5458static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5459 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005460 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005461 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005462 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005463
5464 switch (CSM) {
5465 case Sema::CXXInvalid:
5466 llvm_unreachable("not a special member");
5467
5468 case Sema::CXXDefaultConstructor:
5469 // C++11 [class.ctor]p5:
5470 // A default constructor is trivial if:
5471 // - all the [direct subobjects] have trivial default constructors
5472 //
5473 // Note, no overload resolution is performed in this case.
5474 if (RD->hasTrivialDefaultConstructor())
5475 return true;
5476
5477 if (Selected) {
5478 // If there's a default constructor which could have been trivial, dig it
5479 // out. Otherwise, if there's any user-provided default constructor, point
5480 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005481 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005482 if (RD->needsImplicitDefaultConstructor())
5483 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005484 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005485 if (!CI->isDefaultConstructor())
5486 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005487 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005488 if (!DefCtor->isUserProvided())
5489 break;
5490 }
5491
5492 *Selected = DefCtor;
5493 }
5494
5495 return false;
5496
5497 case Sema::CXXDestructor:
5498 // C++11 [class.dtor]p5:
5499 // A destructor is trivial if:
5500 // - all the direct [subobjects] have trivial destructors
5501 if (RD->hasTrivialDestructor())
5502 return true;
5503
5504 if (Selected) {
5505 if (RD->needsImplicitDestructor())
5506 S.DeclareImplicitDestructor(RD);
5507 *Selected = RD->getDestructor();
5508 }
5509
5510 return false;
5511
5512 case Sema::CXXCopyConstructor:
5513 // C++11 [class.copy]p12:
5514 // A copy constructor is trivial if:
5515 // - the constructor selected to copy each direct [subobject] is trivial
5516 if (RD->hasTrivialCopyConstructor()) {
5517 if (Quals == Qualifiers::Const)
5518 // We must either select the trivial copy constructor or reach an
5519 // ambiguity; no need to actually perform overload resolution.
5520 return true;
5521 } else if (!Selected) {
5522 return false;
5523 }
5524 // In C++98, we are not supposed to perform overload resolution here, but we
5525 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5526 // cases like B as having a non-trivial copy constructor:
5527 // struct A { template<typename T> A(T&); };
5528 // struct B { mutable A a; };
5529 goto NeedOverloadResolution;
5530
5531 case Sema::CXXCopyAssignment:
5532 // C++11 [class.copy]p25:
5533 // A copy assignment operator is trivial if:
5534 // - the assignment operator selected to copy each direct [subobject] is
5535 // trivial
5536 if (RD->hasTrivialCopyAssignment()) {
5537 if (Quals == Qualifiers::Const)
5538 return true;
5539 } else if (!Selected) {
5540 return false;
5541 }
5542 // In C++98, we are not supposed to perform overload resolution here, but we
5543 // treat that as a language defect.
5544 goto NeedOverloadResolution;
5545
5546 case Sema::CXXMoveConstructor:
5547 case Sema::CXXMoveAssignment:
5548 NeedOverloadResolution:
5549 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005550 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005551
5552 // The standard doesn't describe how to behave if the lookup is ambiguous.
5553 // We treat it as not making the member non-trivial, just like the standard
5554 // mandates for the default constructor. This should rarely matter, because
5555 // the member will also be deleted.
5556 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5557 return true;
5558
5559 if (!SMOR->getMethod()) {
5560 assert(SMOR->getKind() ==
5561 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5562 return false;
5563 }
5564
5565 // We deliberately don't check if we found a deleted special member. We're
5566 // not supposed to!
5567 if (Selected)
5568 *Selected = SMOR->getMethod();
5569 return SMOR->getMethod()->isTrivial();
5570 }
5571
5572 llvm_unreachable("unknown special method kind");
5573}
5574
Benjamin Kramer3e350262013-02-15 12:30:38 +00005575static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005576 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005577 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005578 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005579
5580 // Look for constructor templates.
5581 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5582 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5583 if (CXXConstructorDecl *CD =
5584 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5585 return CD;
5586 }
5587
Craig Topperc3ec1492014-05-26 06:22:03 +00005588 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005589}
5590
5591/// The kind of subobject we are checking for triviality. The values of this
5592/// enumeration are used in diagnostics.
5593enum TrivialSubobjectKind {
5594 /// The subobject is a base class.
5595 TSK_BaseClass,
5596 /// The subobject is a non-static data member.
5597 TSK_Field,
5598 /// The object is actually the complete object.
5599 TSK_CompleteObject
5600};
5601
5602/// Check whether the special member selected for a given type would be trivial.
5603static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005604 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005605 Sema::CXXSpecialMember CSM,
5606 TrivialSubobjectKind Kind,
5607 bool Diagnose) {
5608 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5609 if (!SubRD)
5610 return true;
5611
5612 CXXMethodDecl *Selected;
5613 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005614 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005615 return true;
5616
5617 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005618 if (ConstRHS)
5619 SubType.addConst();
5620
Richard Smith92f241f2012-12-08 02:53:02 +00005621 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5622 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5623 << Kind << SubType.getUnqualifiedType();
5624 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5625 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5626 } else if (!Selected)
5627 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5628 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5629 else if (Selected->isUserProvided()) {
5630 if (Kind == TSK_CompleteObject)
5631 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5632 << Kind << SubType.getUnqualifiedType() << CSM;
5633 else {
5634 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5635 << Kind << SubType.getUnqualifiedType() << CSM;
5636 S.Diag(Selected->getLocation(), diag::note_declared_at);
5637 }
5638 } else {
5639 if (Kind != TSK_CompleteObject)
5640 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5641 << Kind << SubType.getUnqualifiedType() << CSM;
5642
5643 // Explain why the defaulted or deleted special member isn't trivial.
5644 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5645 }
5646 }
5647
5648 return false;
5649}
5650
5651/// Check whether the members of a class type allow a special member to be
5652/// trivial.
5653static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5654 Sema::CXXSpecialMember CSM,
5655 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005656 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005657 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5658 continue;
5659
5660 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5661
5662 // Pretend anonymous struct or union members are members of this class.
5663 if (FI->isAnonymousStructOrUnion()) {
5664 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5665 CSM, ConstArg, Diagnose))
5666 return false;
5667 continue;
5668 }
5669
5670 // C++11 [class.ctor]p5:
5671 // A default constructor is trivial if [...]
5672 // -- no non-static data member of its class has a
5673 // brace-or-equal-initializer
5674 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5675 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005676 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005677 return false;
5678 }
5679
5680 // Objective C ARC 4.3.5:
5681 // [...] nontrivally ownership-qualified types are [...] not trivially
5682 // default constructible, copy constructible, move constructible, copy
5683 // assignable, move assignable, or destructible [...]
5684 if (S.getLangOpts().ObjCAutoRefCount &&
5685 FieldType.hasNonTrivialObjCLifetime()) {
5686 if (Diagnose)
5687 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5688 << RD << FieldType.getObjCLifetime();
5689 return false;
5690 }
5691
Richard Smith41c35d62013-11-27 03:39:20 +00005692 bool ConstRHS = ConstArg && !FI->isMutable();
5693 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5694 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005695 return false;
5696 }
5697
5698 return true;
5699}
5700
5701/// Diagnose why the specified class does not have a trivial special member of
5702/// the given kind.
5703void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5704 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005705
Richard Smith41c35d62013-11-27 03:39:20 +00005706 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5707 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005708 TSK_CompleteObject, /*Diagnose*/true);
5709}
5710
5711/// Determine whether a defaulted or deleted special member function is trivial,
5712/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5713/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5714bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5715 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005716 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5717
5718 CXXRecordDecl *RD = MD->getParent();
5719
5720 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005721
Richard Smith2002bfe2013-11-04 02:02:27 +00005722 // C++11 [class.copy]p12, p25: [DR1593]
5723 // A [special member] is trivial if [...] its parameter-type-list is
5724 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005725 switch (CSM) {
5726 case CXXDefaultConstructor:
5727 case CXXDestructor:
5728 // Trivial default constructors and destructors cannot have parameters.
5729 break;
5730
5731 case CXXCopyConstructor:
5732 case CXXCopyAssignment: {
5733 // Trivial copy operations always have const, non-volatile parameter types.
5734 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005735 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005736 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5737 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5738 if (Diagnose)
5739 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5740 << Param0->getSourceRange() << Param0->getType()
5741 << Context.getLValueReferenceType(
5742 Context.getRecordType(RD).withConst());
5743 return false;
5744 }
5745 break;
5746 }
5747
5748 case CXXMoveConstructor:
5749 case CXXMoveAssignment: {
5750 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005751 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005752 const RValueReferenceType *RT =
5753 Param0->getType()->getAs<RValueReferenceType>();
5754 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5755 if (Diagnose)
5756 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5757 << Param0->getSourceRange() << Param0->getType()
5758 << Context.getRValueReferenceType(Context.getRecordType(RD));
5759 return false;
5760 }
5761 break;
5762 }
5763
5764 case CXXInvalid:
5765 llvm_unreachable("not a special member");
5766 }
5767
Richard Smith92f241f2012-12-08 02:53:02 +00005768 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5769 if (Diagnose)
5770 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5771 diag::note_nontrivial_default_arg)
5772 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5773 return false;
5774 }
5775 if (MD->isVariadic()) {
5776 if (Diagnose)
5777 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5778 return false;
5779 }
5780
5781 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5782 // A copy/move [constructor or assignment operator] is trivial if
5783 // -- the [member] selected to copy/move each direct base class subobject
5784 // is trivial
5785 //
5786 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5787 // A [default constructor or destructor] is trivial if
5788 // -- all the direct base classes have trivial [default constructors or
5789 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005790 for (const auto &BI : RD->bases())
5791 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005792 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005793 return false;
5794
5795 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5796 // A copy/move [constructor or assignment operator] for a class X is
5797 // trivial if
5798 // -- for each non-static data member of X that is of class type (or array
5799 // thereof), the constructor selected to copy/move that member is
5800 // trivial
5801 //
5802 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5803 // A [default constructor or destructor] is trivial if
5804 // -- for all of the non-static data members of its class that are of class
5805 // type (or array thereof), each such class has a trivial [default
5806 // constructor or destructor]
5807 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5808 return false;
5809
5810 // C++11 [class.dtor]p5:
5811 // A destructor is trivial if [...]
5812 // -- the destructor is not virtual
5813 if (CSM == CXXDestructor && MD->isVirtual()) {
5814 if (Diagnose)
5815 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5816 return false;
5817 }
5818
5819 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5820 // A [special member] for class X is trivial if [...]
5821 // -- class X has no virtual functions and no virtual base classes
5822 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5823 if (!Diagnose)
5824 return false;
5825
5826 if (RD->getNumVBases()) {
5827 // Check for virtual bases. We already know that the corresponding
5828 // member in all bases is trivial, so vbases must all be direct.
5829 CXXBaseSpecifier &BS = *RD->vbases_begin();
5830 assert(BS.isVirtual());
5831 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5832 return false;
5833 }
5834
5835 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005836 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005837 if (MI->isVirtual()) {
5838 SourceLocation MLoc = MI->getLocStart();
5839 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5840 return false;
5841 }
5842 }
5843
5844 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5845 }
5846
5847 // Looks like it's trivial!
5848 return true;
5849}
5850
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005851/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005852namespace {
5853 struct FindHiddenVirtualMethodData {
5854 Sema *S;
5855 CXXMethodDecl *Method;
5856 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005857 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005858 };
5859}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005860
David Blaikie282c92a2012-10-19 00:53:08 +00005861/// \brief Check whether any most overriden method from MD in Methods
5862static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5863 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5864 if (MD->size_overridden_methods() == 0)
5865 return Methods.count(MD->getCanonicalDecl());
5866 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5867 E = MD->end_overridden_methods();
5868 I != E; ++I)
5869 if (CheckMostOverridenMethods(*I, Methods))
5870 return true;
5871 return false;
5872}
5873
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005874/// \brief Member lookup function that determines whether a given C++
5875/// method overloads virtual methods in a base class without overriding any,
5876/// to be used with CXXRecordDecl::lookupInBases().
5877static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5878 CXXBasePath &Path,
5879 void *UserData) {
5880 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5881
5882 FindHiddenVirtualMethodData &Data
5883 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5884
5885 DeclarationName Name = Data.Method->getDeclName();
5886 assert(Name.getNameKind() == DeclarationName::Identifier);
5887
5888 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005889 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005890 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005891 !Path.Decls.empty();
5892 Path.Decls = Path.Decls.slice(1)) {
5893 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005894 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005895 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005896 foundSameNameMethod = true;
5897 // Interested only in hidden virtual methods.
5898 if (!MD->isVirtual())
5899 continue;
5900 // If the method we are checking overrides a method from its base
5901 // don't warn about the other overloaded methods.
5902 if (!Data.S->IsOverload(Data.Method, MD, false))
5903 return true;
5904 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005905 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005906 overloadedMethods.push_back(MD);
5907 }
5908 }
5909
5910 if (foundSameNameMethod)
5911 Data.OverloadedMethods.append(overloadedMethods.begin(),
5912 overloadedMethods.end());
5913 return foundSameNameMethod;
5914}
5915
David Blaikie282c92a2012-10-19 00:53:08 +00005916/// \brief Add the most overriden methods from MD to Methods
5917static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5918 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5919 if (MD->size_overridden_methods() == 0)
5920 Methods.insert(MD->getCanonicalDecl());
5921 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5922 E = MD->end_overridden_methods();
5923 I != E; ++I)
5924 AddMostOverridenMethods(*I, Methods);
5925}
5926
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005927/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005928/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005929void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5930 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005931 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005932 return;
5933
5934 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5935 /*bool RecordPaths=*/false,
5936 /*bool DetectVirtual=*/false);
5937 FindHiddenVirtualMethodData Data;
5938 Data.Method = MD;
5939 Data.S = this;
5940
5941 // Keep the base methods that were overriden or introduced in the subclass
5942 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005943 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005944 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5945 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5946 NamedDecl *ND = *I;
5947 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005948 ND = shad->getTargetDecl();
5949 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5950 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005951 }
5952
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005953 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5954 OverloadedMethods = Data.OverloadedMethods;
5955}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005956
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005957void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5958 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5959 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5960 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5961 PartialDiagnostic PD = PDiag(
5962 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5963 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5964 Diag(overloadedMD->getLocation(), PD);
5965 }
5966}
5967
5968/// \brief Diagnose methods which overload virtual methods in a base class
5969/// without overriding any.
5970void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5971 if (MD->isInvalidDecl())
5972 return;
5973
5974 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5975 MD->getLocation()) == DiagnosticsEngine::Ignored)
5976 return;
5977
5978 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5979 FindHiddenVirtualMethods(MD, OverloadedMethods);
5980 if (!OverloadedMethods.empty()) {
5981 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5982 << MD << (OverloadedMethods.size() > 1);
5983
5984 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005985 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005986}
5987
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005988void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005989 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005990 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005991 SourceLocation RBrac,
5992 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005993 if (!TagDecl)
5994 return;
Mike Stump11289f42009-09-09 15:08:12 +00005995
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005996 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005997
Rafael Espindola06e1b132012-07-12 04:32:30 +00005998 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5999 if (l->getKind() != AttributeList::AT_Visibility)
6000 continue;
6001 l->setInvalid();
6002 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6003 l->getName();
6004 }
6005
David Blaikie751c5582011-09-22 02:58:26 +00006006 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006007 // strict aliasing violation!
6008 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006009 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006010
Douglas Gregor0be31a22010-07-02 17:43:08 +00006011 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006012 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006013}
6014
Douglas Gregor05379422008-11-03 17:51:48 +00006015/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6016/// special functions, such as the default constructor, copy
6017/// constructor, or destructor, to the given C++ class (C++
6018/// [special]p1). This routine can only be executed just before the
6019/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006020void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006021 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006022 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006023
Richard Smith6b02d462012-12-08 08:32:28 +00006024 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006025 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006026
Richard Smith6b02d462012-12-08 08:32:28 +00006027 // If the properties or semantics of the copy constructor couldn't be
6028 // determined while the class was being declared, force a declaration
6029 // of it now.
6030 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6031 DeclareImplicitCopyConstructor(ClassDecl);
6032 }
6033
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006034 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006035 ++ASTContext::NumImplicitMoveConstructors;
6036
Richard Smith6b02d462012-12-08 08:32:28 +00006037 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6038 DeclareImplicitMoveConstructor(ClassDecl);
6039 }
6040
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006041 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6042 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006043
6044 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006045 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006046 // it shows up in the right place in the vtable and that we diagnose
6047 // problems with the implicit exception specification.
6048 if (ClassDecl->isDynamicClass() ||
6049 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006050 DeclareImplicitCopyAssignment(ClassDecl);
6051 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006052
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006053 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006054 ++ASTContext::NumImplicitMoveAssignmentOperators;
6055
6056 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006057 if (ClassDecl->isDynamicClass() ||
6058 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006059 DeclareImplicitMoveAssignment(ClassDecl);
6060 }
6061
Douglas Gregor7454c562010-07-02 20:37:36 +00006062 if (!ClassDecl->hasUserDeclaredDestructor()) {
6063 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006064
6065 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006066 // have to declare the destructor immediately. This ensures that, e.g., it
6067 // shows up in the right place in the vtable and that we diagnose problems
6068 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006069 if (ClassDecl->isDynamicClass() ||
6070 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006071 DeclareImplicitDestructor(ClassDecl);
6072 }
Douglas Gregor05379422008-11-03 17:51:48 +00006073}
6074
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006075unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006076 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006077 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006078
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006079 // The order of template parameters is not important here. All names
6080 // get added to the same scope.
6081 SmallVector<TemplateParameterList *, 4> ParameterLists;
6082
6083 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6084 D = TD->getTemplatedDecl();
6085
6086 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6087 ParameterLists.push_back(PSD->getTemplateParameters());
6088
6089 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6090 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6091 ParameterLists.push_back(DD->getTemplateParameterList(i));
6092
6093 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6094 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6095 ParameterLists.push_back(FTD->getTemplateParameters());
6096 }
6097 }
6098
6099 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6100 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6101 ParameterLists.push_back(TD->getTemplateParameterList(i));
6102
6103 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6104 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6105 ParameterLists.push_back(CTD->getTemplateParameters());
6106 }
6107 }
6108
6109 unsigned Count = 0;
6110 for (TemplateParameterList *Params : ParameterLists) {
6111 if (Params->size() > 0)
6112 // Ignore explicit specializations; they don't contribute to the template
6113 // depth.
6114 ++Count;
6115 for (NamedDecl *Param : *Params) {
6116 if (Param->getDeclName()) {
6117 S->AddDecl(Param);
6118 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006119 }
6120 }
6121 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006122
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006123 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006124}
6125
John McCall48871652010-08-21 09:40:31 +00006126void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006127 if (!RecordD) return;
6128 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006129 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006130 PushDeclContext(S, Record);
6131}
6132
John McCall48871652010-08-21 09:40:31 +00006133void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006134 if (!RecordD) return;
6135 PopDeclContext();
6136}
6137
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006138/// This is used to implement the constant expression evaluation part of the
6139/// attribute enable_if extension. There is nothing in standard C++ which would
6140/// require reentering parameters.
6141void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6142 if (!Param)
6143 return;
6144
6145 S->AddDecl(Param);
6146 if (Param->getDeclName())
6147 IdResolver.AddDecl(Param);
6148}
6149
Douglas Gregor4d87df52008-12-16 21:30:33 +00006150/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6151/// parsing a top-level (non-nested) C++ class, and we are now
6152/// parsing those parts of the given Method declaration that could
6153/// not be parsed earlier (C++ [class.mem]p2), such as default
6154/// arguments. This action should enter the scope of the given
6155/// Method declaration as if we had just parsed the qualified method
6156/// name. However, it should not bring the parameters into scope;
6157/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006158void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006159}
6160
6161/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6162/// C++ method declaration. We're (re-)introducing the given
6163/// function parameter into scope for use in parsing later parts of
6164/// the method declaration. For example, we could see an
6165/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006166void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006167 if (!ParamD)
6168 return;
Mike Stump11289f42009-09-09 15:08:12 +00006169
John McCall48871652010-08-21 09:40:31 +00006170 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006171
6172 // If this parameter has an unparsed default argument, clear it out
6173 // to make way for the parsed default argument.
6174 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006175 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006176
John McCall48871652010-08-21 09:40:31 +00006177 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006178 if (Param->getDeclName())
6179 IdResolver.AddDecl(Param);
6180}
6181
6182/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6183/// processing the delayed method declaration for Method. The method
6184/// declaration is now considered finished. There may be a separate
6185/// ActOnStartOfFunctionDef action later (not necessarily
6186/// immediately!) for this method, if it was also defined inside the
6187/// class body.
John McCall48871652010-08-21 09:40:31 +00006188void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006189 if (!MethodD)
6190 return;
Mike Stump11289f42009-09-09 15:08:12 +00006191
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006192 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006193
John McCall48871652010-08-21 09:40:31 +00006194 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006195
6196 // Now that we have our default arguments, check the constructor
6197 // again. It could produce additional diagnostics or affect whether
6198 // the class has implicitly-declared destructors, among other
6199 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006200 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6201 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006202
6203 // Check the default arguments, which we may have added.
6204 if (!Method->isInvalidDecl())
6205 CheckCXXDefaultArguments(Method);
6206}
6207
Douglas Gregor831c93f2008-11-05 20:51:48 +00006208/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006209/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006210/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006211/// emit diagnostics and set the invalid bit to true. In any case, the type
6212/// will be updated to reflect a well-formed type for the constructor and
6213/// returned.
6214QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006215 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006216 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006217
6218 // C++ [class.ctor]p3:
6219 // A constructor shall not be virtual (10.3) or static (9.4). A
6220 // constructor can be invoked for a const, volatile or const
6221 // volatile object. A constructor shall not be declared const,
6222 // volatile, or const volatile (9.3.2).
6223 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006224 if (!D.isInvalidType())
6225 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6226 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6227 << SourceRange(D.getIdentifierLoc());
6228 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006229 }
John McCall8e7d6562010-08-26 03:08:43 +00006230 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006231 if (!D.isInvalidType())
6232 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6233 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6234 << SourceRange(D.getIdentifierLoc());
6235 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006236 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006237 }
Mike Stump11289f42009-09-09 15:08:12 +00006238
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006239 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006240 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006241 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006242 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6243 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006244 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006245 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6246 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006247 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006248 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6249 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006250 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006251 }
Mike Stump11289f42009-09-09 15:08:12 +00006252
Douglas Gregordb9d6642011-01-26 05:01:58 +00006253 // C++0x [class.ctor]p4:
6254 // A constructor shall not be declared with a ref-qualifier.
6255 if (FTI.hasRefQualifier()) {
6256 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6257 << FTI.RefQualifierIsLValueRef
6258 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6259 D.setInvalidType();
6260 }
6261
Douglas Gregor831c93f2008-11-05 20:51:48 +00006262 // Rebuild the function type "R" without any type qualifiers (in
6263 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006264 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006265 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006266 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006267 return R;
6268
6269 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6270 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006271 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006272
6273 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006274}
6275
Douglas Gregor4d87df52008-12-16 21:30:33 +00006276/// CheckConstructor - Checks a fully-formed constructor for
6277/// well-formedness, issuing any diagnostics required. Returns true if
6278/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006279void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006280 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006281 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6282 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006283 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006284
6285 // C++ [class.copy]p3:
6286 // A declaration of a constructor for a class X is ill-formed if
6287 // its first parameter is of type (optionally cv-qualified) X and
6288 // either there are no other parameters or else all other
6289 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006290 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006291 ((Constructor->getNumParams() == 1) ||
6292 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006293 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6294 Constructor->getTemplateSpecializationKind()
6295 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006296 QualType ParamType = Constructor->getParamDecl(0)->getType();
6297 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6298 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006299 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006300 const char *ConstRef
6301 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6302 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006303 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006304 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006305
6306 // FIXME: Rather that making the constructor invalid, we should endeavor
6307 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006308 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006309 }
6310 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006311}
6312
John McCalldeb646e2010-08-04 01:04:25 +00006313/// CheckDestructor - Checks a fully-formed destructor definition for
6314/// well-formedness, issuing any diagnostics required. Returns true
6315/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006316bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006317 CXXRecordDecl *RD = Destructor->getParent();
6318
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006319 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006320 SourceLocation Loc;
6321
6322 if (!Destructor->isImplicit())
6323 Loc = Destructor->getLocation();
6324 else
6325 Loc = RD->getLocation();
6326
6327 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006328 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006329 DeclarationName Name =
6330 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006331 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006332 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006333 // If there's no class-specific operator delete, look up the global
6334 // non-array delete.
6335 if (!OperatorDelete)
6336 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006337
Eli Friedmanfa0df832012-02-02 03:46:19 +00006338 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006339
6340 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006341 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006342
6343 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006344}
6345
Douglas Gregor831c93f2008-11-05 20:51:48 +00006346/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6347/// the well-formednes of the destructor declarator @p D with type @p
6348/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006349/// emit diagnostics and set the declarator to invalid. Even if this happens,
6350/// will be updated to reflect a well-formed type for the destructor and
6351/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006352QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006353 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006354 // C++ [class.dtor]p1:
6355 // [...] A typedef-name that names a class is a class-name
6356 // (7.1.3); however, a typedef-name that names a class shall not
6357 // be used as the identifier in the declarator for a destructor
6358 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006359 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006360 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006361 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006362 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006363 else if (const TemplateSpecializationType *TST =
6364 DeclaratorType->getAs<TemplateSpecializationType>())
6365 if (TST->isTypeAlias())
6366 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6367 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006368
6369 // C++ [class.dtor]p2:
6370 // A destructor is used to destroy objects of its class type. A
6371 // destructor takes no parameters, and no return type can be
6372 // specified for it (not even void). The address of a destructor
6373 // shall not be taken. A destructor shall not be static. A
6374 // destructor can be invoked for a const, volatile or const
6375 // volatile object. A destructor shall not be declared const,
6376 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006377 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006378 if (!D.isInvalidType())
6379 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6380 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006381 << SourceRange(D.getIdentifierLoc())
6382 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6383
John McCall8e7d6562010-08-26 03:08:43 +00006384 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006385 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006386 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006387 // Destructors don't have return types, but the parser will
6388 // happily parse something like:
6389 //
6390 // class X {
6391 // float ~X();
6392 // };
6393 //
6394 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006395 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6396 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6397 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006398 }
Mike Stump11289f42009-09-09 15:08:12 +00006399
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006400 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006401 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006402 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006403 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6404 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006405 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006406 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6407 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006408 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006409 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6410 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006411 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006412 }
6413
Douglas Gregordb9d6642011-01-26 05:01:58 +00006414 // C++0x [class.dtor]p2:
6415 // A destructor shall not be declared with a ref-qualifier.
6416 if (FTI.hasRefQualifier()) {
6417 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6418 << FTI.RefQualifierIsLValueRef
6419 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6420 D.setInvalidType();
6421 }
6422
Douglas Gregor831c93f2008-11-05 20:51:48 +00006423 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006424 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006425 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6426
6427 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006428 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006429 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006430 }
6431
Mike Stump11289f42009-09-09 15:08:12 +00006432 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006433 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006434 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006435 D.setInvalidType();
6436 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006437
6438 // Rebuild the function type "R" without any type qualifiers or
6439 // parameters (in case any of the errors above fired) and with
6440 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006441 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006442 if (!D.isInvalidType())
6443 return R;
6444
Douglas Gregor95755162010-07-01 05:10:53 +00006445 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006446 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6447 EPI.Variadic = false;
6448 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006449 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006450 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006451}
6452
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006453/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6454/// well-formednes of the conversion function declarator @p D with
6455/// type @p R. If there are any errors in the declarator, this routine
6456/// will emit diagnostics and return true. Otherwise, it will return
6457/// false. Either way, the type @p R will be updated to reflect a
6458/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006459void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006460 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006461 // C++ [class.conv.fct]p1:
6462 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006463 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006464 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006465 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006466 if (!D.isInvalidType())
6467 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006468 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6469 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006470 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006471 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006472 }
John McCall212fa2e2010-04-13 00:04:31 +00006473
6474 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6475
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006476 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006477 // Conversion functions don't have return types, but the parser will
6478 // happily parse something like:
6479 //
6480 // class X {
6481 // float operator bool();
6482 // };
6483 //
6484 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006485 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6486 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6487 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006488 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006489 }
6490
John McCall212fa2e2010-04-13 00:04:31 +00006491 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6492
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006493 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006494 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006495 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6496
6497 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006498 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006499 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006500 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006501 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006502 D.setInvalidType();
6503 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006504
John McCall212fa2e2010-04-13 00:04:31 +00006505 // Diagnose "&operator bool()" and other such nonsense. This
6506 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006507 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006508 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006509 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006510 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006511 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006512 }
6513
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006514 // C++ [class.conv.fct]p4:
6515 // The conversion-type-id shall not represent a function type nor
6516 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006517 if (ConvType->isArrayType()) {
6518 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6519 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006520 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006521 } else if (ConvType->isFunctionType()) {
6522 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6523 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006524 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006525 }
6526
6527 // Rebuild the function type "R" without any parameters (in case any
6528 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006529 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006530 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006531 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006532
Douglas Gregor5fb53972009-01-14 15:45:31 +00006533 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006534 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006535 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006536 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006537 diag::warn_cxx98_compat_explicit_conversion_functions :
6538 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006539 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006540}
6541
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006542/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6543/// the declaration of the given C++ conversion function. This routine
6544/// is responsible for recording the conversion function in the C++
6545/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006546Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006547 assert(Conversion && "Expected to receive a conversion function declaration");
6548
Douglas Gregor4287b372008-12-12 08:25:50 +00006549 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006550
6551 // Make sure we aren't redeclaring the conversion function.
6552 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006553
6554 // C++ [class.conv.fct]p1:
6555 // [...] A conversion function is never used to convert a
6556 // (possibly cv-qualified) object to the (possibly cv-qualified)
6557 // same object type (or a reference to it), to a (possibly
6558 // cv-qualified) base class of that type (or a reference to it),
6559 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006560 // FIXME: Suppress this warning if the conversion function ends up being a
6561 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006562 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006563 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006564 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006565 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006566 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6567 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006568 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006569 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006570 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6571 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006572 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006573 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006574 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006575 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006576 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006577 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006578 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006579 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006580 }
6581
Douglas Gregor457104e2010-09-29 04:25:11 +00006582 if (FunctionTemplateDecl *ConversionTemplate
6583 = Conversion->getDescribedFunctionTemplate())
6584 return ConversionTemplate;
6585
John McCall48871652010-08-21 09:40:31 +00006586 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006587}
6588
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006589//===----------------------------------------------------------------------===//
6590// Namespace Handling
6591//===----------------------------------------------------------------------===//
6592
Richard Smith45bb8852012-10-04 22:13:39 +00006593/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6594/// reopened.
6595static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6596 SourceLocation Loc,
6597 IdentifierInfo *II, bool *IsInline,
6598 NamespaceDecl *PrevNS) {
6599 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006600
Richard Smithf501cc32012-10-05 01:46:25 +00006601 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6602 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6603 // inline namespaces, with the intention of bringing names into namespace std.
6604 //
6605 // We support this just well enough to get that case working; this is not
6606 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006607 if (*IsInline && II && II->getName().startswith("__atomic") &&
6608 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006609 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006610 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6611 NS = NS->getPreviousDecl())
6612 NS->setInline(*IsInline);
6613 // Patch up the lookup table for the containing namespace. This isn't really
6614 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006615 for (auto *I : PrevNS->decls())
6616 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006617 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6618 return;
6619 }
6620
6621 if (PrevNS->isInline())
6622 // The user probably just forgot the 'inline', so suggest that it
6623 // be added back.
6624 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6625 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6626 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006627 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006628
6629 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6630 *IsInline = PrevNS->isInline();
6631}
John McCallb1be5232010-08-26 09:15:37 +00006632
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006633/// ActOnStartNamespaceDef - This is called at the start of a namespace
6634/// definition.
John McCall48871652010-08-21 09:40:31 +00006635Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006636 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006637 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006638 SourceLocation IdentLoc,
6639 IdentifierInfo *II,
6640 SourceLocation LBrace,
6641 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006642 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6643 // For anonymous namespace, take the location of the left brace.
6644 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006645 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006646 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006647 bool IsStd = false;
6648 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006649 Scope *DeclRegionScope = NamespcScope->getParent();
6650
Craig Topperc3ec1492014-05-26 06:22:03 +00006651 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006652 if (II) {
6653 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006654 // The identifier in an original-namespace-definition shall not
6655 // have been previously defined in the declarative region in
6656 // which the original-namespace-definition appears. The
6657 // identifier in an original-namespace-definition is the name of
6658 // the namespace. Subsequently in that declarative region, it is
6659 // treated as an original-namespace-name.
6660 //
6661 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006662 // look through using directives, just look for any ordinary names.
6663
6664 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006665 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6666 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006667 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006668 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6669 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6670 ++I) {
6671 if ((*I)->getIdentifierNamespace() & IDNS) {
6672 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006673 break;
6674 }
6675 }
6676
Douglas Gregore57e7522012-01-07 09:11:48 +00006677 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6678
6679 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006680 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006681 if (IsInline != PrevNS->isInline())
6682 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6683 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006684 } else if (PrevDecl) {
6685 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006686 Diag(Loc, diag::err_redefinition_different_kind)
6687 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006688 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006689 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006690 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006691 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006692 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006693 // This is the first "real" definition of the namespace "std", so update
6694 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006695 PrevNS = getStdNamespace();
6696 IsStd = true;
6697 AddToKnown = !IsInline;
6698 } else {
6699 // We've seen this namespace for the first time.
6700 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006701 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006702 } else {
John McCall4fa53422009-10-01 00:25:31 +00006703 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006704
6705 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006706 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006707 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006708 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006709 } else {
6710 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006711 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006712 }
6713
Richard Smith45bb8852012-10-04 22:13:39 +00006714 if (PrevNS && IsInline != PrevNS->isInline())
6715 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6716 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006717 }
6718
6719 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6720 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006721 if (IsInvalid)
6722 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006723
6724 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006725
Douglas Gregore57e7522012-01-07 09:11:48 +00006726 // FIXME: Should we be merging attributes?
6727 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006728 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006729
6730 if (IsStd)
6731 StdNamespace = Namespc;
6732 if (AddToKnown)
6733 KnownNamespaces[Namespc] = false;
6734
6735 if (II) {
6736 PushOnScopeChains(Namespc, DeclRegionScope);
6737 } else {
6738 // Link the anonymous namespace into its parent.
6739 DeclContext *Parent = CurContext->getRedeclContext();
6740 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6741 TU->setAnonymousNamespace(Namespc);
6742 } else {
6743 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006744 }
John McCall4fa53422009-10-01 00:25:31 +00006745
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006746 CurContext->addDecl(Namespc);
6747
John McCall4fa53422009-10-01 00:25:31 +00006748 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6749 // behaves as if it were replaced by
6750 // namespace unique { /* empty body */ }
6751 // using namespace unique;
6752 // namespace unique { namespace-body }
6753 // where all occurrences of 'unique' in a translation unit are
6754 // replaced by the same identifier and this identifier differs
6755 // from all other identifiers in the entire program.
6756
6757 // We just create the namespace with an empty name and then add an
6758 // implicit using declaration, just like the standard suggests.
6759 //
6760 // CodeGen enforces the "universally unique" aspect by giving all
6761 // declarations semantically contained within an anonymous
6762 // namespace internal linkage.
6763
Douglas Gregore57e7522012-01-07 09:11:48 +00006764 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006765 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006766 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006767 /* 'using' */ LBrace,
6768 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006769 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006770 /* identifier */ SourceLocation(),
6771 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006772 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006773 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006774 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006775 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006776 }
6777
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006778 ActOnDocumentableDecl(Namespc);
6779
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006780 // Although we could have an invalid decl (i.e. the namespace name is a
6781 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006782 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6783 // for the namespace has the declarations that showed up in that particular
6784 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006785 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006786 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006787}
6788
Sebastian Redla6602e92009-11-23 15:34:23 +00006789/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6790/// is a namespace alias, returns the namespace it points to.
6791static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6792 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6793 return AD->getNamespace();
6794 return dyn_cast_or_null<NamespaceDecl>(D);
6795}
6796
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006797/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6798/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006799void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006800 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6801 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006802 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006803 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006804 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006805 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006806}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006807
John McCall28a0cf72010-08-25 07:42:41 +00006808CXXRecordDecl *Sema::getStdBadAlloc() const {
6809 return cast_or_null<CXXRecordDecl>(
6810 StdBadAlloc.get(Context.getExternalSource()));
6811}
6812
6813NamespaceDecl *Sema::getStdNamespace() const {
6814 return cast_or_null<NamespaceDecl>(
6815 StdNamespace.get(Context.getExternalSource()));
6816}
6817
Douglas Gregorcdf87022010-06-29 17:53:46 +00006818/// \brief Retrieve the special "std" namespace, which may require us to
6819/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006820NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006821 if (!StdNamespace) {
6822 // The "std" namespace has not yet been defined, so build one implicitly.
6823 StdNamespace = NamespaceDecl::Create(Context,
6824 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006825 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006826 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006827 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006828 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006829 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006830 }
6831
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006832 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006833}
6834
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006835bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006836 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006837 "Looking for std::initializer_list outside of C++.");
6838
6839 // We're looking for implicit instantiations of
6840 // template <typename E> class std::initializer_list.
6841
6842 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6843 return false;
6844
Craig Topperc3ec1492014-05-26 06:22:03 +00006845 ClassTemplateDecl *Template = nullptr;
6846 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006847
Sebastian Redl43144e72012-01-17 22:49:58 +00006848 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006849
Sebastian Redl43144e72012-01-17 22:49:58 +00006850 ClassTemplateSpecializationDecl *Specialization =
6851 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6852 if (!Specialization)
6853 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006854
Sebastian Redl43144e72012-01-17 22:49:58 +00006855 Template = Specialization->getSpecializedTemplate();
6856 Arguments = Specialization->getTemplateArgs().data();
6857 } else if (const TemplateSpecializationType *TST =
6858 Ty->getAs<TemplateSpecializationType>()) {
6859 Template = dyn_cast_or_null<ClassTemplateDecl>(
6860 TST->getTemplateName().getAsTemplateDecl());
6861 Arguments = TST->getArgs();
6862 }
6863 if (!Template)
6864 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006865
6866 if (!StdInitializerList) {
6867 // Haven't recognized std::initializer_list yet, maybe this is it.
6868 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6869 if (TemplateClass->getIdentifier() !=
6870 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006871 !getStdNamespace()->InEnclosingNamespaceSetOf(
6872 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006873 return false;
6874 // This is a template called std::initializer_list, but is it the right
6875 // template?
6876 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006877 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006878 return false;
6879 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6880 return false;
6881
6882 // It's the right template.
6883 StdInitializerList = Template;
6884 }
6885
6886 if (Template != StdInitializerList)
6887 return false;
6888
6889 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006890 if (Element)
6891 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006892 return true;
6893}
6894
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006895static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6896 NamespaceDecl *Std = S.getStdNamespace();
6897 if (!Std) {
6898 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006899 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006900 }
6901
6902 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6903 Loc, Sema::LookupOrdinaryName);
6904 if (!S.LookupQualifiedName(Result, Std)) {
6905 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006906 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006907 }
6908 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6909 if (!Template) {
6910 Result.suppressDiagnostics();
6911 // We found something weird. Complain about the first thing we found.
6912 NamedDecl *Found = *Result.begin();
6913 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006914 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006915 }
6916
6917 // We found some template called std::initializer_list. Now verify that it's
6918 // correct.
6919 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006920 if (Params->getMinRequiredArguments() != 1 ||
6921 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006922 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006923 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006924 }
6925
6926 return Template;
6927}
6928
6929QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6930 if (!StdInitializerList) {
6931 StdInitializerList = LookupStdInitializerList(*this, Loc);
6932 if (!StdInitializerList)
6933 return QualType();
6934 }
6935
6936 TemplateArgumentListInfo Args(Loc, Loc);
6937 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6938 Context.getTrivialTypeSourceInfo(Element,
6939 Loc)));
6940 return Context.getCanonicalType(
6941 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6942}
6943
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006944bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6945 // C++ [dcl.init.list]p2:
6946 // A constructor is an initializer-list constructor if its first parameter
6947 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6948 // std::initializer_list<E> for some type E, and either there are no other
6949 // parameters or else all other parameters have default arguments.
6950 if (Ctor->getNumParams() < 1 ||
6951 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6952 return false;
6953
6954 QualType ArgType = Ctor->getParamDecl(0)->getType();
6955 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6956 ArgType = RT->getPointeeType().getUnqualifiedType();
6957
Craig Topperc3ec1492014-05-26 06:22:03 +00006958 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006959}
6960
Douglas Gregora172e082011-03-26 22:25:30 +00006961/// \brief Determine whether a using statement is in a context where it will be
6962/// apply in all contexts.
6963static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6964 switch (CurContext->getDeclKind()) {
6965 case Decl::TranslationUnit:
6966 return true;
6967 case Decl::LinkageSpec:
6968 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6969 default:
6970 return false;
6971 }
6972}
6973
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006974namespace {
6975
6976// Callback to only accept typo corrections that are namespaces.
6977class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006978public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006979 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006980 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006981 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006982 return false;
6983 }
6984};
6985
6986}
6987
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006988static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6989 CXXScopeSpec &SS,
6990 SourceLocation IdentLoc,
6991 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006992 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006993 R.clear();
6994 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006995 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00006996 Validator,
6997 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006998 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006999 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7000 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007001 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007002 S.diagnoseTypo(Corrected,
7003 S.PDiag(diag::err_using_directive_member_suggest)
7004 << Ident << DC << DroppedSpecifier << SS.getRange(),
7005 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007006 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007007 S.diagnoseTypo(Corrected,
7008 S.PDiag(diag::err_using_directive_suggest) << Ident,
7009 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007010 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007011 R.addDecl(Corrected.getCorrectionDecl());
7012 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007013 }
7014 return false;
7015}
7016
John McCall48871652010-08-21 09:40:31 +00007017Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007018 SourceLocation UsingLoc,
7019 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007020 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007021 SourceLocation IdentLoc,
7022 IdentifierInfo *NamespcName,
7023 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007024 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7025 assert(NamespcName && "Invalid NamespcName.");
7026 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007027
7028 // This can only happen along a recovery path.
7029 while (S->getFlags() & Scope::TemplateParamScope)
7030 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007031 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007032
Craig Topperc3ec1492014-05-26 06:22:03 +00007033 UsingDirectiveDecl *UDir = nullptr;
7034 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007035 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007036 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007037
Douglas Gregor34074322009-01-14 22:20:51 +00007038 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007039 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7040 LookupParsedName(R, S, &SS);
7041 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007042 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007043
Douglas Gregorcdf87022010-06-29 17:53:46 +00007044 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007045 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007046 // Allow "using namespace std;" or "using namespace ::std;" even if
7047 // "std" hasn't been defined yet, for GCC compatibility.
7048 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7049 NamespcName->isStr("std")) {
7050 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007051 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007052 R.resolveKind();
7053 }
7054 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007055 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007056 }
7057
John McCall9f3059a2009-10-09 21:13:30 +00007058 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007059 NamedDecl *Named = R.getFoundDecl();
7060 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7061 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007062 // C++ [namespace.udir]p1:
7063 // A using-directive specifies that the names in the nominated
7064 // namespace can be used in the scope in which the
7065 // using-directive appears after the using-directive. During
7066 // unqualified name lookup (3.4.1), the names appear as if they
7067 // were declared in the nearest enclosing namespace which
7068 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007069 // namespace. [Note: in this context, "contains" means "contains
7070 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007071
7072 // Find enclosing context containing both using-directive and
7073 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007074 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007075 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7076 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7077 CommonAncestor = CommonAncestor->getParent();
7078
Sebastian Redla6602e92009-11-23 15:34:23 +00007079 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007080 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007081 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007082
Douglas Gregora172e082011-03-26 22:25:30 +00007083 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007084 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007085 Diag(IdentLoc, diag::warn_using_directive_in_header);
7086 }
7087
Douglas Gregor889ceb72009-02-03 19:21:40 +00007088 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007089 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007090 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007091 }
7092
Richard Smith54ecd982013-02-20 19:22:51 +00007093 if (UDir)
7094 ProcessDeclAttributeList(S, UDir, AttrList);
7095
John McCall48871652010-08-21 09:40:31 +00007096 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007097}
7098
7099void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007100 // If the scope has an associated entity and the using directive is at
7101 // namespace or translation unit scope, add the UsingDirectiveDecl into
7102 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007103 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007104 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007105 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007106 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007107 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007108 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007109 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007110}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007111
Douglas Gregorfec52632009-06-20 00:51:54 +00007112
John McCall48871652010-08-21 09:40:31 +00007113Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007114 AccessSpecifier AS,
7115 bool HasUsingKeyword,
7116 SourceLocation UsingLoc,
7117 CXXScopeSpec &SS,
7118 UnqualifiedId &Name,
7119 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007120 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007121 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007122 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007123
Douglas Gregor220f4272009-11-04 16:30:06 +00007124 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007125 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007126 case UnqualifiedId::IK_Identifier:
7127 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007128 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007129 case UnqualifiedId::IK_ConversionFunctionId:
7130 break;
7131
7132 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007133 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007134 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007135 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007136 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007137 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007138 diag::err_using_decl_constructor)
7139 << SS.getRange();
7140
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007141 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007142
Craig Topperc3ec1492014-05-26 06:22:03 +00007143 return nullptr;
7144
Douglas Gregor220f4272009-11-04 16:30:06 +00007145 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007146 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007147 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007148 return nullptr;
7149
Douglas Gregor220f4272009-11-04 16:30:06 +00007150 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007151 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007152 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007153 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007154 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007155
7156 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7157 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007158 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007159 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007160
Richard Smithc2bc61b2013-03-18 21:12:30 +00007161 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007162 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007163 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007164 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7165 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007166 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007167 }
7168
Douglas Gregorc4356532010-12-16 00:46:58 +00007169 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7170 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007171 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007172
John McCall3f746822009-11-17 05:59:44 +00007173 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007174 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007175 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007176 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007177 if (UD)
7178 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007179
John McCall48871652010-08-21 09:40:31 +00007180 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007181}
7182
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007183/// \brief Determine whether a using declaration considers the given
7184/// declarations as "equivalent", e.g., if they are redeclarations of
7185/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007186static bool
7187IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7188 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007189 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007190
Richard Smithdda56e42011-04-15 14:24:37 +00007191 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007192 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007193 return Context.hasSameType(TD1->getUnderlyingType(),
7194 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007195
7196 return false;
7197}
7198
7199
John McCall84d87672009-12-10 09:41:52 +00007200/// Determines whether to create a using shadow decl for a particular
7201/// decl, given the set of decls existing prior to this using lookup.
7202bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007203 const LookupResult &Previous,
7204 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007205 // Diagnose finding a decl which is not from a base class of the
7206 // current class. We do this now because there are cases where this
7207 // function will silently decide not to build a shadow decl, which
7208 // will pre-empt further diagnostics.
7209 //
7210 // We don't need to do this in C++0x because we do the check once on
7211 // the qualifier.
7212 //
7213 // FIXME: diagnose the following if we care enough:
7214 // struct A { int foo; };
7215 // struct B : A { using A::foo; };
7216 // template <class T> struct C : A {};
7217 // template <class T> struct D : C<T> { using B::foo; } // <---
7218 // This is invalid (during instantiation) in C++03 because B::foo
7219 // resolves to the using decl in B, which is not a base class of D<T>.
7220 // We can't diagnose it immediately because C<T> is an unknown
7221 // specialization. The UsingShadowDecl in D<T> then points directly
7222 // to A::foo, which will look well-formed when we instantiate.
7223 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007224 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007225 DeclContext *OrigDC = Orig->getDeclContext();
7226
7227 // Handle enums and anonymous structs.
7228 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7229 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7230 while (OrigRec->isAnonymousStructOrUnion())
7231 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7232
7233 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7234 if (OrigDC == CurContext) {
7235 Diag(Using->getLocation(),
7236 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007237 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007238 Diag(Orig->getLocation(), diag::note_using_decl_target);
7239 return true;
7240 }
7241
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007242 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007243 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007244 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007245 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007246 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007247 Diag(Orig->getLocation(), diag::note_using_decl_target);
7248 return true;
7249 }
7250 }
7251
7252 if (Previous.empty()) return false;
7253
7254 NamedDecl *Target = Orig;
7255 if (isa<UsingShadowDecl>(Target))
7256 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7257
John McCalla17e83e2009-12-11 02:33:26 +00007258 // If the target happens to be one of the previous declarations, we
7259 // don't have a conflict.
7260 //
7261 // FIXME: but we might be increasing its access, in which case we
7262 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007263 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007264 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007265 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7266 I != E; ++I) {
7267 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007268 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7269 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7270 PrevShadow = Shadow;
7271 FoundEquivalentDecl = true;
7272 }
John McCalla17e83e2009-12-11 02:33:26 +00007273
7274 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7275 }
7276
Richard Smithfd8634a2013-10-23 02:17:46 +00007277 if (FoundEquivalentDecl)
7278 return false;
7279
Alp Tokera2794f92014-01-22 07:29:52 +00007280 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007281 NamedDecl *OldDecl = nullptr;
7282 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7283 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007284 case Ovl_Overload:
7285 return false;
7286
7287 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007288 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007289 break;
Richard Smith18819302014-02-06 01:31:33 +00007290
John McCall84d87672009-12-10 09:41:52 +00007291 // We found a decl with the exact signature.
7292 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007293 // If we're in a record, we want to hide the target, so we
7294 // return true (without a diagnostic) to tell the caller not to
7295 // build a shadow decl.
7296 if (CurContext->isRecord())
7297 return true;
7298
7299 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007300 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007301 break;
7302 }
7303
7304 Diag(Target->getLocation(), diag::note_using_decl_target);
7305 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7306 return true;
7307 }
7308
7309 // Target is not a function.
7310
John McCall84d87672009-12-10 09:41:52 +00007311 if (isa<TagDecl>(Target)) {
7312 // No conflict between a tag and a non-tag.
7313 if (!Tag) return false;
7314
John McCalle29c5cd2009-12-10 19:51:03 +00007315 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007316 Diag(Target->getLocation(), diag::note_using_decl_target);
7317 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7318 return true;
7319 }
7320
7321 // No conflict between a tag and a non-tag.
7322 if (!NonTag) return false;
7323
John McCalle29c5cd2009-12-10 19:51:03 +00007324 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007325 Diag(Target->getLocation(), diag::note_using_decl_target);
7326 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7327 return true;
7328}
7329
John McCall3f746822009-11-17 05:59:44 +00007330/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007331UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007332 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007333 NamedDecl *Orig,
7334 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007335
7336 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007337 NamedDecl *Target = Orig;
7338 if (isa<UsingShadowDecl>(Target)) {
7339 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7340 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007341 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007342
John McCall3f746822009-11-17 05:59:44 +00007343 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007344 = UsingShadowDecl::Create(Context, CurContext,
7345 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007346 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007347
Douglas Gregor457104e2010-09-29 04:25:11 +00007348 Shadow->setAccess(UD->getAccess());
7349 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7350 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007351
7352 Shadow->setPreviousDecl(PrevDecl);
7353
John McCall3f746822009-11-17 05:59:44 +00007354 if (S)
John McCall3969e302009-12-08 07:46:18 +00007355 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007356 else
John McCall3969e302009-12-08 07:46:18 +00007357 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007358
John McCall3969e302009-12-08 07:46:18 +00007359
John McCall84d87672009-12-10 09:41:52 +00007360 return Shadow;
7361}
John McCall3969e302009-12-08 07:46:18 +00007362
John McCall84d87672009-12-10 09:41:52 +00007363/// Hides a using shadow declaration. This is required by the current
7364/// using-decl implementation when a resolvable using declaration in a
7365/// class is followed by a declaration which would hide or override
7366/// one or more of the using decl's targets; for example:
7367///
7368/// struct Base { void foo(int); };
7369/// struct Derived : Base {
7370/// using Base::foo;
7371/// void foo(int);
7372/// };
7373///
7374/// The governing language is C++03 [namespace.udecl]p12:
7375///
7376/// When a using-declaration brings names from a base class into a
7377/// derived class scope, member functions in the derived class
7378/// override and/or hide member functions with the same name and
7379/// parameter types in a base class (rather than conflicting).
7380///
7381/// There are two ways to implement this:
7382/// (1) optimistically create shadow decls when they're not hidden
7383/// by existing declarations, or
7384/// (2) don't create any shadow decls (or at least don't make them
7385/// visible) until we've fully parsed/instantiated the class.
7386/// The problem with (1) is that we might have to retroactively remove
7387/// a shadow decl, which requires several O(n) operations because the
7388/// decl structures are (very reasonably) not designed for removal.
7389/// (2) avoids this but is very fiddly and phase-dependent.
7390void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007391 if (Shadow->getDeclName().getNameKind() ==
7392 DeclarationName::CXXConversionFunctionName)
7393 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7394
John McCall84d87672009-12-10 09:41:52 +00007395 // Remove it from the DeclContext...
7396 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007397
John McCall84d87672009-12-10 09:41:52 +00007398 // ...and the scope, if applicable...
7399 if (S) {
John McCall48871652010-08-21 09:40:31 +00007400 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007401 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007402 }
7403
John McCall84d87672009-12-10 09:41:52 +00007404 // ...and the using decl.
7405 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7406
7407 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007408 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007409}
7410
Richard Smith09d5b3a2014-05-01 00:35:04 +00007411/// Find the base specifier for a base class with the given type.
7412static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7413 QualType DesiredBase,
7414 bool &AnyDependentBases) {
7415 // Check whether the named type is a direct base class.
7416 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7417 for (auto &Base : Derived->bases()) {
7418 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7419 if (CanonicalDesiredBase == BaseType)
7420 return &Base;
7421 if (BaseType->isDependentType())
7422 AnyDependentBases = true;
7423 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007424 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007425}
7426
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007427namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007428class UsingValidatorCCC : public CorrectionCandidateCallback {
7429public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007430 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007431 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007432 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007433 IsInstantiation(IsInstantiation), OldNNS(NNS),
7434 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007435
Craig Toppera798a9d2014-03-02 09:32:10 +00007436 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007437 NamedDecl *ND = Candidate.getCorrectionDecl();
7438
7439 // Keywords are not valid here.
7440 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007441 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007442
7443 // Completely unqualified names are invalid for a 'using' declaration.
7444 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7445 return false;
7446
Richard Smith09d5b3a2014-05-01 00:35:04 +00007447 if (RequireMemberOf) {
7448 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7449 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7450 // No-one ever wants a using-declaration to name an injected-class-name
7451 // of a base class, unless they're declaring an inheriting constructor.
7452 ASTContext &Ctx = ND->getASTContext();
7453 if (!Ctx.getLangOpts().CPlusPlus11)
7454 return false;
7455 QualType FoundType = Ctx.getRecordType(FoundRecord);
7456
7457 // Check that the injected-class-name is named as a member of its own
7458 // type; we don't want to suggest 'using Derived::Base;', since that
7459 // means something else.
7460 NestedNameSpecifier *Specifier =
7461 Candidate.WillReplaceSpecifier()
7462 ? Candidate.getCorrectionSpecifier()
7463 : OldNNS;
7464 if (!Specifier->getAsType() ||
7465 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7466 return false;
7467
7468 // Check that this inheriting constructor declaration actually names a
7469 // direct base class of the current class.
7470 bool AnyDependentBases = false;
7471 if (!findDirectBaseWithType(RequireMemberOf,
7472 Ctx.getRecordType(FoundRecord),
7473 AnyDependentBases) &&
7474 !AnyDependentBases)
7475 return false;
7476 } else {
7477 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7478 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7479 return false;
7480
7481 // FIXME: Check that the base class member is accessible?
7482 }
7483 }
7484
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007485 if (isa<TypeDecl>(ND))
7486 return HasTypenameKeyword || !IsInstantiation;
7487
7488 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007489 }
7490
7491private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007492 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007493 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007494 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007495 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007496};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007497} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007498
John McCalle61f2ba2009-11-18 02:36:19 +00007499/// Builds a using declaration.
7500///
7501/// \param IsInstantiation - Whether this call arises from an
7502/// instantiation of an unresolved using declaration. We treat
7503/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007504NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7505 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007506 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007507 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007508 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007509 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007510 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007511 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007512 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007513 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007514 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007515
Anders Carlssonf038fc22009-08-28 05:49:21 +00007516 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007517
Anders Carlsson59140b32009-08-28 03:16:11 +00007518 if (SS.isEmpty()) {
7519 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007520 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007521 }
Mike Stump11289f42009-09-09 15:08:12 +00007522
John McCall84d87672009-12-10 09:41:52 +00007523 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007524 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007525 ForRedeclaration);
7526 Previous.setHideTags(false);
7527 if (S) {
7528 LookupName(Previous, S);
7529
7530 // It is really dumb that we have to do this.
7531 LookupResult::Filter F = Previous.makeFilter();
7532 while (F.hasNext()) {
7533 NamedDecl *D = F.next();
7534 if (!isDeclInScope(D, CurContext, S))
7535 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007536 // If we found a local extern declaration that's not ordinarily visible,
7537 // and this declaration is being added to a non-block scope, ignore it.
7538 // We're only checking for scope conflicts here, not also for violations
7539 // of the linkage rules.
7540 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7541 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7542 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007543 }
7544 F.done();
7545 } else {
7546 assert(IsInstantiation && "no scope in non-instantiation");
7547 assert(CurContext->isRecord() && "scope not record in instantiation");
7548 LookupQualifiedName(Previous, CurContext);
7549 }
7550
John McCall84d87672009-12-10 09:41:52 +00007551 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007552 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7553 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007554 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007555
7556 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007557 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007558 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007559
John McCall84c16cf2009-11-12 03:15:40 +00007560 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007561 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007562 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007563 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007564 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007565 // FIXME: not all declaration name kinds are legal here
7566 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7567 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007568 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007569 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007570 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007571 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7572 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007573 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007574 D->setAccess(AS);
7575 CurContext->addDecl(D);
7576 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007577 }
John McCallb96ec562009-12-04 22:46:56 +00007578
Richard Smith09d5b3a2014-05-01 00:35:04 +00007579 auto Build = [&](bool Invalid) {
7580 UsingDecl *UD =
7581 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7582 HasTypenameKeyword);
7583 UD->setAccess(AS);
7584 CurContext->addDecl(UD);
7585 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007586 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007587 };
7588 auto BuildInvalid = [&]{ return Build(true); };
7589 auto BuildValid = [&]{ return Build(false); };
7590
7591 if (RequireCompleteDeclContext(SS, LookupContext))
7592 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007593
Richard Smith23d55872012-04-02 01:30:27 +00007594 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007595 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007596 UsingDecl *UD = BuildValid();
7597 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007598 return UD;
7599 }
7600
7601 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007602
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007603 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007604
John McCall3969e302009-12-08 07:46:18 +00007605 // Unlike most lookups, we don't always want to hide tag
7606 // declarations: tag names are visible through the using declaration
7607 // even if hidden by ordinary names, *except* in a dependent context
7608 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007609 if (!IsInstantiation)
7610 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007611
John McCall5dadb652012-04-07 03:04:20 +00007612 // For the purposes of this lookup, we have a base object type
7613 // equal to that of the current context.
7614 if (CurContext->isRecord()) {
7615 R.setBaseObjectType(
7616 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7617 }
7618
John McCall27b18f82009-11-17 02:14:36 +00007619 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007620
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007621 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007622 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007623 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007624 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007625 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007626 R.getLookupKind(), S, &SS, CCC,
7627 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007628 // We reject any correction for which ND would be NULL.
7629 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007630
Richard Smithf9b15102013-08-17 00:46:16 +00007631 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007632 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007633 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7634 << NameInfo.getName() << LookupContext << 0
7635 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007636
7637 // If we corrected to an inheriting constructor, handle it as one.
7638 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7639 if (RD && RD->isInjectedClassName()) {
7640 // Fix up the information we'll use to build the using declaration.
7641 if (Corrected.WillReplaceSpecifier()) {
7642 NestedNameSpecifierLocBuilder Builder;
7643 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7644 QualifierLoc.getSourceRange());
7645 QualifierLoc = Builder.getWithLocInContext(Context);
7646 }
7647
7648 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7649 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007650 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007651
7652 // Build it and process it as an inheriting constructor.
7653 UsingDecl *UD = BuildValid();
7654 CheckInheritingConstructorUsingDecl(UD);
7655 return UD;
7656 }
7657
7658 // FIXME: Pick up all the declarations if we found an overloaded function.
7659 R.setLookupName(Corrected.getCorrection());
7660 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007661 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007662 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007663 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007664 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007665 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007666 }
7667
Richard Smith09d5b3a2014-05-01 00:35:04 +00007668 if (R.isAmbiguous())
7669 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007670
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007671 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007672 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007673 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007674 Diag(IdentLoc, diag::err_using_typename_non_type);
7675 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7676 Diag((*I)->getUnderlyingDecl()->getLocation(),
7677 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007678 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007679 }
7680 } else {
7681 // If we asked for a non-typename and we got a type, error out,
7682 // but only if this is an instantiation of an unresolved using
7683 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007684 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007685 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7686 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007687 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007688 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007689 }
7690
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007691 // C++0x N2914 [namespace.udecl]p6:
7692 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007693 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007694 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7695 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007696 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007697 }
Mike Stump11289f42009-09-09 15:08:12 +00007698
Richard Smith09d5b3a2014-05-01 00:35:04 +00007699 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007700 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007701 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007702 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7703 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007704 }
John McCall3f746822009-11-17 05:59:44 +00007705
7706 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007707}
7708
Sebastian Redl08905022011-02-05 19:23:19 +00007709/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007710bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007711 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007712
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007713 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007714 assert(SourceType &&
7715 "Using decl naming constructor doesn't have type in scope spec.");
7716 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7717
7718 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007719 bool AnyDependentBases = false;
7720 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7721 AnyDependentBases);
7722 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007723 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007724 diag::err_using_decl_constructor_not_in_direct_base)
7725 << UD->getNameInfo().getSourceRange()
7726 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007727 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007728 return true;
7729 }
7730
Richard Smith09d5b3a2014-05-01 00:35:04 +00007731 if (Base)
7732 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007733
7734 return false;
7735}
7736
John McCall84d87672009-12-10 09:41:52 +00007737/// Checks that the given using declaration is not an invalid
7738/// redeclaration. Note that this is checking only for the using decl
7739/// itself, not for any ill-formedness among the UsingShadowDecls.
7740bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007741 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007742 const CXXScopeSpec &SS,
7743 SourceLocation NameLoc,
7744 const LookupResult &Prev) {
7745 // C++03 [namespace.udecl]p8:
7746 // C++0x [namespace.udecl]p10:
7747 // A using-declaration is a declaration and can therefore be used
7748 // repeatedly where (and only where) multiple declarations are
7749 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007750 //
John McCall032092f2010-11-29 18:01:58 +00007751 // That's in non-member contexts.
7752 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007753 return false;
7754
Aaron Ballman4a979672014-01-03 13:56:08 +00007755 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007756
7757 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7758 NamedDecl *D = *I;
7759
7760 bool DTypename;
7761 NestedNameSpecifier *DQual;
7762 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007763 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007764 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007765 } else if (UnresolvedUsingValueDecl *UD
7766 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7767 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007768 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007769 } else if (UnresolvedUsingTypenameDecl *UD
7770 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7771 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007772 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007773 } else continue;
7774
7775 // using decls differ if one says 'typename' and the other doesn't.
7776 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007777 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007778
7779 // using decls differ if they name different scopes (but note that
7780 // template instantiation can cause this check to trigger when it
7781 // didn't before instantiation).
7782 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7783 Context.getCanonicalNestedNameSpecifier(DQual))
7784 continue;
7785
7786 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007787 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007788 return true;
7789 }
7790
7791 return false;
7792}
7793
John McCall3969e302009-12-08 07:46:18 +00007794
John McCallb96ec562009-12-04 22:46:56 +00007795/// Checks that the given nested-name qualifier used in a using decl
7796/// in the current context is appropriately related to the current
7797/// scope. If an error is found, diagnoses it and returns true.
7798bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7799 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007800 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007801 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007802 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007803
John McCall3969e302009-12-08 07:46:18 +00007804 if (!CurContext->isRecord()) {
7805 // C++03 [namespace.udecl]p3:
7806 // C++0x [namespace.udecl]p8:
7807 // A using-declaration for a class member shall be a member-declaration.
7808
7809 // If we weren't able to compute a valid scope, it must be a
7810 // dependent class scope.
7811 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007812 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7813 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007814 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007815
John McCall3969e302009-12-08 07:46:18 +00007816 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7817 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007818
7819 // If we have a complete, non-dependent source type, try to suggest a
7820 // way to get the same effect.
7821 if (!RD)
7822 return true;
7823
7824 // Find what this using-declaration was referring to.
7825 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7826 R.setHideTags(false);
7827 R.suppressDiagnostics();
7828 LookupQualifiedName(R, RD);
7829
7830 if (R.getAsSingle<TypeDecl>()) {
7831 if (getLangOpts().CPlusPlus11) {
7832 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7833 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7834 << 0 // alias declaration
7835 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7836 NameInfo.getName().getAsString() +
7837 " = ");
7838 } else {
7839 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7840 SourceLocation InsertLoc =
7841 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7842 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7843 << 1 // typedef declaration
7844 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7845 << FixItHint::CreateInsertion(
7846 InsertLoc, " " + NameInfo.getName().getAsString());
7847 }
7848 } else if (R.getAsSingle<VarDecl>()) {
7849 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7850 // repeating the type of the static data member here.
7851 FixItHint FixIt;
7852 if (getLangOpts().CPlusPlus11) {
7853 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7854 FixIt = FixItHint::CreateReplacement(
7855 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7856 }
7857
7858 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7859 << 2 // reference declaration
7860 << FixIt;
7861 }
John McCall3969e302009-12-08 07:46:18 +00007862 return true;
7863 }
7864
7865 // Otherwise, everything is known to be fine.
7866 return false;
7867 }
7868
7869 // The current scope is a record.
7870
7871 // If the named context is dependent, we can't decide much.
7872 if (!NamedContext) {
7873 // FIXME: in C++0x, we can diagnose if we can prove that the
7874 // nested-name-specifier does not refer to a base class, which is
7875 // still possible in some cases.
7876
7877 // Otherwise we have to conservatively report that things might be
7878 // okay.
7879 return false;
7880 }
7881
7882 if (!NamedContext->isRecord()) {
7883 // Ideally this would point at the last name in the specifier,
7884 // but we don't have that level of source info.
7885 Diag(SS.getRange().getBegin(),
7886 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007887 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007888 return true;
7889 }
7890
Douglas Gregor7c842292010-12-21 07:41:49 +00007891 if (!NamedContext->isDependentContext() &&
7892 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7893 return true;
7894
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007895 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007896 // C++0x [namespace.udecl]p3:
7897 // In a using-declaration used as a member-declaration, the
7898 // nested-name-specifier shall name a base class of the class
7899 // being defined.
7900
7901 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7902 cast<CXXRecordDecl>(NamedContext))) {
7903 if (CurContext == NamedContext) {
7904 Diag(NameLoc,
7905 diag::err_using_decl_nested_name_specifier_is_current_class)
7906 << SS.getRange();
7907 return true;
7908 }
7909
7910 Diag(SS.getRange().getBegin(),
7911 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007912 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007913 << cast<CXXRecordDecl>(CurContext)
7914 << SS.getRange();
7915 return true;
7916 }
7917
7918 return false;
7919 }
7920
7921 // C++03 [namespace.udecl]p4:
7922 // A using-declaration used as a member-declaration shall refer
7923 // to a member of a base class of the class being defined [etc.].
7924
7925 // Salient point: SS doesn't have to name a base class as long as
7926 // lookup only finds members from base classes. Therefore we can
7927 // diagnose here only if we can prove that that can't happen,
7928 // i.e. if the class hierarchies provably don't intersect.
7929
7930 // TODO: it would be nice if "definitely valid" results were cached
7931 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7932 // need to be repeated.
7933
7934 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007935 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007936
7937 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7938 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7939 Data->Bases.insert(Base);
7940 return true;
7941 }
7942
7943 bool hasDependentBases(const CXXRecordDecl *Class) {
7944 return !Class->forallBases(collect, this);
7945 }
7946
7947 /// Returns true if the base is dependent or is one of the
7948 /// accumulated base classes.
7949 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7950 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7951 return !Data->Bases.count(Base);
7952 }
7953
7954 bool mightShareBases(const CXXRecordDecl *Class) {
7955 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7956 }
7957 };
7958
7959 UserData Data;
7960
7961 // Returns false if we find a dependent base.
7962 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7963 return false;
7964
7965 // Returns false if the class has a dependent base or if it or one
7966 // of its bases is present in the base set of the current context.
7967 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7968 return false;
7969
7970 Diag(SS.getRange().getBegin(),
7971 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007972 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007973 << cast<CXXRecordDecl>(CurContext)
7974 << SS.getRange();
7975
7976 return true;
John McCallb96ec562009-12-04 22:46:56 +00007977}
7978
Richard Smithdda56e42011-04-15 14:24:37 +00007979Decl *Sema::ActOnAliasDeclaration(Scope *S,
7980 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007981 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007982 SourceLocation UsingLoc,
7983 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007984 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007985 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007986 // Skip up to the relevant declaration scope.
7987 while (S->getFlags() & Scope::TemplateParamScope)
7988 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007989 assert((S->getFlags() & Scope::DeclScope) &&
7990 "got alias-declaration outside of declaration scope");
7991
7992 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00007993 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00007994
7995 bool Invalid = false;
7996 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00007997 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00007998 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007999
8000 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008001 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008002
8003 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008004 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008005 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008006 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8007 TInfo->getTypeLoc().getBeginLoc());
8008 }
Richard Smithdda56e42011-04-15 14:24:37 +00008009
8010 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8011 LookupName(Previous, S);
8012
8013 // Warn about shadowing the name of a template parameter.
8014 if (Previous.isSingleResult() &&
8015 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008016 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008017 Previous.clear();
8018 }
8019
8020 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8021 "name in alias declaration must be an identifier");
8022 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8023 Name.StartLocation,
8024 Name.Identifier, TInfo);
8025
8026 NewTD->setAccess(AS);
8027
8028 if (Invalid)
8029 NewTD->setInvalidDecl();
8030
Richard Smith54ecd982013-02-20 19:22:51 +00008031 ProcessDeclAttributeList(S, NewTD, AttrList);
8032
Richard Smith3f1b5d02011-05-05 21:57:07 +00008033 CheckTypedefForVariablyModifiedType(S, NewTD);
8034 Invalid |= NewTD->isInvalidDecl();
8035
Richard Smithdda56e42011-04-15 14:24:37 +00008036 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008037
8038 NamedDecl *NewND;
8039 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008040 TypeAliasTemplateDecl *OldDecl = nullptr;
8041 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008042
8043 if (TemplateParamLists.size() != 1) {
8044 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008045 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8046 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008047 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008048 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008049
8050 // Only consider previous declarations in the same scope.
8051 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8052 /*ExplicitInstantiationOrSpecialization*/false);
8053 if (!Previous.empty()) {
8054 Redeclaration = true;
8055
8056 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8057 if (!OldDecl && !Invalid) {
8058 Diag(UsingLoc, diag::err_redefinition_different_kind)
8059 << Name.Identifier;
8060
8061 NamedDecl *OldD = Previous.getRepresentativeDecl();
8062 if (OldD->getLocation().isValid())
8063 Diag(OldD->getLocation(), diag::note_previous_definition);
8064
8065 Invalid = true;
8066 }
8067
8068 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8069 if (TemplateParameterListsAreEqual(TemplateParams,
8070 OldDecl->getTemplateParameters(),
8071 /*Complain=*/true,
8072 TPL_TemplateMatch))
8073 OldTemplateParams = OldDecl->getTemplateParameters();
8074 else
8075 Invalid = true;
8076
8077 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8078 if (!Invalid &&
8079 !Context.hasSameType(OldTD->getUnderlyingType(),
8080 NewTD->getUnderlyingType())) {
8081 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8082 // but we can't reasonably accept it.
8083 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8084 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8085 if (OldTD->getLocation().isValid())
8086 Diag(OldTD->getLocation(), diag::note_previous_definition);
8087 Invalid = true;
8088 }
8089 }
8090 }
8091
8092 // Merge any previous default template arguments into our parameters,
8093 // and check the parameter list.
8094 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8095 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008096 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008097
8098 TypeAliasTemplateDecl *NewDecl =
8099 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8100 Name.Identifier, TemplateParams,
8101 NewTD);
8102
8103 NewDecl->setAccess(AS);
8104
8105 if (Invalid)
8106 NewDecl->setInvalidDecl();
8107 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008108 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008109
8110 NewND = NewDecl;
8111 } else {
8112 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8113 NewND = NewTD;
8114 }
Richard Smithdda56e42011-04-15 14:24:37 +00008115
8116 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008117 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008118
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008119 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008120 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008121}
8122
John McCall48871652010-08-21 09:40:31 +00008123Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008124 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008125 SourceLocation AliasLoc,
8126 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008127 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008128 SourceLocation IdentLoc,
8129 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008130
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008131 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008132 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8133 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008134
Anders Carlssondca83c42009-03-28 06:23:46 +00008135 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008136 NamedDecl *PrevDecl
8137 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8138 ForRedeclaration);
8139 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Craig Topperc3ec1492014-05-26 06:22:03 +00008140 PrevDecl = nullptr;
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008141
8142 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008143 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008144 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008145 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008146 // FIXME: At some point, we'll want to create the (redundant)
8147 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008148 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008149 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00008150 return nullptr;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008151 }
Mike Stump11289f42009-09-09 15:08:12 +00008152
Anders Carlssondca83c42009-03-28 06:23:46 +00008153 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8154 diag::err_redefinition_different_kind;
8155 Diag(AliasLoc, DiagID) << Alias;
8156 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00008157 return nullptr;
Anders Carlssondca83c42009-03-28 06:23:46 +00008158 }
8159
John McCall27b18f82009-11-17 02:14:36 +00008160 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008161 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008162
John McCall9f3059a2009-10-09 21:13:30 +00008163 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008164 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008165 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008166 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008167 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008168 }
Mike Stump11289f42009-09-09 15:08:12 +00008169
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008170 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008171 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008172 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008173 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008174
John McCalld8d0d432010-02-16 06:53:13 +00008175 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008176 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008177}
8178
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008179Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008180Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8181 CXXMethodDecl *MD) {
8182 CXXRecordDecl *ClassDecl = MD->getParent();
8183
Douglas Gregor6d880b12010-07-01 22:31:05 +00008184 // C++ [except.spec]p14:
8185 // An implicitly declared special member function (Clause 12) shall have an
8186 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008187 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008188 if (ClassDecl->isInvalidDecl())
8189 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008190
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008191 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008192 for (const auto &B : ClassDecl->bases()) {
8193 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008194 continue;
8195
Aaron Ballman574705e2014-03-13 15:41:46 +00008196 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008197 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008198 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8199 // If this is a deleted function, add it anyway. This might be conformant
8200 // with the standard. This might not. I'm not sure. It might not matter.
8201 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008202 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008203 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008204 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008205
8206 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008207 for (const auto &B : ClassDecl->vbases()) {
8208 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008209 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008210 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8211 // If this is a deleted function, add it anyway. This might be conformant
8212 // with the standard. This might not. I'm not sure. It might not matter.
8213 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008214 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008215 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008216 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008217
8218 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008219 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008220 if (F->hasInClassInitializer()) {
8221 if (Expr *E = F->getInClassInitializer())
8222 ExceptSpec.CalledExpr(E);
8223 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008224 // DR1351:
8225 // If the brace-or-equal-initializer of a non-static data member
8226 // invokes a defaulted default constructor of its class or of an
8227 // enclosing class in a potentially evaluated subexpression, the
8228 // program is ill-formed.
8229 //
8230 // This resolution is unworkable: the exception specification of the
8231 // default constructor can be needed in an unevaluated context, in
8232 // particular, in the operand of a noexcept-expression, and we can be
8233 // unable to compute an exception specification for an enclosed class.
8234 //
8235 // We do not allow an in-class initializer to require the evaluation
8236 // of the exception specification for any in-class initializer whose
8237 // definition is not lexically complete.
8238 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008239 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008240 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008241 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8242 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8243 // If this is a deleted function, add it anyway. This might be conformant
8244 // with the standard. This might not. I'm not sure. It might not matter.
8245 // In particular, the problem is that this function never gets called. It
8246 // might just be ill-formed because this function attempts to refer to
8247 // a deleted function here.
8248 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008249 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008250 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008251 }
John McCalldb40c7f2010-12-14 08:05:40 +00008252
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008253 return ExceptSpec;
8254}
8255
Richard Smithc2bc61b2013-03-18 21:12:30 +00008256Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008257Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8258 CXXRecordDecl *ClassDecl = CD->getParent();
8259
8260 // C++ [except.spec]p14:
8261 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008262 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008263 if (ClassDecl->isInvalidDecl())
8264 return ExceptSpec;
8265
8266 // Inherited constructor.
8267 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8268 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8269 // FIXME: Copying or moving the parameters could add extra exceptions to the
8270 // set, as could the default arguments for the inherited constructor. This
8271 // will be addressed when we implement the resolution of core issue 1351.
8272 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8273
8274 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008275 for (const auto &B : ClassDecl->bases()) {
8276 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008277 continue;
8278
Aaron Ballman574705e2014-03-13 15:41:46 +00008279 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008280 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8281 if (BaseClassDecl == InheritedDecl)
8282 continue;
8283 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8284 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008285 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008286 }
8287 }
8288
8289 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008290 for (const auto &B : ClassDecl->vbases()) {
8291 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008292 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8293 if (BaseClassDecl == InheritedDecl)
8294 continue;
8295 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8296 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008297 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008298 }
8299 }
8300
8301 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008302 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008303 if (F->hasInClassInitializer()) {
8304 if (Expr *E = F->getInClassInitializer())
8305 ExceptSpec.CalledExpr(E);
8306 else if (!F->isInvalidDecl())
8307 Diag(CD->getLocation(),
8308 diag::err_in_class_initializer_references_def_ctor) << CD;
8309 } else if (const RecordType *RecordTy
8310 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8311 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8312 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8313 if (Constructor)
8314 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8315 }
8316 }
8317
Richard Smithc2bc61b2013-03-18 21:12:30 +00008318 return ExceptSpec;
8319}
8320
Richard Smith8bf22e52012-11-29 01:34:07 +00008321namespace {
8322/// RAII object to register a special member as being currently declared.
8323struct DeclaringSpecialMember {
8324 Sema &S;
8325 Sema::SpecialMemberDecl D;
8326 bool WasAlreadyBeingDeclared;
8327
8328 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8329 : S(S), D(RD, CSM) {
8330 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8331 if (WasAlreadyBeingDeclared)
8332 // This almost never happens, but if it does, ensure that our cache
8333 // doesn't contain a stale result.
8334 S.SpecialMemberCache.clear();
8335
8336 // FIXME: Register a note to be produced if we encounter an error while
8337 // declaring the special member.
8338 }
8339 ~DeclaringSpecialMember() {
8340 if (!WasAlreadyBeingDeclared)
8341 S.SpecialMembersBeingDeclared.erase(D);
8342 }
8343
8344 /// \brief Are we already trying to declare this special member?
8345 bool isAlreadyBeingDeclared() const {
8346 return WasAlreadyBeingDeclared;
8347 }
8348};
8349}
8350
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008351CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8352 CXXRecordDecl *ClassDecl) {
8353 // C++ [class.ctor]p5:
8354 // A default constructor for a class X is a constructor of class X
8355 // that can be called without an argument. If there is no
8356 // user-declared constructor for class X, a default constructor is
8357 // implicitly declared. An implicitly-declared default constructor
8358 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008359 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008360 "Should not build implicit default constructor!");
8361
Richard Smith8bf22e52012-11-29 01:34:07 +00008362 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8363 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008364 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008365
Richard Smithb5800092012-06-10 05:43:50 +00008366 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8367 CXXDefaultConstructor,
8368 false);
8369
Douglas Gregor6d880b12010-07-01 22:31:05 +00008370 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008371 CanQualType ClassType
8372 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008373 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008374 DeclarationName Name
8375 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008376 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008377 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008378 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8379 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8380 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008381 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008382 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008383 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008384
8385 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008386 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008387 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008388
Richard Smith6b02d462012-12-08 08:32:28 +00008389 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8390 // constructors is easy to compute.
8391 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8392
8393 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008394 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008395
Douglas Gregor9672f922010-07-03 00:47:00 +00008396 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008397 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008398
Douglas Gregor0be31a22010-07-02 17:43:08 +00008399 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008400 PushOnScopeChains(DefaultCon, S, false);
8401 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008402
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008403 return DefaultCon;
8404}
8405
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008406void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8407 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008408 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008409 !Constructor->doesThisDeclarationHaveABody() &&
8410 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008411 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008412
Anders Carlsson423f5d82010-04-23 16:04:08 +00008413 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008414 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008415
Eli Friedmaneaf34142012-10-18 20:14:08 +00008416 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008417 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008418 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008419 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008420 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008421 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008422 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008423 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008424 }
Douglas Gregor73193272010-09-20 16:48:21 +00008425
8426 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008427 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008428
Eli Friedman276dd182013-09-05 00:02:25 +00008429 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008430 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008431
8432 if (ASTMutationListener *L = getASTMutationListener()) {
8433 L->CompletedImplicitDefinition(Constructor);
8434 }
Richard Trieuef64e942013-10-25 00:56:00 +00008435
8436 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008437}
8438
Richard Smith938f40b2011-06-11 17:19:42 +00008439void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008440 // Perform any delayed checks on exception specifications.
8441 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008442}
8443
Richard Smith185be182013-04-10 05:48:59 +00008444namespace {
8445/// Information on inheriting constructors to declare.
8446class InheritingConstructorInfo {
8447public:
8448 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8449 : SemaRef(SemaRef), Derived(Derived) {
8450 // Mark the constructors that we already have in the derived class.
8451 //
8452 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8453 // unless there is a user-declared constructor with the same signature in
8454 // the class where the using-declaration appears.
8455 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8456 }
8457
8458 void inheritAll(CXXRecordDecl *RD) {
8459 visitAll(RD, &InheritingConstructorInfo::inherit);
8460 }
8461
8462private:
8463 /// Information about an inheriting constructor.
8464 struct InheritingConstructor {
8465 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008466 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008467
8468 /// If \c true, a constructor with this signature is already declared
8469 /// in the derived class.
8470 bool DeclaredInDerived;
8471
8472 /// The constructor which is inherited.
8473 const CXXConstructorDecl *BaseCtor;
8474
8475 /// The derived constructor we declared.
8476 CXXConstructorDecl *DerivedCtor;
8477 };
8478
8479 /// Inheriting constructors with a given canonical type. There can be at
8480 /// most one such non-template constructor, and any number of templated
8481 /// constructors.
8482 struct InheritingConstructorsForType {
8483 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008484 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8485 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008486
8487 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8488 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8489 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8490 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8491 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8492 false, S.TPL_TemplateMatch))
8493 return Templates[I].second;
8494 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8495 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008496 }
Richard Smith185be182013-04-10 05:48:59 +00008497
8498 return NonTemplate;
8499 }
8500 };
8501
8502 /// Get or create the inheriting constructor record for a constructor.
8503 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8504 QualType CtorType) {
8505 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8506 .getEntry(SemaRef, Ctor);
8507 }
8508
8509 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8510
8511 /// Process all constructors for a class.
8512 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008513 for (const auto *Ctor : RD->ctors())
8514 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008515 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8516 I(RD->decls_begin()), E(RD->decls_end());
8517 I != E; ++I) {
8518 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8519 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8520 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008521 }
8522 }
Richard Smith185be182013-04-10 05:48:59 +00008523
8524 /// Note that a constructor (or constructor template) was declared in Derived.
8525 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8526 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8527 }
8528
8529 /// Inherit a single constructor.
8530 void inherit(const CXXConstructorDecl *Ctor) {
8531 const FunctionProtoType *CtorType =
8532 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008533 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008534 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8535
8536 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8537
8538 // Core issue (no number yet): the ellipsis is always discarded.
8539 if (EPI.Variadic) {
8540 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8541 SemaRef.Diag(Ctor->getLocation(),
8542 diag::note_using_decl_constructor_ellipsis);
8543 EPI.Variadic = false;
8544 }
8545
8546 // Declare a constructor for each number of parameters.
8547 //
8548 // C++11 [class.inhctor]p1:
8549 // The candidate set of inherited constructors from the class X named in
8550 // the using-declaration consists of [... modulo defects ...] for each
8551 // constructor or constructor template of X, the set of constructors or
8552 // constructor templates that results from omitting any ellipsis parameter
8553 // specification and successively omitting parameters with a default
8554 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008555 unsigned MinParams = minParamsToInherit(Ctor);
8556 unsigned Params = Ctor->getNumParams();
8557 if (Params >= MinParams) {
8558 do
8559 declareCtor(UsingLoc, Ctor,
8560 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008561 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008562 while (Params > MinParams &&
8563 Ctor->getParamDecl(--Params)->hasDefaultArg());
8564 }
Richard Smith185be182013-04-10 05:48:59 +00008565 }
8566
8567 /// Find the using-declaration which specified that we should inherit the
8568 /// constructors of \p Base.
8569 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8570 // No fancy lookup required; just look for the base constructor name
8571 // directly within the derived class.
8572 ASTContext &Context = SemaRef.Context;
8573 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8574 Context.getCanonicalType(Context.getRecordType(Base)));
8575 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8576 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8577 }
8578
8579 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8580 // C++11 [class.inhctor]p3:
8581 // [F]or each constructor template in the candidate set of inherited
8582 // constructors, a constructor template is implicitly declared
8583 if (Ctor->getDescribedFunctionTemplate())
8584 return 0;
8585
8586 // For each non-template constructor in the candidate set of inherited
8587 // constructors other than a constructor having no parameters or a
8588 // copy/move constructor having a single parameter, a constructor is
8589 // implicitly declared [...]
8590 if (Ctor->getNumParams() == 0)
8591 return 1;
8592 if (Ctor->isCopyOrMoveConstructor())
8593 return 2;
8594
8595 // Per discussion on core reflector, never inherit a constructor which
8596 // would become a default, copy, or move constructor of Derived either.
8597 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8598 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8599 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8600 }
8601
8602 /// Declare a single inheriting constructor, inheriting the specified
8603 /// constructor, with the given type.
8604 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8605 QualType DerivedType) {
8606 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8607
8608 // C++11 [class.inhctor]p3:
8609 // ... a constructor is implicitly declared with the same constructor
8610 // characteristics unless there is a user-declared constructor with
8611 // the same signature in the class where the using-declaration appears
8612 if (Entry.DeclaredInDerived)
8613 return;
8614
8615 // C++11 [class.inhctor]p7:
8616 // If two using-declarations declare inheriting constructors with the
8617 // same signature, the program is ill-formed
8618 if (Entry.DerivedCtor) {
8619 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8620 // Only diagnose this once per constructor.
8621 if (Entry.DerivedCtor->isInvalidDecl())
8622 return;
8623 Entry.DerivedCtor->setInvalidDecl();
8624
8625 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8626 SemaRef.Diag(BaseCtor->getLocation(),
8627 diag::note_using_decl_constructor_conflict_current_ctor);
8628 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8629 diag::note_using_decl_constructor_conflict_previous_ctor);
8630 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8631 diag::note_using_decl_constructor_conflict_previous_using);
8632 } else {
8633 // Core issue (no number): if the same inheriting constructor is
8634 // produced by multiple base class constructors from the same base
8635 // class, the inheriting constructor is defined as deleted.
8636 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8637 }
8638
8639 return;
8640 }
8641
8642 ASTContext &Context = SemaRef.Context;
8643 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8644 Context.getCanonicalType(Context.getRecordType(Derived)));
8645 DeclarationNameInfo NameInfo(Name, UsingLoc);
8646
Craig Topperc3ec1492014-05-26 06:22:03 +00008647 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008648 if (const FunctionTemplateDecl *FTD =
8649 BaseCtor->getDescribedFunctionTemplate()) {
8650 TemplateParams = FTD->getTemplateParameters();
8651 // We're reusing template parameters from a different DeclContext. This
8652 // is questionable at best, but works out because the template depth in
8653 // both places is guaranteed to be 0.
8654 // FIXME: Rebuild the template parameters in the new context, and
8655 // transform the function type to refer to them.
8656 }
8657
8658 // Build type source info pointing at the using-declaration. This is
8659 // required by template instantiation.
8660 TypeSourceInfo *TInfo =
8661 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8662 FunctionProtoTypeLoc ProtoLoc =
8663 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8664
8665 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8666 Context, Derived, UsingLoc, NameInfo, DerivedType,
8667 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8668 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8669
8670 // Build an unevaluated exception specification for this constructor.
8671 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8672 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8673 EPI.ExceptionSpecType = EST_Unevaluated;
8674 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008675 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008676 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008677
8678 // Build the parameter declarations.
8679 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008680 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008681 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008682 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008683 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008684 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8685 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008686 PD->setScopeInfo(0, I);
8687 PD->setImplicit();
8688 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008689 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008690 }
8691
8692 // Set up the new constructor.
8693 DerivedCtor->setAccess(BaseCtor->getAccess());
8694 DerivedCtor->setParams(ParamDecls);
8695 DerivedCtor->setInheritedConstructor(BaseCtor);
8696 if (BaseCtor->isDeleted())
8697 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8698
8699 // If this is a constructor template, build the template declaration.
8700 if (TemplateParams) {
8701 FunctionTemplateDecl *DerivedTemplate =
8702 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8703 TemplateParams, DerivedCtor);
8704 DerivedTemplate->setAccess(BaseCtor->getAccess());
8705 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8706 Derived->addDecl(DerivedTemplate);
8707 } else {
8708 Derived->addDecl(DerivedCtor);
8709 }
8710
8711 Entry.BaseCtor = BaseCtor;
8712 Entry.DerivedCtor = DerivedCtor;
8713 }
8714
8715 Sema &SemaRef;
8716 CXXRecordDecl *Derived;
8717 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8718 MapType Map;
8719};
8720}
8721
8722void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8723 // Defer declaring the inheriting constructors until the class is
8724 // instantiated.
8725 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008726 return;
8727
Richard Smith185be182013-04-10 05:48:59 +00008728 // Find base classes from which we might inherit constructors.
8729 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008730 for (const auto &BaseIt : ClassDecl->bases())
8731 if (BaseIt.getInheritConstructors())
8732 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008733
Richard Smith185be182013-04-10 05:48:59 +00008734 // Go no further if we're not inheriting any constructors.
8735 if (InheritedBases.empty())
8736 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008737
Richard Smith185be182013-04-10 05:48:59 +00008738 // Declare the inherited constructors.
8739 InheritingConstructorInfo ICI(*this, ClassDecl);
8740 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8741 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008742}
8743
Richard Smithc2bc61b2013-03-18 21:12:30 +00008744void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8745 CXXConstructorDecl *Constructor) {
8746 CXXRecordDecl *ClassDecl = Constructor->getParent();
8747 assert(Constructor->getInheritedConstructor() &&
8748 !Constructor->doesThisDeclarationHaveABody() &&
8749 !Constructor->isDeleted());
8750
8751 SynthesizedFunctionScope Scope(*this, Constructor);
8752 DiagnosticErrorTrap Trap(Diags);
8753 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8754 Trap.hasErrorOccurred()) {
8755 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8756 << Context.getTagDeclType(ClassDecl);
8757 Constructor->setInvalidDecl();
8758 return;
8759 }
8760
8761 SourceLocation Loc = Constructor->getLocation();
8762 Constructor->setBody(new (Context) CompoundStmt(Loc));
8763
Eli Friedman276dd182013-09-05 00:02:25 +00008764 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008765 MarkVTableUsed(CurrentLocation, ClassDecl);
8766
8767 if (ASTMutationListener *L = getASTMutationListener()) {
8768 L->CompletedImplicitDefinition(Constructor);
8769 }
8770}
8771
8772
Alexis Huntf91729462011-05-12 22:46:25 +00008773Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008774Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8775 CXXRecordDecl *ClassDecl = MD->getParent();
8776
Douglas Gregorf1203042010-07-01 19:09:28 +00008777 // C++ [except.spec]p14:
8778 // An implicitly declared special member function (Clause 12) shall have
8779 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008780 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008781 if (ClassDecl->isInvalidDecl())
8782 return ExceptSpec;
8783
Douglas Gregorf1203042010-07-01 19:09:28 +00008784 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008785 for (const auto &B : ClassDecl->bases()) {
8786 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008787 continue;
8788
Aaron Ballman574705e2014-03-13 15:41:46 +00008789 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8790 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008791 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008792 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008793
Douglas Gregorf1203042010-07-01 19:09:28 +00008794 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008795 for (const auto &B : ClassDecl->vbases()) {
8796 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8797 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008798 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008799 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008800
Douglas Gregorf1203042010-07-01 19:09:28 +00008801 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008802 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008803 if (const RecordType *RecordTy
8804 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008805 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008806 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008807 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008808
Alexis Huntf91729462011-05-12 22:46:25 +00008809 return ExceptSpec;
8810}
8811
8812CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8813 // C++ [class.dtor]p2:
8814 // If a class has no user-declared destructor, a destructor is
8815 // declared implicitly. An implicitly-declared destructor is an
8816 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008817 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008818
Richard Smith8bf22e52012-11-29 01:34:07 +00008819 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8820 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008821 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008822
Douglas Gregor7454c562010-07-02 20:37:36 +00008823 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008824 CanQualType ClassType
8825 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008826 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008827 DeclarationName Name
8828 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008829 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008830 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008831 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008832 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008833 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008834 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008835 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008836 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008837
8838 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008839 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008840 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008841
Richard Smith6b02d462012-12-08 08:32:28 +00008842 AddOverriddenMethods(ClassDecl, Destructor);
8843
8844 // We don't need to use SpecialMemberIsTrivial here; triviality for
8845 // destructors is easy to compute.
8846 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8847
8848 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008849 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008850
Douglas Gregor7454c562010-07-02 20:37:36 +00008851 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008852 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008853
Douglas Gregor7454c562010-07-02 20:37:36 +00008854 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008855 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008856 PushOnScopeChains(Destructor, S, false);
8857 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008858
Douglas Gregorf1203042010-07-01 19:09:28 +00008859 return Destructor;
8860}
8861
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008862void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008863 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008864 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008865 !Destructor->doesThisDeclarationHaveABody() &&
8866 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008867 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008868 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008869 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008870
Douglas Gregor54818f02010-05-12 16:39:35 +00008871 if (Destructor->isInvalidDecl())
8872 return;
8873
Eli Friedmaneaf34142012-10-18 20:14:08 +00008874 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008875
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008876 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008877 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8878 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008879
Douglas Gregor54818f02010-05-12 16:39:35 +00008880 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008881 Diag(CurrentLocation, diag::note_member_synthesized_at)
8882 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8883
8884 Destructor->setInvalidDecl();
8885 return;
8886 }
8887
Douglas Gregor73193272010-09-20 16:48:21 +00008888 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008889 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008890 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008891 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008892
8893 if (ASTMutationListener *L = getASTMutationListener()) {
8894 L->CompletedImplicitDefinition(Destructor);
8895 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008896}
8897
Richard Smith84973e52012-04-21 18:42:51 +00008898/// \brief Perform any semantic analysis which needs to be delayed until all
8899/// pending class member declarations have been parsed.
8900void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008901 // If the context is an invalid C++ class, just suppress these checks.
8902 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8903 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008904 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008905 DelayedDestructorExceptionSpecChecks.clear();
8906 return;
8907 }
8908 }
Richard Smith84973e52012-04-21 18:42:51 +00008909}
8910
Richard Smithd3b5c9082012-07-27 04:22:15 +00008911void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8912 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008913 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008914 "adjusting dtor exception specs was introduced in c++11");
8915
Sebastian Redl623ea822011-05-19 05:13:44 +00008916 // C++11 [class.dtor]p3:
8917 // A declaration of a destructor that does not have an exception-
8918 // specification is implicitly considered to have the same exception-
8919 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008920 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008921 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008922 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008923 return;
8924
Chandler Carruth9a797572011-09-20 04:55:26 +00008925 // Replace the destructor's type, building off the existing one. Fortunately,
8926 // the only thing of interest in the destructor type is its extended info.
8927 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008928 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8929 EPI.ExceptionSpecType = EST_Unevaluated;
8930 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008931 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008932
Sebastian Redl623ea822011-05-19 05:13:44 +00008933 // FIXME: If the destructor has a body that could throw, and the newly created
8934 // spec doesn't allow exceptions, we should emit a warning, because this
8935 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008936 // However, we don't have a body or an exception specification yet, so it
8937 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008938}
8939
Pavel Labath58934982013-08-30 08:52:28 +00008940namespace {
8941/// \brief An abstract base class for all helper classes used in building the
8942// copy/move operators. These classes serve as factory functions and help us
8943// avoid using the same Expr* in the AST twice.
8944class ExprBuilder {
8945 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8946 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8947
8948protected:
8949 static Expr *assertNotNull(Expr *E) {
8950 assert(E && "Expression construction must not fail.");
8951 return E;
8952 }
8953
8954public:
8955 ExprBuilder() {}
8956 virtual ~ExprBuilder() {}
8957
8958 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8959};
8960
8961class RefBuilder: public ExprBuilder {
8962 VarDecl *Var;
8963 QualType VarType;
8964
8965public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008966 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008967 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00008968 }
8969
8970 RefBuilder(VarDecl *Var, QualType VarType)
8971 : Var(Var), VarType(VarType) {}
8972};
8973
8974class ThisBuilder: public ExprBuilder {
8975public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008976 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008977 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00008978 }
8979};
8980
8981class CastBuilder: public ExprBuilder {
8982 const ExprBuilder &Builder;
8983 QualType Type;
8984 ExprValueKind Kind;
8985 const CXXCastPath &Path;
8986
8987public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008988 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008989 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8990 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008991 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00008992 }
8993
8994 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8995 const CXXCastPath &Path)
8996 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8997};
8998
8999class DerefBuilder: public ExprBuilder {
9000 const ExprBuilder &Builder;
9001
9002public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009003 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009004 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009005 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009006 }
9007
9008 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9009};
9010
9011class MemberBuilder: public ExprBuilder {
9012 const ExprBuilder &Builder;
9013 QualType Type;
9014 CXXScopeSpec SS;
9015 bool IsArrow;
9016 LookupResult &MemberLookup;
9017
9018public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009019 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009020 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009021 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009022 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009023 }
9024
9025 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9026 LookupResult &MemberLookup)
9027 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9028 MemberLookup(MemberLookup) {}
9029};
9030
9031class MoveCastBuilder: public ExprBuilder {
9032 const ExprBuilder &Builder;
9033
9034public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009035 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009036 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9037 }
9038
9039 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9040};
9041
9042class LvalueConvBuilder: public ExprBuilder {
9043 const ExprBuilder &Builder;
9044
9045public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009046 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009047 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009048 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009049 }
9050
9051 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9052};
9053
9054class SubscriptBuilder: public ExprBuilder {
9055 const ExprBuilder &Base;
9056 const ExprBuilder &Index;
9057
9058public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009059 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009060 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009061 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009062 }
9063
9064 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9065 : Base(Base), Index(Index) {}
9066};
9067
9068} // end anonymous namespace
9069
Richard Smith41ae3282012-11-14 00:50:40 +00009070/// When generating a defaulted copy or move assignment operator, if a field
9071/// should be copied with __builtin_memcpy rather than via explicit assignments,
9072/// do so. This optimization only applies for arrays of scalars, and for arrays
9073/// of class type where the selected copy/move-assignment operator is trivial.
9074static StmtResult
9075buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009076 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009077 // Compute the size of the memory buffer to be copied.
9078 QualType SizeType = S.Context.getSizeType();
9079 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9080 S.Context.getTypeSizeInChars(T).getQuantity());
9081
9082 // Take the address of the field references for "from" and "to". We
9083 // directly construct UnaryOperators here because semantic analysis
9084 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009085 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009086 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9087 S.Context.getPointerType(From->getType()),
9088 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009089 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009090 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9091 S.Context.getPointerType(To->getType()),
9092 VK_RValue, OK_Ordinary, Loc);
9093
9094 const Type *E = T->getBaseElementTypeUnsafe();
9095 bool NeedsCollectableMemCpy =
9096 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9097
9098 // Create a reference to the __builtin_objc_memmove_collectable function
9099 StringRef MemCpyName = NeedsCollectableMemCpy ?
9100 "__builtin_objc_memmove_collectable" :
9101 "__builtin_memcpy";
9102 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9103 Sema::LookupOrdinaryName);
9104 S.LookupName(R, S.TUScope, true);
9105
9106 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9107 if (!MemCpy)
9108 // Something went horribly wrong earlier, and we will have complained
9109 // about it.
9110 return StmtError();
9111
9112 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009113 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009114 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9115
9116 Expr *CallArgs[] = {
9117 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9118 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009119 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009120 Loc, CallArgs, Loc);
9121
9122 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009123 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009124}
9125
Sebastian Redl22653ba2011-08-30 19:58:05 +00009126/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009127/// \c To.
9128///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009129/// This routine is used to copy/move the members of a class with an
9130/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009131/// copied are arrays, this routine builds for loops to copy them.
9132///
9133/// \param S The Sema object used for type-checking.
9134///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009135/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009136///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009137/// \param T The type of the expressions being copied/moved. Both expressions
9138/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009139///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009140/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009141///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009142/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009143///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009144/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009145/// Otherwise, it's a non-static member subobject.
9146///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009147/// \param Copying Whether we're copying or moving.
9148///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009149/// \param Depth Internal parameter recording the depth of the recursion.
9150///
Richard Smith41ae3282012-11-14 00:50:40 +00009151/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9152/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009153static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009154buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009155 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009156 bool CopyingBaseSubobject, bool Copying,
9157 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009158 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009159 // Each subobject is assigned in the manner appropriate to its type:
9160 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009161 // - if the subobject is of class type, as if by a call to operator= with
9162 // the subobject as the object expression and the corresponding
9163 // subobject of x as a single function argument (as if by explicit
9164 // qualification; that is, ignoring any possible virtual overriding
9165 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009166 //
9167 // C++03 [class.copy]p13:
9168 // - if the subobject is of class type, the copy assignment operator for
9169 // the class is used (as if by explicit qualification; that is,
9170 // ignoring any possible virtual overriding functions in more derived
9171 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009172 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9173 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009174
Douglas Gregorb139cd52010-05-01 20:49:11 +00009175 // Look for operator=.
9176 DeclarationName Name
9177 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9178 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9179 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009180
Richard Smith52c0b582012-11-13 00:54:12 +00009181 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9182 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009183 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009184 LookupResult::Filter F = OpLookup.makeFilter();
9185 while (F.hasNext()) {
9186 NamedDecl *D = F.next();
9187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9188 if (Method->isCopyAssignmentOperator() ||
9189 (!Copying && Method->isMoveAssignmentOperator()))
9190 continue;
9191
9192 F.erase();
9193 }
9194 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009195 }
Richard Smith52c0b582012-11-13 00:54:12 +00009196
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009197 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009198 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009199 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009200 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009201 // ambiguities), we need to cast "this" to that subobject type; to
9202 // ensure that we don't go through the virtual call mechanism, we need
9203 // to qualify the operator= name with the base class (see below). However,
9204 // this means that if the base class has a protected copy assignment
9205 // operator, the protected member access check will fail. So, we
9206 // rewrite "protected" access to "public" access in this case, since we
9207 // know by construction that we're calling from a derived class.
9208 if (CopyingBaseSubobject) {
9209 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9210 L != LEnd; ++L) {
9211 if (L.getAccess() == AS_protected)
9212 L.setAccess(AS_public);
9213 }
9214 }
Richard Smith52c0b582012-11-13 00:54:12 +00009215
Douglas Gregorb139cd52010-05-01 20:49:11 +00009216 // Create the nested-name-specifier that will be used to qualify the
9217 // reference to operator=; this is required to suppress the virtual
9218 // call mechanism.
9219 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009220 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009221 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009222 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009223 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009224 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009225
Douglas Gregorb139cd52010-05-01 20:49:11 +00009226 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009227 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009228 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9229 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009230 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009231 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009232 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009233 /*SuppressQualifierCheck=*/true);
9234 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009235 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009236
Douglas Gregorb139cd52010-05-01 20:49:11 +00009237 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009238
Pavel Labath58934982013-08-30 08:52:28 +00009239 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009240 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009241 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009242 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009243 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009244 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009245
Richard Smith41ae3282012-11-14 00:50:40 +00009246 // If we built a call to a trivial 'operator=' while copying an array,
9247 // bail out. We'll replace the whole shebang with a memcpy.
9248 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9249 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009250 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009251
Richard Smith52c0b582012-11-13 00:54:12 +00009252 // Convert to an expression-statement, and clean up any produced
9253 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009254 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009255 }
John McCallab8c2732010-03-16 06:11:48 +00009256
Richard Smith52c0b582012-11-13 00:54:12 +00009257 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009258 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009259 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009260 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009261 ExprResult Assignment = S.CreateBuiltinBinOp(
9262 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009263 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009264 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009265 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009266 }
Richard Smith52c0b582012-11-13 00:54:12 +00009267
9268 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009269 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009270
Douglas Gregorb139cd52010-05-01 20:49:11 +00009271 // Construct a loop over the array bounds, e.g.,
9272 //
9273 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9274 //
9275 // that will copy each of the array elements.
9276 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009277
Douglas Gregorb139cd52010-05-01 20:49:11 +00009278 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009279 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009280 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009281 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009282 llvm::raw_svector_ostream OS(Str);
9283 OS << "__i" << Depth;
9284 IterationVarName = &S.Context.Idents.get(OS.str());
9285 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009286 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009287 IterationVarName, SizeType,
9288 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009289 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009290
Douglas Gregorb139cd52010-05-01 20:49:11 +00009291 // Initialize the iteration variable to zero.
9292 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009293 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009294
Pavel Labath58934982013-08-30 08:52:28 +00009295 // Creates a reference to the iteration variable.
9296 RefBuilder IterationVarRef(IterationVar, SizeType);
9297 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009298
Douglas Gregorb139cd52010-05-01 20:49:11 +00009299 // Create the DeclStmt that holds the iteration variable.
9300 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009301
Douglas Gregorb139cd52010-05-01 20:49:11 +00009302 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009303 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9304 MoveCastBuilder FromIndexMove(FromIndexCopy);
9305 const ExprBuilder *FromIndex;
9306 if (Copying)
9307 FromIndex = &FromIndexCopy;
9308 else
9309 FromIndex = &FromIndexMove;
9310
9311 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009312
9313 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009314 StmtResult Copy =
9315 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009316 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009317 Copying, Depth + 1);
9318 // Bail out if copying fails or if we determined that we should use memcpy.
9319 if (Copy.isInvalid() || !Copy.get())
9320 return Copy;
9321
9322 // Create the comparison against the array bound.
9323 llvm::APInt Upper
9324 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9325 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009326 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009327 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9328 BO_NE, S.Context.BoolTy,
9329 VK_RValue, OK_Ordinary, Loc, false);
9330
9331 // Create the pre-increment of the iteration variable.
9332 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009333 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9334 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009335
Douglas Gregorb139cd52010-05-01 20:49:11 +00009336 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009337 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009338 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009339 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009340 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009341}
9342
Richard Smith41ae3282012-11-14 00:50:40 +00009343static StmtResult
9344buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009345 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009346 bool CopyingBaseSubobject, bool Copying) {
9347 // Maybe we should use a memcpy?
9348 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9349 T.isTriviallyCopyableType(S.Context))
9350 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9351
9352 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9353 CopyingBaseSubobject,
9354 Copying, 0));
9355
9356 // If we ended up picking a trivial assignment operator for an array of a
9357 // non-trivially-copyable class type, just emit a memcpy.
9358 if (!Result.isInvalid() && !Result.get())
9359 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9360
9361 return Result;
9362}
9363
Richard Smithd3b5c9082012-07-27 04:22:15 +00009364Sema::ImplicitExceptionSpecification
9365Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9366 CXXRecordDecl *ClassDecl = MD->getParent();
9367
9368 ImplicitExceptionSpecification ExceptSpec(*this);
9369 if (ClassDecl->isInvalidDecl())
9370 return ExceptSpec;
9371
9372 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009373 assert(T->getNumParams() == 1 && "not a copy assignment op");
9374 unsigned ArgQuals =
9375 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009376
Douglas Gregor68e11362010-07-01 17:48:08 +00009377 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009378 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009379 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009380
9381 // It is unspecified whether or not an implicit copy assignment operator
9382 // attempts to deduplicate calls to assignment operators of virtual bases are
9383 // made. As such, this exception specification is effectively unspecified.
9384 // Based on a similar decision made for constness in C++0x, we're erring on
9385 // the side of assuming such calls to be made regardless of whether they
9386 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009387 for (const auto &Base : ClassDecl->bases()) {
9388 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009389 continue;
9390
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009391 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009392 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009393 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9394 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009395 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009396 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009397
Aaron Ballman445a9392014-03-13 16:15:17 +00009398 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009399 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009400 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009401 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9402 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009403 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009404 }
9405
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009406 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009407 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009408 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9409 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009410 LookupCopyingAssignment(FieldClassDecl,
9411 ArgQuals | FieldType.getCVRQualifiers(),
9412 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009413 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009414 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009415 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009416
Richard Smithd3b5c9082012-07-27 04:22:15 +00009417 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009418}
9419
9420CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9421 // Note: The following rules are largely analoguous to the copy
9422 // constructor rules. Note that virtual bases are not taken into account
9423 // for determining the argument type of the operator. Note also that
9424 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009425 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009426
Richard Smith8bf22e52012-11-29 01:34:07 +00009427 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9428 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009429 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009430
Alexis Hunt119f3652011-05-14 05:23:20 +00009431 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9432 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009433 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9434 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009435 ArgType = ArgType.withConst();
9436 ArgType = Context.getLValueReferenceType(ArgType);
9437
Richard Smith99005e62013-05-07 03:19:20 +00009438 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9439 CXXCopyAssignment,
9440 Const);
9441
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009442 // An implicitly-declared copy assignment operator is an inline public
9443 // member of its class.
9444 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009445 SourceLocation ClassLoc = ClassDecl->getLocation();
9446 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009447 CXXMethodDecl *CopyAssignment =
9448 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009449 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9450 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009451 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009452 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009453 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009454
9455 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009456 FunctionProtoType::ExtProtoInfo EPI =
9457 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009458 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009459
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009460 // Add the parameter to the operator.
9461 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009462 ClassLoc, ClassLoc,
9463 /*Id=*/nullptr, ArgType,
9464 /*TInfo=*/nullptr, SC_None,
9465 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009466 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009467
Richard Smith6b02d462012-12-08 08:32:28 +00009468 AddOverriddenMethods(ClassDecl, CopyAssignment);
9469
9470 CopyAssignment->setTrivial(
9471 ClassDecl->needsOverloadResolutionForCopyAssignment()
9472 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9473 : ClassDecl->hasTrivialCopyAssignment());
9474
Richard Smith852265f2012-03-30 20:53:28 +00009475 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009476 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009477
Richard Smith6b02d462012-12-08 08:32:28 +00009478 // Note that we have added this copy-assignment operator.
9479 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9480
9481 if (Scope *S = getScopeForContext(ClassDecl))
9482 PushOnScopeChains(CopyAssignment, S, false);
9483 ClassDecl->addDecl(CopyAssignment);
9484
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009485 return CopyAssignment;
9486}
9487
Richard Smithd577fbb2013-06-13 03:23:42 +00009488/// Diagnose an implicit copy operation for a class which is odr-used, but
9489/// which is deprecated because the class has a user-declared copy constructor,
9490/// copy assignment operator, or destructor.
9491static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9492 SourceLocation UseLoc) {
9493 assert(CopyOp->isImplicit());
9494
9495 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009496 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009497
9498 // In Microsoft mode, assignment operations don't affect constructors and
9499 // vice versa.
9500 if (RD->hasUserDeclaredDestructor()) {
9501 UserDeclaredOperation = RD->getDestructor();
9502 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9503 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009504 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009505 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009506 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009507 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009508 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009509 break;
9510 }
9511 }
9512 assert(UserDeclaredOperation);
9513 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9514 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009515 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009516 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009517 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009518 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009519 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009520 break;
9521 }
9522 }
9523 assert(UserDeclaredOperation);
9524 }
9525
9526 if (UserDeclaredOperation) {
9527 S.Diag(UserDeclaredOperation->getLocation(),
9528 diag::warn_deprecated_copy_operation)
9529 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9530 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9531 S.Diag(UseLoc, diag::note_member_synthesized_at)
9532 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9533 : Sema::CXXCopyAssignment)
9534 << RD;
9535 }
9536}
9537
Douglas Gregorb139cd52010-05-01 20:49:11 +00009538void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9539 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009540 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009541 CopyAssignOperator->isOverloadedOperator() &&
9542 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009543 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9544 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009545 "DefineImplicitCopyAssignment called for wrong function");
9546
9547 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9548
9549 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9550 CopyAssignOperator->setInvalidDecl();
9551 return;
9552 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009553
9554 // C++11 [class.copy]p18:
9555 // The [definition of an implicitly declared copy assignment operator] is
9556 // deprecated if the class has a user-declared copy constructor or a
9557 // user-declared destructor.
9558 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9559 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9560
Eli Friedman276dd182013-09-05 00:02:25 +00009561 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009562
Eli Friedmaneaf34142012-10-18 20:14:08 +00009563 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009564 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009565
9566 // C++0x [class.copy]p30:
9567 // The implicitly-defined or explicitly-defaulted copy assignment operator
9568 // for a non-union class X performs memberwise copy assignment of its
9569 // subobjects. The direct base classes of X are assigned first, in the
9570 // order of their declaration in the base-specifier-list, and then the
9571 // immediate non-static data members of X are assigned, in the order in
9572 // which they were declared in the class definition.
9573
9574 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009575 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009576
9577 // The parameter for the "other" object, which we are copying from.
9578 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9579 Qualifiers OtherQuals = Other->getType().getQualifiers();
9580 QualType OtherRefType = Other->getType();
9581 if (const LValueReferenceType *OtherRef
9582 = OtherRefType->getAs<LValueReferenceType>()) {
9583 OtherRefType = OtherRef->getPointeeType();
9584 OtherQuals = OtherRefType.getQualifiers();
9585 }
9586
9587 // Our location for everything implicitly-generated.
9588 SourceLocation Loc = CopyAssignOperator->getLocation();
9589
Pavel Labath58934982013-08-30 08:52:28 +00009590 // Builds a DeclRefExpr for the "other" object.
9591 RefBuilder OtherRef(Other, OtherRefType);
9592
9593 // Builds the "this" pointer.
9594 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009595
9596 // Assign base classes.
9597 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009598 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009599 // Form the assignment:
9600 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009601 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009602 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009603 Invalid = true;
9604 continue;
9605 }
9606
John McCallcf142162010-08-07 06:22:56 +00009607 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009608 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009609
Douglas Gregorb139cd52010-05-01 20:49:11 +00009610 // Construct the "from" expression, which is an implicit cast to the
9611 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009612 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9613 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009614
9615 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009616 DerefBuilder DerefThis(This);
9617 CastBuilder To(DerefThis,
9618 Context.getCVRQualifiedType(
9619 BaseType, CopyAssignOperator->getTypeQualifiers()),
9620 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009621
9622 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009623 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009624 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009625 /*CopyingBaseSubobject=*/true,
9626 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009627 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009628 Diag(CurrentLocation, diag::note_member_synthesized_at)
9629 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9630 CopyAssignOperator->setInvalidDecl();
9631 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009632 }
9633
9634 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009635 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009636 }
9637
Douglas Gregorb139cd52010-05-01 20:49:11 +00009638 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009639 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009640 if (Field->isUnnamedBitfield())
9641 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009642
9643 if (Field->isInvalidDecl()) {
9644 Invalid = true;
9645 continue;
9646 }
9647
Douglas Gregorb139cd52010-05-01 20:49:11 +00009648 // Check for members of reference type; we can't copy those.
9649 if (Field->getType()->isReferenceType()) {
9650 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9651 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9652 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009653 Diag(CurrentLocation, diag::note_member_synthesized_at)
9654 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009655 Invalid = true;
9656 continue;
9657 }
9658
9659 // Check for members of const-qualified, non-class type.
9660 QualType BaseType = Context.getBaseElementType(Field->getType());
9661 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9662 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9663 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9664 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009665 Diag(CurrentLocation, diag::note_member_synthesized_at)
9666 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009667 Invalid = true;
9668 continue;
9669 }
John McCall1b1a1db2011-06-17 00:18:42 +00009670
9671 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009672 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9673 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009674
9675 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009676 if (FieldType->isIncompleteArrayType()) {
9677 assert(ClassDecl->hasFlexibleArrayMember() &&
9678 "Incomplete array type is not valid");
9679 continue;
9680 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009681
9682 // Build references to the field in the object we're copying from and to.
9683 CXXScopeSpec SS; // Intentionally empty
9684 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9685 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009686 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009687 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009688
9689 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9690
9691 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009692
Douglas Gregorb139cd52010-05-01 20:49:11 +00009693 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009694 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009695 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009696 /*CopyingBaseSubobject=*/false,
9697 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009698 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009699 Diag(CurrentLocation, diag::note_member_synthesized_at)
9700 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9701 CopyAssignOperator->setInvalidDecl();
9702 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009703 }
9704
9705 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009706 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009707 }
9708
9709 if (!Invalid) {
9710 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009711 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009712
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009713 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009714 if (Return.isInvalid())
9715 Invalid = true;
9716 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009717 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009718
9719 if (Trap.hasErrorOccurred()) {
9720 Diag(CurrentLocation, diag::note_member_synthesized_at)
9721 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9722 Invalid = true;
9723 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009724 }
9725 }
9726
9727 if (Invalid) {
9728 CopyAssignOperator->setInvalidDecl();
9729 return;
9730 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009731
9732 StmtResult Body;
9733 {
9734 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009735 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009736 /*isStmtExpr=*/false);
9737 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9738 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009739 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009740
9741 if (ASTMutationListener *L = getASTMutationListener()) {
9742 L->CompletedImplicitDefinition(CopyAssignOperator);
9743 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009744}
9745
Sebastian Redl22653ba2011-08-30 19:58:05 +00009746Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009747Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9748 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009749
Richard Smithd3b5c9082012-07-27 04:22:15 +00009750 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009751 if (ClassDecl->isInvalidDecl())
9752 return ExceptSpec;
9753
9754 // C++0x [except.spec]p14:
9755 // An implicitly declared special member function (Clause 12) shall have an
9756 // exception-specification. [...]
9757
9758 // It is unspecified whether or not an implicit move assignment operator
9759 // attempts to deduplicate calls to assignment operators of virtual bases are
9760 // made. As such, this exception specification is effectively unspecified.
9761 // Based on a similar decision made for constness in C++0x, we're erring on
9762 // the side of assuming such calls to be made regardless of whether they
9763 // actually happen.
9764 // Note that a move constructor is not implicitly declared when there are
9765 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009766 for (const auto &Base : ClassDecl->bases()) {
9767 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009768 continue;
9769
9770 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009771 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009772 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009773 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009774 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009775 }
9776
Aaron Ballman445a9392014-03-13 16:15:17 +00009777 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009778 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009779 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009780 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009781 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009782 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009783 }
9784
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009785 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009786 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009787 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009788 if (CXXMethodDecl *MoveAssign =
9789 LookupMovingAssignment(FieldClassDecl,
9790 FieldType.getCVRQualifiers(),
9791 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009792 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009793 }
9794 }
9795
9796 return ExceptSpec;
9797}
9798
9799CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009800 assert(ClassDecl->needsImplicitMoveAssignment());
9801
Richard Smith8bf22e52012-11-29 01:34:07 +00009802 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9803 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009804 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009805
Sebastian Redl22653ba2011-08-30 19:58:05 +00009806 // Note: The following rules are largely analoguous to the move
9807 // constructor rules.
9808
Sebastian Redl22653ba2011-08-30 19:58:05 +00009809 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9810 QualType RetType = Context.getLValueReferenceType(ArgType);
9811 ArgType = Context.getRValueReferenceType(ArgType);
9812
Richard Smith99005e62013-05-07 03:19:20 +00009813 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9814 CXXMoveAssignment,
9815 false);
9816
Sebastian Redl22653ba2011-08-30 19:58:05 +00009817 // An implicitly-declared move assignment operator is an inline public
9818 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009819 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9820 SourceLocation ClassLoc = ClassDecl->getLocation();
9821 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009822 CXXMethodDecl *MoveAssignment =
9823 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009824 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009825 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009826 MoveAssignment->setAccess(AS_public);
9827 MoveAssignment->setDefaulted();
9828 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009829
Richard Smithd3b5c9082012-07-27 04:22:15 +00009830 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009831 FunctionProtoType::ExtProtoInfo EPI =
9832 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009833 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009834
Sebastian Redl22653ba2011-08-30 19:58:05 +00009835 // Add the parameter to the operator.
9836 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009837 ClassLoc, ClassLoc,
9838 /*Id=*/nullptr, ArgType,
9839 /*TInfo=*/nullptr, SC_None,
9840 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009841 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009842
Richard Smith6b02d462012-12-08 08:32:28 +00009843 AddOverriddenMethods(ClassDecl, MoveAssignment);
9844
9845 MoveAssignment->setTrivial(
9846 ClassDecl->needsOverloadResolutionForMoveAssignment()
9847 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9848 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009849
Richard Smithd951a1d2012-02-18 02:02:13 +00009850 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009851 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9852 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009853 }
9854
Richard Smith6b02d462012-12-08 08:32:28 +00009855 // Note that we have added this copy-assignment operator.
9856 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9857
Sebastian Redl22653ba2011-08-30 19:58:05 +00009858 if (Scope *S = getScopeForContext(ClassDecl))
9859 PushOnScopeChains(MoveAssignment, S, false);
9860 ClassDecl->addDecl(MoveAssignment);
9861
Sebastian Redl22653ba2011-08-30 19:58:05 +00009862 return MoveAssignment;
9863}
9864
Richard Smithb2504bd2013-11-04 04:26:14 +00009865/// Check if we're implicitly defining a move assignment operator for a class
9866/// with virtual bases. Such a move assignment might move-assign the virtual
9867/// base multiple times.
9868static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9869 SourceLocation CurrentLocation) {
9870 assert(!Class->isDependentContext() && "should not define dependent move");
9871
9872 // Only a virtual base could get implicitly move-assigned multiple times.
9873 // Only a non-trivial move assignment can observe this. We only want to
9874 // diagnose if we implicitly define an assignment operator that assigns
9875 // two base classes, both of which move-assign the same virtual base.
9876 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9877 Class->getNumBases() < 2)
9878 return;
9879
9880 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9881 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9882 VBaseMap VBases;
9883
Aaron Ballman574705e2014-03-13 15:41:46 +00009884 for (auto &BI : Class->bases()) {
9885 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009886 while (!Worklist.empty()) {
9887 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9888 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9889
9890 // If the base has no non-trivial move assignment operators,
9891 // we don't care about moves from it.
9892 if (!Base->hasNonTrivialMoveAssignment())
9893 continue;
9894
9895 // If there's nothing virtual here, skip it.
9896 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9897 continue;
9898
9899 // If we're not actually going to call a move assignment for this base,
9900 // or the selected move assignment is trivial, skip it.
9901 Sema::SpecialMemberOverloadResult *SMOR =
9902 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9903 /*ConstArg*/false, /*VolatileArg*/false,
9904 /*RValueThis*/true, /*ConstThis*/false,
9905 /*VolatileThis*/false);
9906 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9907 !SMOR->getMethod()->isMoveAssignmentOperator())
9908 continue;
9909
9910 if (BaseSpec->isVirtual()) {
9911 // We're going to move-assign this virtual base, and its move
9912 // assignment operator is not trivial. If this can happen for
9913 // multiple distinct direct bases of Class, diagnose it. (If it
9914 // only happens in one base, we'll diagnose it when synthesizing
9915 // that base class's move assignment operator.)
9916 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009917 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009918 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009919 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009920 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9921 << Class << Base;
9922 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9923 << (Base->getCanonicalDecl() ==
9924 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9925 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009926 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009927 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009928 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9929 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009930
9931 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +00009932 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +00009933 }
9934 } else {
9935 // Only walk over bases that have defaulted move assignment operators.
9936 // We assume that any user-provided move assignment operator handles
9937 // the multiple-moves-of-vbase case itself somehow.
9938 if (!SMOR->getMethod()->isDefaulted())
9939 continue;
9940
9941 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009942 for (auto &BI : Base->bases())
9943 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009944 }
9945 }
9946 }
9947}
9948
Sebastian Redl22653ba2011-08-30 19:58:05 +00009949void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9950 CXXMethodDecl *MoveAssignOperator) {
9951 assert((MoveAssignOperator->isDefaulted() &&
9952 MoveAssignOperator->isOverloadedOperator() &&
9953 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009954 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9955 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009956 "DefineImplicitMoveAssignment called for wrong function");
9957
9958 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9959
9960 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9961 MoveAssignOperator->setInvalidDecl();
9962 return;
9963 }
9964
Eli Friedman276dd182013-09-05 00:02:25 +00009965 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009966
Eli Friedmaneaf34142012-10-18 20:14:08 +00009967 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009968 DiagnosticErrorTrap Trap(Diags);
9969
9970 // C++0x [class.copy]p28:
9971 // The implicitly-defined or move assignment operator for a non-union class
9972 // X performs memberwise move assignment of its subobjects. The direct base
9973 // classes of X are assigned first, in the order of their declaration in the
9974 // base-specifier-list, and then the immediate non-static data members of X
9975 // are assigned, in the order in which they were declared in the class
9976 // definition.
9977
Richard Smithb2504bd2013-11-04 04:26:14 +00009978 // Issue a warning if our implicit move assignment operator will move
9979 // from a virtual base more than once.
9980 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009981
Sebastian Redl22653ba2011-08-30 19:58:05 +00009982 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009983 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009984
9985 // The parameter for the "other" object, which we are move from.
9986 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9987 QualType OtherRefType = Other->getType()->
9988 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009989 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009990 "Bad argument type of defaulted move assignment");
9991
9992 // Our location for everything implicitly-generated.
9993 SourceLocation Loc = MoveAssignOperator->getLocation();
9994
Pavel Labath58934982013-08-30 08:52:28 +00009995 // Builds a reference to the "other" object.
9996 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009997 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009998 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009999
Pavel Labath58934982013-08-30 08:52:28 +000010000 // Builds the "this" pointer.
10001 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010002
Sebastian Redl22653ba2011-08-30 19:58:05 +000010003 // Assign base classes.
10004 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010005 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010006 // C++11 [class.copy]p28:
10007 // It is unspecified whether subobjects representing virtual base classes
10008 // are assigned more than once by the implicitly-defined copy assignment
10009 // operator.
10010 // FIXME: Do not assign to a vbase that will be assigned by some other base
10011 // class. For a move-assignment, this can result in the vbase being moved
10012 // multiple times.
10013
Sebastian Redl22653ba2011-08-30 19:58:05 +000010014 // Form the assignment:
10015 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010016 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010017 if (!BaseType->isRecordType()) {
10018 Invalid = true;
10019 continue;
10020 }
10021
10022 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010023 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010024
10025 // Construct the "from" expression, which is an implicit cast to the
10026 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010027 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010028
10029 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010030 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010031
10032 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010033 CastBuilder To(DerefThis,
10034 Context.getCVRQualifiedType(
10035 BaseType, MoveAssignOperator->getTypeQualifiers()),
10036 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010037
10038 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010039 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010040 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010041 /*CopyingBaseSubobject=*/true,
10042 /*Copying=*/false);
10043 if (Move.isInvalid()) {
10044 Diag(CurrentLocation, diag::note_member_synthesized_at)
10045 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10046 MoveAssignOperator->setInvalidDecl();
10047 return;
10048 }
10049
10050 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010051 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010052 }
10053
Sebastian Redl22653ba2011-08-30 19:58:05 +000010054 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010055 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010056 if (Field->isUnnamedBitfield())
10057 continue;
10058
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010059 if (Field->isInvalidDecl()) {
10060 Invalid = true;
10061 continue;
10062 }
10063
Sebastian Redl22653ba2011-08-30 19:58:05 +000010064 // Check for members of reference type; we can't move those.
10065 if (Field->getType()->isReferenceType()) {
10066 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10067 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10068 Diag(Field->getLocation(), diag::note_declared_at);
10069 Diag(CurrentLocation, diag::note_member_synthesized_at)
10070 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10071 Invalid = true;
10072 continue;
10073 }
10074
10075 // Check for members of const-qualified, non-class type.
10076 QualType BaseType = Context.getBaseElementType(Field->getType());
10077 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10078 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10079 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10080 Diag(Field->getLocation(), diag::note_declared_at);
10081 Diag(CurrentLocation, diag::note_member_synthesized_at)
10082 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10083 Invalid = true;
10084 continue;
10085 }
10086
10087 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010088 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10089 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010090
10091 QualType FieldType = Field->getType().getNonReferenceType();
10092 if (FieldType->isIncompleteArrayType()) {
10093 assert(ClassDecl->hasFlexibleArrayMember() &&
10094 "Incomplete array type is not valid");
10095 continue;
10096 }
10097
10098 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010099 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10100 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010101 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010102 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010103 MemberBuilder From(MoveOther, OtherRefType,
10104 /*IsArrow=*/false, MemberLookup);
10105 MemberBuilder To(This, getCurrentThisType(),
10106 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010107
Pavel Labath58934982013-08-30 08:52:28 +000010108 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010109 "Member reference with rvalue base must be rvalue except for reference "
10110 "members, which aren't allowed for move assignment.");
10111
Sebastian Redl22653ba2011-08-30 19:58:05 +000010112 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010113 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010114 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010115 /*CopyingBaseSubobject=*/false,
10116 /*Copying=*/false);
10117 if (Move.isInvalid()) {
10118 Diag(CurrentLocation, diag::note_member_synthesized_at)
10119 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10120 MoveAssignOperator->setInvalidDecl();
10121 return;
10122 }
Richard Smith11d19592012-11-12 23:33:00 +000010123
Sebastian Redl22653ba2011-08-30 19:58:05 +000010124 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010125 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010126 }
10127
10128 if (!Invalid) {
10129 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010130 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +000010131
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010132 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010133 if (Return.isInvalid())
10134 Invalid = true;
10135 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010136 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010137
10138 if (Trap.hasErrorOccurred()) {
10139 Diag(CurrentLocation, diag::note_member_synthesized_at)
10140 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10141 Invalid = true;
10142 }
10143 }
10144 }
10145
10146 if (Invalid) {
10147 MoveAssignOperator->setInvalidDecl();
10148 return;
10149 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010150
10151 StmtResult Body;
10152 {
10153 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010154 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010155 /*isStmtExpr=*/false);
10156 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10157 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010158 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010159
10160 if (ASTMutationListener *L = getASTMutationListener()) {
10161 L->CompletedImplicitDefinition(MoveAssignOperator);
10162 }
10163}
10164
Richard Smithd3b5c9082012-07-27 04:22:15 +000010165Sema::ImplicitExceptionSpecification
10166Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10167 CXXRecordDecl *ClassDecl = MD->getParent();
10168
10169 ImplicitExceptionSpecification ExceptSpec(*this);
10170 if (ClassDecl->isInvalidDecl())
10171 return ExceptSpec;
10172
10173 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010174 assert(T->getNumParams() >= 1 && "not a copy ctor");
10175 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010176
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010177 // C++ [except.spec]p14:
10178 // An implicitly declared special member function (Clause 12) shall have an
10179 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010180 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010181 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010182 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010183 continue;
10184
Douglas Gregora6d69502010-07-02 23:41:54 +000010185 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010186 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010187 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010188 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010189 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010190 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010191 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010192 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010193 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010194 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010195 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010196 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010197 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010198 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010199 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010200 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10201 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010202 LookupCopyingConstructor(FieldClassDecl,
10203 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010204 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010205 }
10206 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010207
Richard Smithd3b5c9082012-07-27 04:22:15 +000010208 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010209}
10210
10211CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10212 CXXRecordDecl *ClassDecl) {
10213 // C++ [class.copy]p4:
10214 // If the class definition does not explicitly declare a copy
10215 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010216 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010217
Richard Smith8bf22e52012-11-29 01:34:07 +000010218 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10219 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010220 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010221
Alexis Hunt913820d2011-05-13 06:10:58 +000010222 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10223 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010224 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010225 if (Const)
10226 ArgType = ArgType.withConst();
10227 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010228
Richard Smithb5800092012-06-10 05:43:50 +000010229 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10230 CXXCopyConstructor,
10231 Const);
10232
Douglas Gregor54be3392010-07-01 17:57:27 +000010233 DeclarationName Name
10234 = Context.DeclarationNames.getCXXConstructorName(
10235 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010236 SourceLocation ClassLoc = ClassDecl->getLocation();
10237 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010238
10239 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010240 // member of its class.
10241 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010242 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010243 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010244 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010245 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010246 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010247
Richard Smithd3b5c9082012-07-27 04:22:15 +000010248 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010249 FunctionProtoType::ExtProtoInfo EPI =
10250 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010251 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010252 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010253
Douglas Gregor54be3392010-07-01 17:57:27 +000010254 // Add the parameter to the constructor.
10255 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010256 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010257 /*IdentifierInfo=*/nullptr,
10258 ArgType, /*TInfo=*/nullptr,
10259 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010260 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010261
Richard Smith6b02d462012-12-08 08:32:28 +000010262 CopyConstructor->setTrivial(
10263 ClassDecl->needsOverloadResolutionForCopyConstructor()
10264 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10265 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010266
Richard Smith852265f2012-03-30 20:53:28 +000010267 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010268 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010269
Richard Smith6b02d462012-12-08 08:32:28 +000010270 // Note that we have declared this constructor.
10271 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10272
10273 if (Scope *S = getScopeForContext(ClassDecl))
10274 PushOnScopeChains(CopyConstructor, S, false);
10275 ClassDecl->addDecl(CopyConstructor);
10276
Douglas Gregor54be3392010-07-01 17:57:27 +000010277 return CopyConstructor;
10278}
10279
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010280void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010281 CXXConstructorDecl *CopyConstructor) {
10282 assert((CopyConstructor->isDefaulted() &&
10283 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010284 !CopyConstructor->doesThisDeclarationHaveABody() &&
10285 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010286 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010287
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010288 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010289 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010290
Richard Smithd577fbb2013-06-13 03:23:42 +000010291 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010292 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010293 // deprecated if the class has a user-declared copy assignment operator
10294 // or a user-declared destructor.
10295 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10296 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10297
Eli Friedmaneaf34142012-10-18 20:14:08 +000010298 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010299 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010300
David Blaikie3fc2f912013-01-17 05:26:25 +000010301 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010302 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010303 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010304 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010305 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010306 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010307 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010308 CopyConstructor->setBody(ActOnCompoundStmt(
10309 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010310 /*isStmtExpr=*/ false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010311 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010312
Eli Friedman276dd182013-09-05 00:02:25 +000010313 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010314 if (ASTMutationListener *L = getASTMutationListener()) {
10315 L->CompletedImplicitDefinition(CopyConstructor);
10316 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010317}
10318
Sebastian Redl22653ba2011-08-30 19:58:05 +000010319Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010320Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10321 CXXRecordDecl *ClassDecl = MD->getParent();
10322
Sebastian Redl22653ba2011-08-30 19:58:05 +000010323 // C++ [except.spec]p14:
10324 // An implicitly declared special member function (Clause 12) shall have an
10325 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010326 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010327 if (ClassDecl->isInvalidDecl())
10328 return ExceptSpec;
10329
10330 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010331 for (const auto &B : ClassDecl->bases()) {
10332 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010333 continue;
10334
Aaron Ballman574705e2014-03-13 15:41:46 +000010335 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010336 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010337 CXXConstructorDecl *Constructor =
10338 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010339 // If this is a deleted function, add it anyway. This might be conformant
10340 // with the standard. This might not. I'm not sure. It might not matter.
10341 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010342 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010343 }
10344 }
10345
10346 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010347 for (const auto &B : ClassDecl->vbases()) {
10348 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010349 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010350 CXXConstructorDecl *Constructor =
10351 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010352 // If this is a deleted function, add it anyway. This might be conformant
10353 // with the standard. This might not. I'm not sure. It might not matter.
10354 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010355 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010356 }
10357 }
10358
10359 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010360 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010361 QualType FieldType = Context.getBaseElementType(F->getType());
10362 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10363 CXXConstructorDecl *Constructor =
10364 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010365 // If this is a deleted function, add it anyway. This might be conformant
10366 // with the standard. This might not. I'm not sure. It might not matter.
10367 // In particular, the problem is that this function never gets called. It
10368 // might just be ill-formed because this function attempts to refer to
10369 // a deleted function here.
10370 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010371 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010372 }
10373 }
10374
10375 return ExceptSpec;
10376}
10377
10378CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10379 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010380 assert(ClassDecl->needsImplicitMoveConstructor());
10381
Richard Smith8bf22e52012-11-29 01:34:07 +000010382 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10383 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010384 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010385
Sebastian Redl22653ba2011-08-30 19:58:05 +000010386 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10387 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010388
Richard Smithb5800092012-06-10 05:43:50 +000010389 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10390 CXXMoveConstructor,
10391 false);
10392
Sebastian Redl22653ba2011-08-30 19:58:05 +000010393 DeclarationName Name
10394 = Context.DeclarationNames.getCXXConstructorName(
10395 Context.getCanonicalType(ClassType));
10396 SourceLocation ClassLoc = ClassDecl->getLocation();
10397 DeclarationNameInfo NameInfo(Name, ClassLoc);
10398
Richard Smith99005e62013-05-07 03:19:20 +000010399 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010400 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010401 // member of its class.
10402 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010403 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010404 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010405 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010406 MoveConstructor->setAccess(AS_public);
10407 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010408
Richard Smithd3b5c9082012-07-27 04:22:15 +000010409 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010410 FunctionProtoType::ExtProtoInfo EPI =
10411 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010412 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010413 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010414
Sebastian Redl22653ba2011-08-30 19:58:05 +000010415 // Add the parameter to the constructor.
10416 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10417 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010418 /*IdentifierInfo=*/nullptr,
10419 ArgType, /*TInfo=*/nullptr,
10420 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010421 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010422
Richard Smith6b02d462012-12-08 08:32:28 +000010423 MoveConstructor->setTrivial(
10424 ClassDecl->needsOverloadResolutionForMoveConstructor()
10425 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10426 : ClassDecl->hasTrivialMoveConstructor());
10427
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010428 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010429 ClassDecl->setImplicitMoveConstructorIsDeleted();
10430 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010431 }
10432
10433 // Note that we have declared this constructor.
10434 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10435
10436 if (Scope *S = getScopeForContext(ClassDecl))
10437 PushOnScopeChains(MoveConstructor, S, false);
10438 ClassDecl->addDecl(MoveConstructor);
10439
10440 return MoveConstructor;
10441}
10442
10443void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10444 CXXConstructorDecl *MoveConstructor) {
10445 assert((MoveConstructor->isDefaulted() &&
10446 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010447 !MoveConstructor->doesThisDeclarationHaveABody() &&
10448 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010449 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10450
10451 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10452 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10453
Eli Friedmaneaf34142012-10-18 20:14:08 +000010454 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010455 DiagnosticErrorTrap Trap(Diags);
10456
David Blaikie3fc2f912013-01-17 05:26:25 +000010457 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010458 Trap.hasErrorOccurred()) {
10459 Diag(CurrentLocation, diag::note_member_synthesized_at)
10460 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10461 MoveConstructor->setInvalidDecl();
10462 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010463 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010464 MoveConstructor->setBody(ActOnCompoundStmt(
10465 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010466 /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010467 }
10468
Eli Friedman276dd182013-09-05 00:02:25 +000010469 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010470
10471 if (ASTMutationListener *L = getASTMutationListener()) {
10472 L->CompletedImplicitDefinition(MoveConstructor);
10473 }
10474}
10475
Douglas Gregor74f7d502012-02-15 19:33:52 +000010476bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010477 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010478}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010479
10480void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010481 SourceLocation CurrentLocation,
10482 CXXConversionDecl *Conv) {
10483 CXXRecordDecl *Lambda = Conv->getParent();
10484 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10485 // If we are defining a specialization of a conversion to function-ptr
10486 // cache the deduced template arguments for this specialization
10487 // so that we can use them to retrieve the corresponding call-operator
10488 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010489 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10490
Faisal Vali571df122013-09-29 08:45:24 +000010491 // Retrieve the corresponding call-operator specialization.
10492 if (Lambda->isGenericLambda()) {
10493 assert(Conv->isFunctionTemplateSpecialization());
10494 FunctionTemplateDecl *CallOpTemplate =
10495 CallOp->getDescribedFunctionTemplate();
10496 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010497 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010498 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10499 DeducedTemplateArgs->data(),
10500 DeducedTemplateArgs->size(),
10501 InsertPos);
10502 assert(CallOpSpec &&
10503 "Conversion operator must have a corresponding call operator");
10504 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10505 }
10506 // Mark the call operator referenced (and add to pending instantiations
10507 // if necessary).
10508 // For both the conversion and static-invoker template specializations
10509 // we construct their body's in this function, so no need to add them
10510 // to the PendingInstantiations.
10511 MarkFunctionReferenced(CurrentLocation, CallOp);
10512
Eli Friedmaneaf34142012-10-18 20:14:08 +000010513 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010514 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010515
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010516 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010517 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10518 // ... and get the corresponding specialization for a generic lambda.
10519 if (Lambda->isGenericLambda()) {
10520 assert(DeducedTemplateArgs &&
10521 "Must have deduced template arguments from Conversion Operator");
10522 FunctionTemplateDecl *InvokeTemplate =
10523 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010524 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010525 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10526 DeducedTemplateArgs->data(),
10527 DeducedTemplateArgs->size(),
10528 InsertPos);
10529 assert(InvokeSpec &&
10530 "Must have a corresponding static invoker specialization");
10531 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10532 }
10533 // Construct the body of the conversion function { return __invoke; }.
10534 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010535 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010536 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010537 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010538 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10539 Conv->getLocation(),
10540 Conv->getLocation()));
10541
10542 Conv->markUsed(Context);
10543 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010544
Faisal Vali571df122013-09-29 08:45:24 +000010545 // Fill in the __invoke function with a dummy implementation. IR generation
10546 // will fill in the actual details.
10547 Invoker->markUsed(Context);
10548 Invoker->setReferenced();
10549 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10550
Douglas Gregord3b672c2012-02-16 01:06:16 +000010551 if (ASTMutationListener *L = getASTMutationListener()) {
10552 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010553 L->CompletedImplicitDefinition(Invoker);
10554 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010555}
10556
Faisal Vali571df122013-09-29 08:45:24 +000010557
10558
Douglas Gregord3b672c2012-02-16 01:06:16 +000010559void Sema::DefineImplicitLambdaToBlockPointerConversion(
10560 SourceLocation CurrentLocation,
10561 CXXConversionDecl *Conv)
10562{
Faisal Vali850da1a2013-09-29 17:08:32 +000010563 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010564
Eli Friedman276dd182013-09-05 00:02:25 +000010565 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010566
Eli Friedmaneaf34142012-10-18 20:14:08 +000010567 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010568 DiagnosticErrorTrap Trap(Diags);
10569
Douglas Gregored90df32012-02-22 05:02:47 +000010570 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010571 Expr *This = ActOnCXXThis(CurrentLocation).get();
10572 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010573
Eli Friedman98b01ed2012-03-01 04:01:32 +000010574 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10575 Conv->getLocation(),
10576 Conv, DerefThis);
10577
10578 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10579 // behavior. Note that only the general conversion function does this
10580 // (since it's unusable otherwise); in the case where we inline the
10581 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010582 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010583 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10584 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010585 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010586
10587 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010588 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010589 Conv->setInvalidDecl();
10590 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010591 }
Douglas Gregored90df32012-02-22 05:02:47 +000010592
Douglas Gregored90df32012-02-22 05:02:47 +000010593 // Create the return statement that returns the block from the conversion
10594 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010595 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010596 if (Return.isInvalid()) {
10597 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10598 Conv->setInvalidDecl();
10599 return;
10600 }
10601
10602 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010603 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010604 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010605 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010606 Conv->getLocation()));
10607
Douglas Gregored90df32012-02-22 05:02:47 +000010608 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010609 if (ASTMutationListener *L = getASTMutationListener()) {
10610 L->CompletedImplicitDefinition(Conv);
10611 }
10612}
10613
Douglas Gregord2f70072012-03-10 06:53:13 +000010614/// \brief Determine whether the given list arguments contains exactly one
10615/// "real" (non-default) argument.
10616static bool hasOneRealArgument(MultiExprArg Args) {
10617 switch (Args.size()) {
10618 case 0:
10619 return false;
10620
10621 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010622 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010623 return false;
10624
10625 // fall through
10626 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010627 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010628 }
10629
10630 return false;
10631}
10632
John McCalldadc5752010-08-24 06:29:42 +000010633ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010634Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010635 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010636 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010637 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010638 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010639 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010640 unsigned ConstructKind,
10641 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010642 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010643
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010644 // C++0x [class.copy]p34:
10645 // When certain criteria are met, an implementation is allowed to
10646 // omit the copy/move construction of a class object, even if the
10647 // copy/move constructor and/or destructor for the object have
10648 // side effects. [...]
10649 // - when a temporary class object that has not been bound to a
10650 // reference (12.2) would be copied/moved to a class object
10651 // with the same cv-unqualified type, the copy/move operation
10652 // can be omitted by constructing the temporary object
10653 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010654 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010655 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010656 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010657 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010658 }
Mike Stump11289f42009-09-09 15:08:12 +000010659
10660 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010661 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010662 IsListInitialization, RequiresZeroInit,
10663 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010664}
10665
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010666/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10667/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010668ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010669Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10670 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010671 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010672 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010673 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010674 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010675 unsigned ConstructKind,
10676 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010677 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010678 return CXXConstructExpr::Create(
10679 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10680 HadMultipleCandidates, IsListInitialization, RequiresZeroInit,
10681 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10682 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010683}
10684
John McCall03c48482010-02-02 09:10:11 +000010685void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010686 if (VD->isInvalidDecl()) return;
10687
John McCall03c48482010-02-02 09:10:11 +000010688 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010689 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010690 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010691 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010692
Chandler Carruth86d17d32011-03-27 21:26:48 +000010693 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010694 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010695 CheckDestructorAccess(VD->getLocation(), Destructor,
10696 PDiag(diag::err_access_dtor_var)
10697 << VD->getDeclName()
10698 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010699 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010700
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010701 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010702 if (!VD->hasGlobalStorage()) return;
10703
10704 // Emit warning for non-trivial dtor in global scope (a real global,
10705 // class-static, function-static).
10706 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10707
10708 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010709 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010710 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010711}
10712
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010713/// \brief Given a constructor and the set of arguments provided for the
10714/// constructor, convert the arguments and add any required default arguments
10715/// to form a proper call to this constructor.
10716///
10717/// \returns true if an error occurred, false otherwise.
10718bool
10719Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10720 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010721 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010722 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010723 bool AllowExplicit,
10724 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010725 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10726 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010727 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010728
10729 const FunctionProtoType *Proto
10730 = Constructor->getType()->getAs<FunctionProtoType>();
10731 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010732 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010733
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010734 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010735 if (NumArgs < NumParams)
10736 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010737 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010738 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010739
10740 VariadicCallType CallType =
10741 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010742 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010743 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010744 Proto, 0,
10745 llvm::makeArrayRef(Args, NumArgs),
10746 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010747 CallType, AllowExplicit,
10748 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010749 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010750
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010751 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010752
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010753 CheckConstructorCall(Constructor,
10754 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10755 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010756 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010757
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010758 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010759}
10760
Anders Carlssone363c8e2009-12-12 00:32:00 +000010761static inline bool
10762CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10763 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010764 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010765 if (isa<NamespaceDecl>(DC)) {
10766 return SemaRef.Diag(FnDecl->getLocation(),
10767 diag::err_operator_new_delete_declared_in_namespace)
10768 << FnDecl->getDeclName();
10769 }
10770
10771 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010772 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010773 return SemaRef.Diag(FnDecl->getLocation(),
10774 diag::err_operator_new_delete_declared_static)
10775 << FnDecl->getDeclName();
10776 }
10777
Anders Carlsson60659a82009-12-12 02:43:16 +000010778 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010779}
10780
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010781static inline bool
10782CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10783 CanQualType ExpectedResultType,
10784 CanQualType ExpectedFirstParamType,
10785 unsigned DependentParamTypeDiag,
10786 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010787 QualType ResultType =
10788 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010789
10790 // Check that the result type is not dependent.
10791 if (ResultType->isDependentType())
10792 return SemaRef.Diag(FnDecl->getLocation(),
10793 diag::err_operator_new_delete_dependent_result_type)
10794 << FnDecl->getDeclName() << ExpectedResultType;
10795
10796 // Check that the result type is what we expect.
10797 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10798 return SemaRef.Diag(FnDecl->getLocation(),
10799 diag::err_operator_new_delete_invalid_result_type)
10800 << FnDecl->getDeclName() << ExpectedResultType;
10801
10802 // A function template must have at least 2 parameters.
10803 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10804 return SemaRef.Diag(FnDecl->getLocation(),
10805 diag::err_operator_new_delete_template_too_few_parameters)
10806 << FnDecl->getDeclName();
10807
10808 // The function decl must have at least 1 parameter.
10809 if (FnDecl->getNumParams() == 0)
10810 return SemaRef.Diag(FnDecl->getLocation(),
10811 diag::err_operator_new_delete_too_few_parameters)
10812 << FnDecl->getDeclName();
10813
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010814 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010815 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10816 if (FirstParamType->isDependentType())
10817 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10818 << FnDecl->getDeclName() << ExpectedFirstParamType;
10819
10820 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010821 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010822 ExpectedFirstParamType)
10823 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10824 << FnDecl->getDeclName() << ExpectedFirstParamType;
10825
10826 return false;
10827}
10828
Anders Carlsson12308f42009-12-11 23:23:22 +000010829static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010830CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010831 // C++ [basic.stc.dynamic.allocation]p1:
10832 // A program is ill-formed if an allocation function is declared in a
10833 // namespace scope other than global scope or declared static in global
10834 // scope.
10835 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10836 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010837
10838 CanQualType SizeTy =
10839 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10840
10841 // C++ [basic.stc.dynamic.allocation]p1:
10842 // The return type shall be void*. The first parameter shall have type
10843 // std::size_t.
10844 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10845 SizeTy,
10846 diag::err_operator_new_dependent_param_type,
10847 diag::err_operator_new_param_type))
10848 return true;
10849
10850 // C++ [basic.stc.dynamic.allocation]p1:
10851 // The first parameter shall not have an associated default argument.
10852 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010853 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010854 diag::err_operator_new_default_arg)
10855 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10856
10857 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010858}
10859
10860static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010861CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010862 // C++ [basic.stc.dynamic.deallocation]p1:
10863 // A program is ill-formed if deallocation functions are declared in a
10864 // namespace scope other than global scope or declared static in global
10865 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010866 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10867 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010868
10869 // C++ [basic.stc.dynamic.deallocation]p2:
10870 // Each deallocation function shall return void and its first parameter
10871 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010872 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10873 SemaRef.Context.VoidPtrTy,
10874 diag::err_operator_delete_dependent_param_type,
10875 diag::err_operator_delete_param_type))
10876 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010877
Anders Carlsson12308f42009-12-11 23:23:22 +000010878 return false;
10879}
10880
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010881/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10882/// of this overloaded operator is well-formed. If so, returns false;
10883/// otherwise, emits appropriate diagnostics and returns true.
10884bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010885 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010886 "Expected an overloaded operator declaration");
10887
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010888 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10889
Mike Stump11289f42009-09-09 15:08:12 +000010890 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010891 // The allocation and deallocation functions, operator new,
10892 // operator new[], operator delete and operator delete[], are
10893 // described completely in 3.7.3. The attributes and restrictions
10894 // found in the rest of this subclause do not apply to them unless
10895 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010896 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010897 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010898
Anders Carlsson22f443f2009-12-12 00:26:23 +000010899 if (Op == OO_New || Op == OO_Array_New)
10900 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010901
10902 // C++ [over.oper]p6:
10903 // An operator function shall either be a non-static member
10904 // function or be a non-member function and have at least one
10905 // parameter whose type is a class, a reference to a class, an
10906 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010907 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10908 if (MethodDecl->isStatic())
10909 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010910 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010911 } else {
10912 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010913 for (auto Param : FnDecl->params()) {
10914 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010915 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10916 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010917 ClassOrEnumParam = true;
10918 break;
10919 }
10920 }
10921
Douglas Gregord69246b2008-11-17 16:14:12 +000010922 if (!ClassOrEnumParam)
10923 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010924 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010925 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010926 }
10927
10928 // C++ [over.oper]p8:
10929 // An operator function cannot have default arguments (8.3.6),
10930 // except where explicitly stated below.
10931 //
Mike Stump11289f42009-09-09 15:08:12 +000010932 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010933 // (C++ [over.call]p1).
10934 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010935 for (auto Param : FnDecl->params()) {
10936 if (Param->hasDefaultArg())
10937 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010938 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010939 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010940 }
10941 }
10942
Douglas Gregor6cf08062008-11-10 13:38:07 +000010943 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10944 { false, false, false }
10945#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10946 , { Unary, Binary, MemberOnly }
10947#include "clang/Basic/OperatorKinds.def"
10948 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010949
Douglas Gregor6cf08062008-11-10 13:38:07 +000010950 bool CanBeUnaryOperator = OperatorUses[Op][0];
10951 bool CanBeBinaryOperator = OperatorUses[Op][1];
10952 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010953
10954 // C++ [over.oper]p8:
10955 // [...] Operator functions cannot have more or fewer parameters
10956 // than the number required for the corresponding operator, as
10957 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010958 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010959 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010960 if (Op != OO_Call &&
10961 ((NumParams == 1 && !CanBeUnaryOperator) ||
10962 (NumParams == 2 && !CanBeBinaryOperator) ||
10963 (NumParams < 1) || (NumParams > 2))) {
10964 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010965 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010966 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010967 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010968 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010969 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010970 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010971 assert(CanBeBinaryOperator &&
10972 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010973 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010974 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010975
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010976 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010977 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010978 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010979
Douglas Gregord69246b2008-11-17 16:14:12 +000010980 // Overloaded operators other than operator() cannot be variadic.
10981 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010982 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010983 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010984 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010985 }
10986
10987 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010988 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10989 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010990 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010991 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010992 }
10993
10994 // C++ [over.inc]p1:
10995 // The user-defined function called operator++ implements the
10996 // prefix and postfix ++ operator. If this function is a member
10997 // function with no parameters, or a non-member function with one
10998 // parameter of class or enumeration type, it defines the prefix
10999 // increment operator ++ for objects of that type. If the function
11000 // is a member function with one parameter (which shall be of type
11001 // int) or a non-member function with two parameters (the second
11002 // of which shall be of type int), it defines the postfix
11003 // increment operator ++ for objects of that type.
11004 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11005 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011006 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011007
Richard Smith538b52a2014-01-30 22:24:05 +000011008 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11009 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011010 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011011 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011012 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011013 }
11014
Douglas Gregord69246b2008-11-17 16:14:12 +000011015 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011016}
Chris Lattner3b024a32008-12-17 07:09:26 +000011017
Alexis Huntc88db062010-01-13 09:01:02 +000011018/// CheckLiteralOperatorDeclaration - Check whether the declaration
11019/// of this literal operator function is well-formed. If so, returns
11020/// false; otherwise, emits appropriate diagnostics and returns true.
11021bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011022 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011023 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11024 << FnDecl->getDeclName();
11025 return true;
11026 }
11027
Richard Smith72eebee2012-03-04 09:41:16 +000011028 if (FnDecl->isExternC()) {
11029 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11030 return true;
11031 }
11032
Alexis Huntc88db062010-01-13 09:01:02 +000011033 bool Valid = false;
11034
Richard Smithbcc22fc2012-03-09 08:00:36 +000011035 // This might be the definition of a literal operator template.
11036 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11037 // This might be a specialization of a literal operator template.
11038 if (!TpDecl)
11039 TpDecl = FnDecl->getPrimaryTemplate();
11040
Richard Smithb8b41d32013-10-07 19:57:58 +000011041 // template <char...> type operator "" name() and
11042 // template <class T, T...> type operator "" name() are the only valid
11043 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011044 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011045 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011046 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011047 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11048 if (Params->size() == 1) {
11049 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011050 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011051
Alexis Hunt7dd26172010-04-07 23:11:06 +000011052 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011053 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11054 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11055 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011056 } else if (Params->size() == 2) {
11057 TemplateTypeParmDecl *PmType =
11058 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11059 NonTypeTemplateParmDecl *PmArgs =
11060 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11061
11062 // The second template parameter must be a parameter pack with the
11063 // first template parameter as its type.
11064 if (PmType && PmArgs &&
11065 !PmType->isTemplateParameterPack() &&
11066 PmArgs->isTemplateParameterPack()) {
11067 const TemplateTypeParmType *TArgs =
11068 PmArgs->getType()->getAs<TemplateTypeParmType>();
11069 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11070 TArgs->getIndex() == PmType->getIndex()) {
11071 Valid = true;
11072 if (ActiveTemplateInstantiations.empty())
11073 Diag(FnDecl->getLocation(),
11074 diag::ext_string_literal_operator_template);
11075 }
11076 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011077 }
11078 }
Richard Smith72eebee2012-03-04 09:41:16 +000011079 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011080 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011081 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11082
Richard Smith72eebee2012-03-04 09:41:16 +000011083 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011084
Alexis Hunt079a6f72010-04-07 22:57:35 +000011085 // unsigned long long int, long double, and any character type are allowed
11086 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011087 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11088 Context.hasSameType(T, Context.LongDoubleTy) ||
11089 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011090 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011091 Context.hasSameType(T, Context.Char16Ty) ||
11092 Context.hasSameType(T, Context.Char32Ty)) {
11093 if (++Param == FnDecl->param_end())
11094 Valid = true;
11095 goto FinishedParams;
11096 }
11097
Alexis Hunt079a6f72010-04-07 22:57:35 +000011098 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011099 const PointerType *PT = T->getAs<PointerType>();
11100 if (!PT)
11101 goto FinishedParams;
11102 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011103 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011104 goto FinishedParams;
11105 T = T.getUnqualifiedType();
11106
11107 // Move on to the second parameter;
11108 ++Param;
11109
11110 // If there is no second parameter, the first must be a const char *
11111 if (Param == FnDecl->param_end()) {
11112 if (Context.hasSameType(T, Context.CharTy))
11113 Valid = true;
11114 goto FinishedParams;
11115 }
11116
11117 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11118 // are allowed as the first parameter to a two-parameter function
11119 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011120 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011121 Context.hasSameType(T, Context.Char16Ty) ||
11122 Context.hasSameType(T, Context.Char32Ty)))
11123 goto FinishedParams;
11124
11125 // The second and final parameter must be an std::size_t
11126 T = (*Param)->getType().getUnqualifiedType();
11127 if (Context.hasSameType(T, Context.getSizeType()) &&
11128 ++Param == FnDecl->param_end())
11129 Valid = true;
11130 }
11131
11132 // FIXME: This diagnostic is absolutely terrible.
11133FinishedParams:
11134 if (!Valid) {
11135 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11136 << FnDecl->getDeclName();
11137 return true;
11138 }
11139
Richard Smith768cecc2012-03-09 08:16:22 +000011140 // A parameter-declaration-clause containing a default argument is not
11141 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011142 for (auto Param : FnDecl->params()) {
11143 if (Param->hasDefaultArg()) {
11144 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011145 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011146 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011147 break;
11148 }
11149 }
11150
Richard Smith0df56f42012-03-08 02:39:21 +000011151 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011152 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11153 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011154 // C++11 [usrlit.suffix]p1:
11155 // Literal suffix identifiers that do not start with an underscore
11156 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011157 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11158 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011159 }
Richard Smith0df56f42012-03-08 02:39:21 +000011160
Alexis Huntc88db062010-01-13 09:01:02 +000011161 return false;
11162}
11163
Douglas Gregor07665a62009-01-05 19:45:36 +000011164/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11165/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011166/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11167/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011168/// the '{' brace. Otherwise, this linkage specification does not
11169/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011170Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011171 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011172 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011173 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11174 if (!Lit->isAscii()) {
11175 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11176 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011177 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011178 }
11179
11180 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011181 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011182 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011183 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011184 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011185 Language = LinkageSpecDecl::lang_cxx;
11186 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011187 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11188 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011189 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011190 }
Mike Stump11289f42009-09-09 15:08:12 +000011191
Chris Lattner438e5012008-12-17 07:13:27 +000011192 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011193
Richard Smith4ee696d2014-02-17 23:25:27 +000011194 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11195 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011196 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011197 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011198 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011199 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011200}
11201
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011202/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011203/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11204/// valid, it's the position of the closing '}' brace in a linkage
11205/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011206Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011207 Decl *LinkageSpec,
11208 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011209 if (RBraceLoc.isValid()) {
11210 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11211 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011212 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011213 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011214 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011215}
11216
Michael Han84324352013-02-22 17:15:32 +000011217Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11218 AttributeList *AttrList,
11219 SourceLocation SemiLoc) {
11220 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11221 // Attribute declarations appertain to empty declaration so we handle
11222 // them here.
11223 if (AttrList)
11224 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011225
Michael Han84324352013-02-22 17:15:32 +000011226 CurContext->addDecl(ED);
11227 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011228}
11229
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011230/// \brief Perform semantic analysis for the variable declaration that
11231/// occurs within a C++ catch clause, returning the newly-created
11232/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011233VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011234 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011235 SourceLocation StartLoc,
11236 SourceLocation Loc,
11237 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011238 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011239 QualType ExDeclType = TInfo->getType();
11240
Sebastian Redl54c04d42008-12-22 19:15:10 +000011241 // Arrays and functions decay.
11242 if (ExDeclType->isArrayType())
11243 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11244 else if (ExDeclType->isFunctionType())
11245 ExDeclType = Context.getPointerType(ExDeclType);
11246
11247 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11248 // The exception-declaration shall not denote a pointer or reference to an
11249 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011250 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011251 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011252 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011253 Invalid = true;
11254 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011255
Sebastian Redl54c04d42008-12-22 19:15:10 +000011256 QualType BaseType = ExDeclType;
11257 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011258 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011259 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011260 BaseType = Ptr->getPointeeType();
11261 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011262 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011263 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011264 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011265 BaseType = Ref->getPointeeType();
11266 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011267 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011268 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011269 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011270 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011271 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011272
Mike Stump11289f42009-09-09 15:08:12 +000011273 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011274 RequireNonAbstractType(Loc, ExDeclType,
11275 diag::err_abstract_type_in_decl,
11276 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011277 Invalid = true;
11278
John McCall2ca705e2010-07-24 00:37:23 +000011279 // Only the non-fragile NeXT runtime currently supports C++ catches
11280 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011281 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011282 QualType T = ExDeclType;
11283 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11284 T = RT->getPointeeType();
11285
11286 if (T->isObjCObjectType()) {
11287 Diag(Loc, diag::err_objc_object_catch);
11288 Invalid = true;
11289 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011290 // FIXME: should this be a test for macosx-fragile specifically?
11291 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011292 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011293 }
11294 }
11295
Abramo Bagnaradff19302011-03-08 08:55:46 +000011296 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011297 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011298 ExDecl->setExceptionVariable(true);
11299
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011300 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011301 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011302 Invalid = true;
11303
Douglas Gregor750734c2011-07-06 18:14:43 +000011304 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011305 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011306 // Insulate this from anything else we might currently be parsing.
11307 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11308
Douglas Gregor6de584c2010-03-05 23:38:39 +000011309 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011310 // The object declared in an exception-declaration or, if the
11311 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011312 // copy-initialized (8.5) from the exception object. [...]
11313 // The object is destroyed when the handler exits, after the destruction
11314 // of any automatic objects initialized within the handler.
11315 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011316 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011317 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011318 QualType initType = ExDeclType;
11319
11320 InitializedEntity entity =
11321 InitializedEntity::InitializeVariable(ExDecl);
11322 InitializationKind initKind =
11323 InitializationKind::CreateCopy(Loc, SourceLocation());
11324
11325 Expr *opaqueValue =
11326 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011327 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11328 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011329 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011330 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011331 else {
11332 // If the constructor used was non-trivial, set this as the
11333 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011334 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011335 if (!construct->getConstructor()->isTrivial()) {
11336 Expr *init = MaybeCreateExprWithCleanups(construct);
11337 ExDecl->setInit(init);
11338 }
11339
11340 // And make sure it's destructable.
11341 FinalizeVarWithDestructor(ExDecl, recordType);
11342 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011343 }
11344 }
11345
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011346 if (Invalid)
11347 ExDecl->setInvalidDecl();
11348
11349 return ExDecl;
11350}
11351
11352/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11353/// handler.
John McCall48871652010-08-21 09:40:31 +000011354Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011355 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011356 bool Invalid = D.isInvalidType();
11357
11358 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011359 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11360 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011361 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11362 D.getIdentifierLoc());
11363 Invalid = true;
11364 }
11365
Sebastian Redl54c04d42008-12-22 19:15:10 +000011366 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011367 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011368 LookupOrdinaryName,
11369 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011370 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011371 // it contains any previous declaration, except for function parameters in
11372 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011373 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011374 if (isDeclInScope(PrevDecl, CurContext, S)) {
11375 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11376 << D.getIdentifier();
11377 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11378 Invalid = true;
11379 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011380 // Maybe we will complain about the shadowed template parameter.
11381 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011382 }
11383
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011384 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011385 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11386 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011387 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011388 }
11389
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011390 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011391 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011392 D.getIdentifierLoc(),
11393 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011394 if (Invalid)
11395 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011396
Sebastian Redl54c04d42008-12-22 19:15:10 +000011397 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011398 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011399 PushOnScopeChains(ExDecl, S);
11400 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011401 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011402
Douglas Gregor758a8692009-06-17 21:51:59 +000011403 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011404 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011405}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011406
Abramo Bagnaraea947882011-03-08 16:41:52 +000011407Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011408 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011409 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011410 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011411 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011412
Richard Smithded9c2e2012-07-11 22:37:56 +000011413 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011414 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011415
11416 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11417 AssertMessage, RParenLoc, false);
11418}
11419
11420Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11421 Expr *AssertExpr,
11422 StringLiteral *AssertMessage,
11423 SourceLocation RParenLoc,
11424 bool Failed) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011425 assert(AssertExpr != nullptr && AssertMessage != nullptr &&
11426 "Expected non-null Expr's");
Richard Smithded9c2e2012-07-11 22:37:56 +000011427 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11428 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011429 // In a static_assert-declaration, the constant-expression shall be a
11430 // constant expression that can be contextually converted to bool.
11431 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11432 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011433 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011434
Richard Smith902ca212011-12-14 23:32:26 +000011435 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011436 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011437 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011438 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011439 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011440
Richard Smithded9c2e2012-07-11 22:37:56 +000011441 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011442 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011443 llvm::raw_svector_ostream Msg(MsgBuffer);
Craig Topperc3ec1492014-05-26 06:22:03 +000011444 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011445 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011446 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011447 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011448 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011449 }
Mike Stump11289f42009-09-09 15:08:12 +000011450
Abramo Bagnaraea947882011-03-08 16:41:52 +000011451 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011452 AssertExpr, AssertMessage, RParenLoc,
11453 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011454
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011455 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011456 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011457}
Sebastian Redlf769df52009-03-24 22:27:57 +000011458
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011459/// \brief Perform semantic analysis of the given friend type declaration.
11460///
11461/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011462FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011463 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011464 TypeSourceInfo *TSInfo) {
11465 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11466
11467 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011468 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011469
Richard Smithc8239732011-10-18 21:39:00 +000011470 // C++03 [class.friend]p2:
11471 // An elaborated-type-specifier shall be used in a friend declaration
11472 // for a class.*
11473 //
11474 // * The class-key of the elaborated-type-specifier is required.
11475 if (!ActiveTemplateInstantiations.empty()) {
11476 // Do not complain about the form of friend template types during
11477 // template instantiation; we will already have complained when the
11478 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011479 } else {
11480 if (!T->isElaboratedTypeSpecifier()) {
11481 // If we evaluated the type to a record type, suggest putting
11482 // a tag in front.
11483 if (const RecordType *RT = T->getAs<RecordType>()) {
11484 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011485
11486 SmallString<16> InsertionText(" ");
11487 InsertionText += RD->getKindName();
11488
Nick Lewycky36722d22013-02-06 05:59:33 +000011489 Diag(TypeRange.getBegin(),
11490 getLangOpts().CPlusPlus11 ?
11491 diag::warn_cxx98_compat_unelaborated_friend_type :
11492 diag::ext_unelaborated_friend_type)
11493 << (unsigned) RD->getTagKind()
11494 << T
11495 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11496 InsertionText);
11497 } else {
11498 Diag(FriendLoc,
11499 getLangOpts().CPlusPlus11 ?
11500 diag::warn_cxx98_compat_nonclass_type_friend :
11501 diag::ext_nonclass_type_friend)
11502 << T
11503 << TypeRange;
11504 }
11505 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011506 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011507 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011508 diag::warn_cxx98_compat_enum_friend :
11509 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011510 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011511 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011512 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011513
Nick Lewycky36722d22013-02-06 05:59:33 +000011514 // C++11 [class.friend]p3:
11515 // A friend declaration that does not declare a function shall have one
11516 // of the following forms:
11517 // friend elaborated-type-specifier ;
11518 // friend simple-type-specifier ;
11519 // friend typename-specifier ;
11520 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11521 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11522 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011523
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011524 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011525 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011526 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011527 return FriendDecl::Create(Context, CurContext,
11528 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11529 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011530}
11531
John McCallace48cd2010-10-19 01:40:49 +000011532/// Handle a friend tag declaration where the scope specifier was
11533/// templated.
11534Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11535 unsigned TagSpec, SourceLocation TagLoc,
11536 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011537 IdentifierInfo *Name,
11538 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011539 AttributeList *Attr,
11540 MultiTemplateParamsArg TempParamLists) {
11541 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11542
11543 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011544 bool Invalid = false;
11545
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011546 if (TemplateParameterList *TemplateParams =
11547 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011548 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011549 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011550 if (TemplateParams->size() > 0) {
11551 // This is a declaration of a class template.
11552 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011553 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011554
Eric Christopher6f228b52011-07-21 05:34:24 +000011555 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11556 SS, Name, NameLoc, Attr,
11557 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011558 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011559 TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011560 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011561 } else {
11562 // The "template<>" header is extraneous.
11563 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11564 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11565 isExplicitSpecialization = true;
11566 }
11567 }
11568
Craig Topperc3ec1492014-05-26 06:22:03 +000011569 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011570
John McCallace48cd2010-10-19 01:40:49 +000011571 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011572 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011573 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011574 isAllExplicitSpecializations = false;
11575 break;
11576 }
11577 }
11578
11579 // FIXME: don't ignore attributes.
11580
11581 // If it's explicit specializations all the way down, just forget
11582 // about the template header and build an appropriate non-templated
11583 // friend. TODO: for source fidelity, remember the headers.
11584 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011585 if (SS.isEmpty()) {
11586 bool Owned = false;
11587 bool IsDependent = false;
11588 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011589 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011590 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011591 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011592 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011593 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011594 /*UnderlyingType=*/TypeResult(),
11595 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011596 }
Richard Smith649c7b062014-01-08 00:56:48 +000011597
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011598 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011599 ElaboratedTypeKeyword Keyword
11600 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011601 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011602 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011603 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011604 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011605
11606 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11607 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011608 DependentNameTypeLoc TL =
11609 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011610 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011611 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011612 TL.setNameLoc(NameLoc);
11613 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011614 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011615 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011616 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011617 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011618 }
11619
11620 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011621 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011622 Friend->setAccess(AS_public);
11623 CurContext->addDecl(Friend);
11624 return Friend;
11625 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011626
11627 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11628
11629
John McCallace48cd2010-10-19 01:40:49 +000011630
11631 // Handle the case of a templated-scope friend class. e.g.
11632 // template <class T> class A<T>::B;
11633 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011634 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11635 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011636 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11637 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11638 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011639 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011640 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011641 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011642 TL.setNameLoc(NameLoc);
11643
11644 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011645 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011646 Friend->setAccess(AS_public);
11647 Friend->setUnsupportedFriend(true);
11648 CurContext->addDecl(Friend);
11649 return Friend;
11650}
11651
11652
John McCall11083da2009-09-16 22:47:08 +000011653/// Handle a friend type declaration. This works in tandem with
11654/// ActOnTag.
11655///
11656/// Notes on friend class templates:
11657///
11658/// We generally treat friend class declarations as if they were
11659/// declaring a class. So, for example, the elaborated type specifier
11660/// in a friend declaration is required to obey the restrictions of a
11661/// class-head (i.e. no typedefs in the scope chain), template
11662/// parameters are required to match up with simple template-ids, &c.
11663/// However, unlike when declaring a template specialization, it's
11664/// okay to refer to a template specialization without an empty
11665/// template parameter declaration, e.g.
11666/// friend class A<T>::B<unsigned>;
11667/// We permit this as a special case; if there are any template
11668/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011669/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011670Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011671 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011672 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011673
11674 assert(DS.isFriendSpecified());
11675 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11676
John McCall11083da2009-09-16 22:47:08 +000011677 // Try to convert the decl specifier to a type. This works for
11678 // friend templates because ActOnTag never produces a ClassTemplateDecl
11679 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011680 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011681 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11682 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011683 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011684 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011685
Douglas Gregor6c110f32010-12-16 01:14:37 +000011686 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011687 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011688
John McCall11083da2009-09-16 22:47:08 +000011689 // This is definitely an error in C++98. It's probably meant to
11690 // be forbidden in C++0x, too, but the specification is just
11691 // poorly written.
11692 //
11693 // The problem is with declarations like the following:
11694 // template <T> friend A<T>::foo;
11695 // where deciding whether a class C is a friend or not now hinges
11696 // on whether there exists an instantiation of A that causes
11697 // 'foo' to equal C. There are restrictions on class-heads
11698 // (which we declare (by fiat) elaborated friend declarations to
11699 // be) that makes this tractable.
11700 //
11701 // FIXME: handle "template <> friend class A<T>;", which
11702 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011703 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011704 Diag(Loc, diag::err_tagless_friend_type_template)
11705 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011706 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011707 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011708
John McCallaa74a0c2009-08-28 07:59:38 +000011709 // C++98 [class.friend]p1: A friend of a class is a function
11710 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011711 // This is fixed in DR77, which just barely didn't make the C++03
11712 // deadline. It's also a very silly restriction that seriously
11713 // affects inner classes and which nobody else seems to implement;
11714 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011715 //
11716 // But note that we could warn about it: it's always useless to
11717 // friend one of your own members (it's not, however, worthless to
11718 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011719
John McCall11083da2009-09-16 22:47:08 +000011720 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011721 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011722 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011723 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011724 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011725 TSI,
John McCall11083da2009-09-16 22:47:08 +000011726 DS.getFriendSpecLoc());
11727 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011728 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011729
11730 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011731 return nullptr;
11732
John McCall11083da2009-09-16 22:47:08 +000011733 D->setAccess(AS_public);
11734 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011735
John McCall48871652010-08-21 09:40:31 +000011736 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011737}
11738
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011739NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11740 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011741 const DeclSpec &DS = D.getDeclSpec();
11742
11743 assert(DS.isFriendSpecified());
11744 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11745
11746 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011747 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011748
11749 // C++ [class.friend]p1
11750 // A friend of a class is a function or class....
11751 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011752 // It *doesn't* see through dependent types, which is correct
11753 // according to [temp.arg.type]p3:
11754 // If a declaration acquires a function type through a
11755 // type dependent on a template-parameter and this causes
11756 // a declaration that does not use the syntactic form of a
11757 // function declarator to have a function type, the program
11758 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011759 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011760 Diag(Loc, diag::err_unexpected_friend);
11761
11762 // It might be worthwhile to try to recover by creating an
11763 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011764 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011765 }
11766
11767 // C++ [namespace.memdef]p3
11768 // - If a friend declaration in a non-local class first declares a
11769 // class or function, the friend class or function is a member
11770 // of the innermost enclosing namespace.
11771 // - The name of the friend is not found by simple name lookup
11772 // until a matching declaration is provided in that namespace
11773 // scope (either before or after the class declaration granting
11774 // friendship).
11775 // - If a friend function is called, its name may be found by the
11776 // name lookup that considers functions from namespaces and
11777 // classes associated with the types of the function arguments.
11778 // - When looking for a prior declaration of a class or a function
11779 // declared as a friend, scopes outside the innermost enclosing
11780 // namespace scope are not considered.
11781
John McCallde3fd222010-10-12 23:13:28 +000011782 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011783 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11784 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011785 assert(Name);
11786
Douglas Gregor6c110f32010-12-16 01:14:37 +000011787 // Check for unexpanded parameter packs.
11788 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11789 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11790 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011791 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011792
John McCall07e91c02009-08-06 02:15:43 +000011793 // The context we found the declaration in, or in which we should
11794 // create the declaration.
11795 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011796 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011797 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011798 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011799
Richard Smith114394f2013-08-09 04:35:01 +000011800 // There are five cases here.
11801 // - There's no scope specifier and we're in a local class. Only look
11802 // for functions declared in the immediately-enclosing block scope.
11803 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011804 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011805 if ((SS.isInvalid() || !SS.isSet()) &&
11806 (FunctionContainingLocalClass =
11807 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11808 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011809 // If a friend declaration appears in a local class and the name
11810 // specified is an unqualified name, a prior declaration is
11811 // looked up without considering scopes that are outside the
11812 // innermost enclosing non-class scope. For a friend function
11813 // declaration, if there is no prior declaration, the program is
11814 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011815
11816 // Find the innermost enclosing non-class scope. This is the block
11817 // scope containing the local class definition (or for a nested class,
11818 // the outer local class).
11819 DCScope = S->getFnParent();
11820
11821 // Look up the function name in the scope.
11822 Previous.clear(LookupLocalFriendName);
11823 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11824
11825 if (!Previous.empty()) {
11826 // All possible previous declarations must have the same context:
11827 // either they were declared at block scope or they are members of
11828 // one of the enclosing local classes.
11829 DC = Previous.getRepresentativeDecl()->getDeclContext();
11830 } else {
11831 // This is ill-formed, but provide the context that we would have
11832 // declared the function in, if we were permitted to, for error recovery.
11833 DC = FunctionContainingLocalClass;
11834 }
Richard Smith541b38b2013-09-20 01:15:31 +000011835 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011836
11837 // C++ [class.friend]p6:
11838 // A function can be defined in a friend declaration of a class if and
11839 // only if the class is a non-local class (9.8), the function name is
11840 // unqualified, and the function has namespace scope.
11841 if (D.isFunctionDefinition()) {
11842 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11843 }
11844
11845 // - There's no scope specifier, in which case we just go to the
11846 // appropriate scope and look for a function or function template
11847 // there as appropriate.
11848 } else if (SS.isInvalid() || !SS.isSet()) {
11849 // C++11 [namespace.memdef]p3:
11850 // If the name in a friend declaration is neither qualified nor
11851 // a template-id and the declaration is a function or an
11852 // elaborated-type-specifier, the lookup to determine whether
11853 // the entity has been previously declared shall not consider
11854 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011855 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011856
John McCallf7cfb222010-10-13 05:45:15 +000011857 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011858 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011859
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011860 // Skip class contexts. If someone can cite chapter and verse
11861 // for this behavior, that would be nice --- it's what GCC and
11862 // EDG do, and it seems like a reasonable intent, but the spec
11863 // really only says that checks for unqualified existing
11864 // declarations should stop at the nearest enclosing namespace,
11865 // not that they should only consider the nearest enclosing
11866 // namespace.
11867 while (DC->isRecord())
11868 DC = DC->getParent();
11869
11870 DeclContext *LookupDC = DC;
11871 while (LookupDC->isTransparentContext())
11872 LookupDC = LookupDC->getParent();
11873
11874 while (true) {
11875 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011876
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011877 if (!Previous.empty()) {
11878 DC = LookupDC;
11879 break;
John McCallf4776592010-10-14 22:22:28 +000011880 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011881
11882 if (isTemplateId) {
11883 if (isa<TranslationUnitDecl>(LookupDC)) break;
11884 } else {
11885 if (LookupDC->isFileContext()) break;
11886 }
11887 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011888 }
11889
John McCallccbc0322010-10-13 06:22:15 +000011890 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011891
John McCallde3fd222010-10-12 23:13:28 +000011892 // - There's a non-dependent scope specifier, in which case we
11893 // compute it and do a previous lookup there for a function
11894 // or function template.
11895 } else if (!SS.getScopeRep()->isDependent()) {
11896 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000011897 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011898
Craig Topperc3ec1492014-05-26 06:22:03 +000011899 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011900
11901 LookupQualifiedName(Previous, DC);
11902
11903 // Ignore things found implicitly in the wrong scope.
11904 // TODO: better diagnostics for this case. Suggesting the right
11905 // qualified scope would be nice...
11906 LookupResult::Filter F = Previous.makeFilter();
11907 while (F.hasNext()) {
11908 NamedDecl *D = F.next();
11909 if (!DC->InEnclosingNamespaceSetOf(
11910 D->getDeclContext()->getRedeclContext()))
11911 F.erase();
11912 }
11913 F.done();
11914
11915 if (Previous.empty()) {
11916 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011917 Diag(Loc, diag::err_qualified_friend_not_found)
11918 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000011919 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011920 }
11921
11922 // C++ [class.friend]p1: A friend of a class is a function or
11923 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011924 if (DC->Equals(CurContext))
11925 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011926 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011927 diag::warn_cxx98_compat_friend_is_member :
11928 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011929
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011930 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011931 // C++ [class.friend]p6:
11932 // A function can be defined in a friend declaration of a class if and
11933 // only if the class is a non-local class (9.8), the function name is
11934 // unqualified, and the function has namespace scope.
11935 SemaDiagnosticBuilder DB
11936 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11937
11938 DB << SS.getScopeRep();
11939 if (DC->isFileContext())
11940 DB << FixItHint::CreateRemoval(SS.getRange());
11941 SS.clear();
11942 }
John McCallde3fd222010-10-12 23:13:28 +000011943
11944 // - There's a scope specifier that does not match any template
11945 // parameter lists, in which case we use some arbitrary context,
11946 // create a method or method template, and wait for instantiation.
11947 // - There's a scope specifier that does match some template
11948 // parameter lists, which we don't handle right now.
11949 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011950 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011951 // C++ [class.friend]p6:
11952 // A function can be defined in a friend declaration of a class if and
11953 // only if the class is a non-local class (9.8), the function name is
11954 // unqualified, and the function has namespace scope.
11955 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11956 << SS.getScopeRep();
11957 }
11958
John McCallde3fd222010-10-12 23:13:28 +000011959 DC = CurContext;
11960 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011961 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011962
John McCallf7cfb222010-10-13 05:45:15 +000011963 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011964 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011965 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11966 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11967 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011968 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011969 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11970 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000011971 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011972 }
John McCall07e91c02009-08-06 02:15:43 +000011973 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011974
Douglas Gregordd847ba2011-11-03 16:37:14 +000011975 // FIXME: This is an egregious hack to cope with cases where the scope stack
11976 // does not contain the declaration context, i.e., in an out-of-line
11977 // definition of a class.
11978 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11979 if (!DCScope) {
11980 FakeDCScope.setEntity(DC);
11981 DCScope = &FakeDCScope;
11982 }
Richard Smith114394f2013-08-09 04:35:01 +000011983
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011984 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011985 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011986 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000011987 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000011988
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011989 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011990
Richard Smith114394f2013-08-09 04:35:01 +000011991 // If we performed typo correction, we might have added a scope specifier
11992 // and changed the decl context.
11993 DC = ND->getDeclContext();
11994
John McCall759e32b2009-08-31 22:39:49 +000011995 // Add the function declaration to the appropriate lookup tables,
11996 // adjusting the redeclarations list as necessary. We don't
11997 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011998 //
John McCall759e32b2009-08-31 22:39:49 +000011999 // Also update the scope-based lookup if the target context's
12000 // lookup context is in lexical scope.
12001 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012002 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012003 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012004 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012005 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012006 }
John McCallaa74a0c2009-08-28 07:59:38 +000012007
12008 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012009 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012010 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012011 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012012 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012013
John McCalla0a96892012-08-10 03:15:35 +000012014 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012015 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012016 } else {
12017 if (DC->isRecord()) CheckFriendAccess(ND);
12018
John McCall2c2eb122010-10-16 06:59:13 +000012019 FunctionDecl *FD;
12020 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12021 FD = FTD->getTemplatedDecl();
12022 else
12023 FD = cast<FunctionDecl>(ND);
12024
David Majnemer502b0ed2013-06-25 23:09:30 +000012025 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12026 // default argument expression, that declaration shall be a definition
12027 // and shall be the only declaration of the function or function
12028 // template in the translation unit.
12029 if (functionDeclHasDefaultArgument(FD)) {
12030 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12031 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12032 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12033 } else if (!D.isFunctionDefinition())
12034 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12035 }
12036
John McCall2c2eb122010-10-16 06:59:13 +000012037 // Mark templated-scope function declarations as unsupported.
12038 if (FD->getNumTemplateParameterLists())
12039 FrD->setUnsupportedFriend(true);
12040 }
John McCallde3fd222010-10-12 23:13:28 +000012041
John McCall48871652010-08-21 09:40:31 +000012042 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012043}
12044
John McCall48871652010-08-21 09:40:31 +000012045void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12046 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012047
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012048 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012049 if (!Fn) {
12050 Diag(DelLoc, diag::err_deleted_non_function);
12051 return;
12052 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012053
Douglas Gregorec9fd132012-01-14 16:38:05 +000012054 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012055 // Don't consider the implicit declaration we generate for explicit
12056 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012057 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12058 Prev->getPreviousDecl()) &&
12059 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012060 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012061 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12062 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12063 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012064 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012065 // If the declaration wasn't the first, we delete the function anyway for
12066 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012067 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012068 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012069
Nico Rieck9de0a572014-05-29 16:51:19 +000012070 // dllimport/dllexport cannot be deleted.
12071 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12072 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12073 Fn->setInvalidDecl();
12074 }
12075
Richard Smithb4d2a152013-04-02 19:38:47 +000012076 if (Fn->isDeleted())
12077 return;
12078
12079 // See if we're deleting a function which is already known to override a
12080 // non-deleted virtual function.
12081 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12082 bool IssuedDiagnostic = false;
12083 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12084 E = MD->end_overridden_methods();
12085 I != E; ++I) {
12086 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12087 if (!IssuedDiagnostic) {
12088 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12089 IssuedDiagnostic = true;
12090 }
12091 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12092 }
12093 }
12094 }
12095
Richard Smithb63b6ee2014-01-22 01:43:19 +000012096 // C++11 [basic.start.main]p3:
12097 // A program that defines main as deleted [...] is ill-formed.
12098 if (Fn->isMain())
12099 Diag(DelLoc, diag::err_deleted_main);
12100
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012101 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012102}
Sebastian Redl4c018662009-04-27 21:33:24 +000012103
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012104void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012105 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012106
12107 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012108 if (MD->getParent()->isDependentType()) {
12109 MD->setDefaulted();
12110 MD->setExplicitlyDefaulted();
12111 return;
12112 }
12113
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012114 CXXSpecialMember Member = getSpecialMember(MD);
12115 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012116 if (!MD->isInvalidDecl())
12117 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012118 return;
12119 }
12120
12121 MD->setDefaulted();
12122 MD->setExplicitlyDefaulted();
12123
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012124 // If this definition appears within the record, do the checking when
12125 // the record is complete.
12126 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012127 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012128 // Find the uninstantiated declaration that actually had the '= default'
12129 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012130 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012131
Richard Smith3901dfe2013-03-27 00:22:47 +000012132 // If the method was defaulted on its first declaration, we will have
12133 // already performed the checking in CheckCompletedCXXClass. Such a
12134 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012135 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012136 return;
12137
Richard Smithd3b5c9082012-07-27 04:22:15 +000012138 CheckExplicitlyDefaultedSpecialMember(MD);
12139
Richard Smithbd305122012-12-11 01:14:52 +000012140 // The exception specification is needed because we are defining the
12141 // function.
12142 ResolveExceptionSpec(DefaultLoc,
12143 MD->getType()->castAs<FunctionProtoType>());
12144
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012145 if (MD->isInvalidDecl())
12146 return;
12147
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012148 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012149 case CXXDefaultConstructor:
12150 DefineImplicitDefaultConstructor(DefaultLoc,
12151 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012152 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012153 case CXXCopyConstructor:
12154 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012155 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012156 case CXXCopyAssignment:
12157 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012158 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012159 case CXXDestructor:
12160 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012161 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012162 case CXXMoveConstructor:
12163 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012164 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012165 case CXXMoveAssignment:
12166 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012167 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012168 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012169 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012170 }
12171 } else {
12172 Diag(DefaultLoc, diag::err_default_special_members);
12173 }
12174}
12175
Sebastian Redl4c018662009-04-27 21:33:24 +000012176static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012177 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012178 Stmt *SubStmt = *CI;
12179 if (!SubStmt)
12180 continue;
12181 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012182 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012183 diag::err_return_in_constructor_handler);
12184 if (!isa<Expr>(SubStmt))
12185 SearchForReturnInStmt(Self, SubStmt);
12186 }
12187}
12188
12189void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12190 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12191 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12192 SearchForReturnInStmt(*this, Handler);
12193 }
12194}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012195
David Blaikie68f71a32013-01-18 23:03:15 +000012196bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012197 const CXXMethodDecl *Old) {
12198 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12199 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12200
12201 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12202
12203 // If the calling conventions match, everything is fine
12204 if (NewCC == OldCC)
12205 return false;
12206
Hans Wennborg2545efe2013-12-11 17:42:11 +000012207 // If the calling conventions mismatch because the new function is static,
12208 // suppress the calling convention mismatch error; the error about static
12209 // function override (err_static_overrides_virtual from
12210 // Sema::CheckFunctionDeclaration) is more clear.
12211 if (New->getStorageClass() == SC_Static)
12212 return false;
12213
Reid Kleckner78af0702013-08-27 23:08:25 +000012214 Diag(New->getLocation(),
12215 diag::err_conflicting_overriding_cc_attributes)
12216 << New->getDeclName() << New->getType() << Old->getType();
12217 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12218 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012219}
12220
Mike Stump11289f42009-09-09 15:08:12 +000012221bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012222 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012223 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12224 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012225
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012226 if (Context.hasSameType(NewTy, OldTy) ||
12227 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012228 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012229
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012230 // Check if the return types are covariant
12231 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012232
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012233 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012234 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12235 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012236 NewClassTy = NewPT->getPointeeType();
12237 OldClassTy = OldPT->getPointeeType();
12238 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012239 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12240 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12241 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12242 NewClassTy = NewRT->getPointeeType();
12243 OldClassTy = OldRT->getPointeeType();
12244 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012245 }
12246 }
Mike Stump11289f42009-09-09 15:08:12 +000012247
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012248 // The return types aren't either both pointers or references to a class type.
12249 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012250 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012251 diag::err_different_return_type_for_overriding_virtual_function)
12252 << New->getDeclName() << NewTy << OldTy;
12253 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012254
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012255 return true;
12256 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012257
Anders Carlssone60365b2009-12-31 18:34:24 +000012258 // C++ [class.virtual]p6:
12259 // If the return type of D::f differs from the return type of B::f, the
12260 // class type in the return type of D::f shall be complete at the point of
12261 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012262 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12263 if (!RT->isBeingDefined() &&
12264 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012265 diag::err_covariant_return_incomplete,
12266 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012267 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012268 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012269
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012270 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012271 // Check if the new class derives from the old class.
12272 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12273 Diag(New->getLocation(),
12274 diag::err_covariant_return_not_derived)
12275 << New->getDeclName() << NewTy << OldTy;
12276 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12277 return true;
12278 }
Mike Stump11289f42009-09-09 15:08:12 +000012279
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012280 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012281 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012282 diag::err_covariant_return_inaccessible_base,
12283 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12284 // FIXME: Should this point to the return type?
Craig Topperc3ec1492014-05-26 06:22:03 +000012285 New->getLocation(), SourceRange(), New->getDeclName(),
12286 nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012287 // FIXME: this note won't trigger for delayed access control
12288 // diagnostics, and it's impossible to get an undelayed error
12289 // here from access control during the original parse because
12290 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012291 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12292 return true;
12293 }
12294 }
Mike Stump11289f42009-09-09 15:08:12 +000012295
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012296 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012297 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012298 Diag(New->getLocation(),
12299 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012300 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012301 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12302 return true;
12303 };
Mike Stump11289f42009-09-09 15:08:12 +000012304
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012305
12306 // The new class type must have the same or less qualifiers as the old type.
12307 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12308 Diag(New->getLocation(),
12309 diag::err_covariant_return_type_class_type_more_qualified)
12310 << New->getDeclName() << NewTy << OldTy;
12311 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12312 return true;
12313 };
Mike Stump11289f42009-09-09 15:08:12 +000012314
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012315 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012316}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012317
Douglas Gregor21920e372009-12-01 17:24:26 +000012318/// \brief Mark the given method pure.
12319///
12320/// \param Method the method to be marked pure.
12321///
12322/// \param InitRange the source range that covers the "0" initializer.
12323bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012324 SourceLocation EndLoc = InitRange.getEnd();
12325 if (EndLoc.isValid())
12326 Method->setRangeEnd(EndLoc);
12327
Douglas Gregor21920e372009-12-01 17:24:26 +000012328 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12329 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012330 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012331 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012332
12333 if (!Method->isInvalidDecl())
12334 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12335 << Method->getDeclName() << InitRange;
12336 return true;
12337}
12338
Douglas Gregor926410d2012-02-21 02:22:07 +000012339/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012340static bool isStaticDataMember(const Decl *D) {
12341 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12342 return Var->isStaticDataMember();
12343
12344 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012345}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012346
John McCall1f4ee7b2009-12-19 09:28:58 +000012347/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12348/// an initializer for the out-of-line declaration 'Dcl'. The scope
12349/// is a fresh scope pushed for just this purpose.
12350///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012351/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12352/// static data member of class X, names should be looked up in the scope of
12353/// class X.
John McCall48871652010-08-21 09:40:31 +000012354void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012355 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012356 if (!D || D->isInvalidDecl())
12357 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012358
Richard Smitha2302242013-12-05 07:51:02 +000012359 // We will always have a nested name specifier here, but this declaration
12360 // might not be out of line if the specifier names the current namespace:
12361 // extern int n;
12362 // int ::n = 0;
12363 if (D->isOutOfLine())
12364 EnterDeclaratorContext(S, D->getDeclContext());
12365
Douglas Gregor926410d2012-02-21 02:22:07 +000012366 // If we are parsing the initializer for a static data member, push a
12367 // new expression evaluation context that is associated with this static
12368 // data member.
12369 if (isStaticDataMember(D))
12370 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012371}
12372
12373/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012374/// initializer for the out-of-line declaration 'D'.
12375void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012376 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012377 if (!D || D->isInvalidDecl())
12378 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012379
Douglas Gregor926410d2012-02-21 02:22:07 +000012380 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012381 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012382
Richard Smitha2302242013-12-05 07:51:02 +000012383 if (D->isOutOfLine())
12384 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012385}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012386
12387/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12388/// C++ if/switch/while/for statement.
12389/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012390DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012391 // C++ 6.4p2:
12392 // The declarator shall not specify a function or an array.
12393 // The type-specifier-seq shall not contain typedef and shall not declare a
12394 // new class or enumeration.
12395 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12396 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012397
12398 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012399 if (!Dcl)
12400 return true;
12401
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012402 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12403 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012404 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012405 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012406 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012407
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012408 return Dcl;
12409}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012410
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012411void Sema::LoadExternalVTableUses() {
12412 if (!ExternalSource)
12413 return;
12414
12415 SmallVector<ExternalVTableUse, 4> VTables;
12416 ExternalSource->ReadUsedVTables(VTables);
12417 SmallVector<VTableUse, 4> NewUses;
12418 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12419 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12420 = VTablesUsed.find(VTables[I].Record);
12421 // Even if a definition wasn't required before, it may be required now.
12422 if (Pos != VTablesUsed.end()) {
12423 if (!Pos->second && VTables[I].DefinitionRequired)
12424 Pos->second = true;
12425 continue;
12426 }
12427
12428 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12429 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12430 }
12431
12432 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12433}
12434
Douglas Gregor88d292c2010-05-13 16:44:06 +000012435void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12436 bool DefinitionRequired) {
12437 // Ignore any vtable uses in unevaluated operands or for classes that do
12438 // not have a vtable.
12439 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012440 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012441 return;
12442
Douglas Gregor88d292c2010-05-13 16:44:06 +000012443 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012444 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012445 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12446 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12447 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12448 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012449 // If we already had an entry, check to see if we are promoting this vtable
12450 // to required a definition. If so, we need to reappend to the VTableUses
12451 // list, since we may have already processed the first entry.
12452 if (DefinitionRequired && !Pos.first->second) {
12453 Pos.first->second = true;
12454 } else {
12455 // Otherwise, we can early exit.
12456 return;
12457 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012458 } else {
12459 // The Microsoft ABI requires that we perform the destructor body
12460 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12461 // the deleting destructor is emitted with the vtable, not with the
12462 // destructor definition as in the Itanium ABI.
12463 // If it has a definition, we do the check at that point instead.
12464 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12465 Class->hasUserDeclaredDestructor() &&
12466 !Class->getDestructor()->isDefined() &&
12467 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012468 CXXDestructorDecl *DD = Class->getDestructor();
12469 ContextRAII SavedContext(*this, DD);
12470 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012471 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012472 }
12473
12474 // Local classes need to have their virtual members marked
12475 // immediately. For all other classes, we mark their virtual members
12476 // at the end of the translation unit.
12477 if (Class->isLocalClass())
12478 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012479 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012480 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012481}
12482
Douglas Gregor88d292c2010-05-13 16:44:06 +000012483bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012484 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012485 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012486 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012487
Douglas Gregor88d292c2010-05-13 16:44:06 +000012488 // Note: The VTableUses vector could grow as a result of marking
12489 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012490 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012491 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012492 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012493 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012494 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012495 if (!Class)
12496 continue;
12497
12498 SourceLocation Loc = VTableUses[I].second;
12499
Richard Smithd3b5c9082012-07-27 04:22:15 +000012500 bool DefineVTable = true;
12501
Douglas Gregor88d292c2010-05-13 16:44:06 +000012502 // If this class has a key function, but that key function is
12503 // defined in another translation unit, we don't need to emit the
12504 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012505 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012506 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012507 // The key function is in another translation unit.
12508 DefineVTable = false;
12509 TemplateSpecializationKind TSK =
12510 KeyFunction->getTemplateSpecializationKind();
12511 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12512 TSK != TSK_ImplicitInstantiation &&
12513 "Instantiations don't have key functions");
12514 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012515 } else if (!KeyFunction) {
12516 // If we have a class with no key function that is the subject
12517 // of an explicit instantiation declaration, suppress the
12518 // vtable; it will live with the explicit instantiation
12519 // definition.
12520 bool IsExplicitInstantiationDeclaration
12521 = Class->getTemplateSpecializationKind()
12522 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012523 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012524 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012525 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012526 if (TSK == TSK_ExplicitInstantiationDeclaration)
12527 IsExplicitInstantiationDeclaration = true;
12528 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12529 IsExplicitInstantiationDeclaration = false;
12530 break;
12531 }
12532 }
12533
12534 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012535 DefineVTable = false;
12536 }
12537
12538 // The exception specifications for all virtual members may be needed even
12539 // if we are not providing an authoritative form of the vtable in this TU.
12540 // We may choose to emit it available_externally anyway.
12541 if (!DefineVTable) {
12542 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12543 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012544 }
12545
12546 // Mark all of the virtual members of this class as referenced, so
12547 // that we can build a vtable. Then, tell the AST consumer that a
12548 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012549 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012550 MarkVirtualMembersReferenced(Loc, Class);
12551 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12552 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12553
12554 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012555 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012556 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012557 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012558 if (!KeyFunction ||
12559 (KeyFunction->hasBody(KeyFunctionDef) &&
12560 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012561 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12562 TSK_ExplicitInstantiationDefinition
12563 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12564 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012565 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012566 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012567 VTableUses.clear();
12568
Douglas Gregor97509692011-04-22 22:25:37 +000012569 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012570}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012571
Richard Smithd3b5c9082012-07-27 04:22:15 +000012572void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12573 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012574 for (const auto *I : RD->methods())
12575 if (I->isVirtual() && !I->isPure())
12576 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012577}
12578
Rafael Espindola5b334082010-03-26 00:36:59 +000012579void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12580 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012581 // Mark all functions which will appear in RD's vtable as used.
12582 CXXFinalOverriderMap FinalOverriders;
12583 RD->getFinalOverriders(FinalOverriders);
12584 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12585 E = FinalOverriders.end();
12586 I != E; ++I) {
12587 for (OverridingMethods::const_iterator OI = I->second.begin(),
12588 OE = I->second.end();
12589 OI != OE; ++OI) {
12590 assert(OI->second.size() > 0 && "no final overrider");
12591 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012592
Richard Smith4ff9ff92012-07-07 06:59:51 +000012593 // C++ [basic.def.odr]p2:
12594 // [...] A virtual member function is used if it is not pure. [...]
12595 if (!Overrider->isPure())
12596 MarkFunctionReferenced(Loc, Overrider);
12597 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012598 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012599
12600 // Only classes that have virtual bases need a VTT.
12601 if (RD->getNumVBases() == 0)
12602 return;
12603
Aaron Ballman574705e2014-03-13 15:41:46 +000012604 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012605 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012606 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012607 if (Base->getNumVBases() == 0)
12608 continue;
12609 MarkVirtualMembersReferenced(Loc, Base);
12610 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012611}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012612
12613/// SetIvarInitializers - This routine builds initialization ASTs for the
12614/// Objective-C implementation whose ivars need be initialized.
12615void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012616 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012617 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012618 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012619 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012620 CollectIvarsToConstructOrDestruct(OID, ivars);
12621 if (ivars.empty())
12622 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012623 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012624 for (unsigned i = 0; i < ivars.size(); i++) {
12625 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012626 if (Field->isInvalidDecl())
12627 continue;
12628
Alexis Hunt1d792652011-01-08 20:30:50 +000012629 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012630 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12631 InitializationKind InitKind =
12632 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012633
12634 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12635 ExprResult MemberInit =
12636 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012637 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012638 // Note, MemberInit could actually come back empty if no initialization
12639 // is required (e.g., because it would call a trivial default constructor)
12640 if (!MemberInit.get() || MemberInit.isInvalid())
12641 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012642
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012643 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012644 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12645 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012646 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012647 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012648 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012649
12650 // Be sure that the destructor is accessible and is marked as referenced.
12651 if (const RecordType *RecordTy
12652 = Context.getBaseElementType(Field->getType())
12653 ->getAs<RecordType>()) {
12654 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012655 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012656 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012657 CheckDestructorAccess(Field->getLocation(), Destructor,
12658 PDiag(diag::err_access_dtor_ivar)
12659 << Context.getBaseElementType(Field->getType()));
12660 }
12661 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012662 }
12663 ObjCImplementation->setIvarInitializers(Context,
12664 AllToInit.data(), AllToInit.size());
12665 }
12666}
Alexis Hunt6118d662011-05-04 05:57:24 +000012667
Alexis Hunt27a761d2011-05-04 23:29:54 +000012668static
12669void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12670 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12671 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12672 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12673 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012674 if (Ctor->isInvalidDecl())
12675 return;
12676
Richard Smith802c4b72012-08-23 06:16:52 +000012677 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12678
12679 // Target may not be determinable yet, for instance if this is a dependent
12680 // call in an uninstantiated template.
12681 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012682 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012683 (void)Target->hasBody(FNTarget);
12684 Target = const_cast<CXXConstructorDecl*>(
12685 cast_or_null<CXXConstructorDecl>(FNTarget));
12686 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012687
12688 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12689 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012690 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012691
12692 if (!Current.insert(Canonical))
12693 return;
12694
12695 // We know that beyond here, we aren't chaining into a cycle.
12696 if (!Target || !Target->isDelegatingConstructor() ||
12697 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012698 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012699 Current.clear();
12700 // We've hit a cycle.
12701 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12702 Current.count(TCanonical)) {
12703 // If we haven't diagnosed this cycle yet, do so now.
12704 if (!Invalid.count(TCanonical)) {
12705 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012706 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012707 << Ctor;
12708
Richard Smith802c4b72012-08-23 06:16:52 +000012709 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012710 if (TCanonical != Canonical)
12711 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12712
12713 CXXConstructorDecl *C = Target;
12714 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012715 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012716 (void)C->getTargetConstructor()->hasBody(FNTarget);
12717 assert(FNTarget && "Ctor cycle through bodiless function");
12718
Richard Smith802c4b72012-08-23 06:16:52 +000012719 C = const_cast<CXXConstructorDecl*>(
12720 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012721 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12722 }
12723 }
12724
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012725 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012726 Current.clear();
12727 } else {
12728 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12729 }
12730}
12731
12732
Alexis Hunt6118d662011-05-04 05:57:24 +000012733void Sema::CheckDelegatingCtorCycles() {
12734 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12735
Douglas Gregorbae31202011-07-27 21:57:17 +000012736 for (DelegatingCtorDeclsType::iterator
12737 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012738 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012739 I != E; ++I)
12740 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012741
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012742 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12743 CE = Invalid.end();
12744 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012745 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012746}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012747
Douglas Gregor3024f072012-04-16 07:05:22 +000012748namespace {
12749 /// \brief AST visitor that finds references to the 'this' expression.
12750 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12751 Sema &S;
12752
12753 public:
12754 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12755
12756 bool VisitCXXThisExpr(CXXThisExpr *E) {
12757 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12758 << E->isImplicit();
12759 return false;
12760 }
12761 };
12762}
12763
12764bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12765 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12766 if (!TSInfo)
12767 return false;
12768
12769 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012770 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012771 if (!ProtoTL)
12772 return false;
12773
12774 // C++11 [expr.prim.general]p3:
12775 // [The expression this] shall not appear before the optional
12776 // cv-qualifier-seq and it shall not appear within the declaration of a
12777 // static member function (although its type and value category are defined
12778 // within a static member function as they are within a non-static member
12779 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012780 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012781 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012782 FindCXXThisExpr Finder(*this);
12783
12784 // If the return type came after the cv-qualifier-seq, check it now.
12785 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012786 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012787 return true;
12788
12789 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012790 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12791 return true;
12792
12793 return checkThisInStaticMemberFunctionAttributes(Method);
12794}
12795
12796bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12797 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12798 if (!TSInfo)
12799 return false;
12800
12801 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012802 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012803 if (!ProtoTL)
12804 return false;
12805
David Blaikie6adc78e2013-02-18 22:06:02 +000012806 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012807 FindCXXThisExpr Finder(*this);
12808
Douglas Gregor3024f072012-04-16 07:05:22 +000012809 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012810 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012811 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012812 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012813 case EST_DynamicNone:
12814 case EST_MSAny:
12815 case EST_None:
12816 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012817
Douglas Gregor3024f072012-04-16 07:05:22 +000012818 case EST_ComputedNoexcept:
12819 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12820 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012821
Douglas Gregor3024f072012-04-16 07:05:22 +000012822 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012823 for (const auto &E : Proto->exceptions()) {
12824 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012825 return true;
12826 }
12827 break;
12828 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012829
12830 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012831}
12832
12833bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12834 FindCXXThisExpr Finder(*this);
12835
12836 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012837 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012838 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000012839 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000012840 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012841 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012842 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012843 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012844 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012845 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012846 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012847 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012848 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012849 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012850 Arg = ETLF->getSuccessValue();
12851 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012852 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012853 Arg = STLF->getSuccessValue();
12854 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012855 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012856 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012857 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012858 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012859 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012860 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012861 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012862 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012863 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12864 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12865 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012866 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012867
12868 if (Arg && !Finder.TraverseStmt(Arg))
12869 return true;
12870
12871 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12872 if (!Finder.TraverseStmt(Args[I]))
12873 return true;
12874 }
12875 }
12876
12877 return false;
12878}
12879
Douglas Gregor433e0532012-04-16 18:27:27 +000012880void
12881Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12882 ArrayRef<ParsedType> DynamicExceptions,
12883 ArrayRef<SourceRange> DynamicExceptionRanges,
12884 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012885 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012886 FunctionProtoType::ExtProtoInfo &EPI) {
12887 Exceptions.clear();
12888 EPI.ExceptionSpecType = EST;
12889 if (EST == EST_Dynamic) {
12890 Exceptions.reserve(DynamicExceptions.size());
12891 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12892 // FIXME: Preserve type source info.
12893 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12894
12895 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12896 collectUnexpandedParameterPacks(ET, Unexpanded);
12897 if (!Unexpanded.empty()) {
12898 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12899 UPPC_ExceptionType,
12900 Unexpanded);
12901 continue;
12902 }
12903
12904 // Check that the type is valid for an exception spec, and
12905 // drop it if not.
12906 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12907 Exceptions.push_back(ET);
12908 }
12909 EPI.NumExceptions = Exceptions.size();
12910 EPI.Exceptions = Exceptions.data();
12911 return;
12912 }
12913
12914 if (EST == EST_ComputedNoexcept) {
12915 // If an error occurred, there's no expression here.
12916 if (NoexceptExpr) {
12917 assert((NoexceptExpr->isTypeDependent() ||
12918 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12919 Context.BoolTy) &&
12920 "Parser should have made sure that the expression is boolean");
12921 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12922 EPI.ExceptionSpecType = EST_BasicNoexcept;
12923 return;
12924 }
12925
12926 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000012927 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000012928 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012929 /*AllowFold*/ false).get();
Douglas Gregor433e0532012-04-16 18:27:27 +000012930 EPI.NoexceptExpr = NoexceptExpr;
12931 }
12932 return;
12933 }
12934}
12935
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012936/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12937Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12938 // Implicitly declared functions (e.g. copy constructors) are
12939 // __host__ __device__
12940 if (D->isImplicit())
12941 return CFT_HostDevice;
12942
12943 if (D->hasAttr<CUDAGlobalAttr>())
12944 return CFT_Global;
12945
12946 if (D->hasAttr<CUDADeviceAttr>()) {
12947 if (D->hasAttr<CUDAHostAttr>())
12948 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012949 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012950 }
12951
12952 return CFT_Host;
12953}
12954
12955bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12956 CUDAFunctionTarget CalleeTarget) {
12957 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12958 // Callable from the device only."
12959 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12960 return true;
12961
12962 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12963 // Callable from the host only."
12964 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12965 // Callable from the host only."
12966 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12967 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12968 return true;
12969
12970 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12971 return true;
12972
12973 return false;
12974}
John McCall5e77d762013-04-16 07:28:30 +000012975
12976/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12977///
12978MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12979 SourceLocation DeclStart,
12980 Declarator &D, Expr *BitWidth,
12981 InClassInitStyle InitStyle,
12982 AccessSpecifier AS,
12983 AttributeList *MSPropertyAttr) {
12984 IdentifierInfo *II = D.getIdentifier();
12985 if (!II) {
12986 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000012987 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000012988 }
12989 SourceLocation Loc = D.getIdentifierLoc();
12990
12991 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12992 QualType T = TInfo->getType();
12993 if (getLangOpts().CPlusPlus) {
12994 CheckExtraCXXDefaultArguments(D);
12995
12996 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12997 UPPC_DataMemberType)) {
12998 D.setInvalidType();
12999 T = Context.IntTy;
13000 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13001 }
13002 }
13003
13004 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13005
13006 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13007 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13008 diag::err_invalid_thread)
13009 << DeclSpec::getSpecifierName(TSCS);
13010
13011 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013012 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013013 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13014 LookupName(Previous, S);
13015 switch (Previous.getResultKind()) {
13016 case LookupResult::Found:
13017 case LookupResult::FoundUnresolvedValue:
13018 PrevDecl = Previous.getAsSingle<NamedDecl>();
13019 break;
13020
13021 case LookupResult::FoundOverloaded:
13022 PrevDecl = Previous.getRepresentativeDecl();
13023 break;
13024
13025 case LookupResult::NotFound:
13026 case LookupResult::NotFoundInCurrentInstantiation:
13027 case LookupResult::Ambiguous:
13028 break;
13029 }
13030
13031 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13032 // Maybe we will complain about the shadowed template parameter.
13033 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13034 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013035 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013036 }
13037
13038 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013039 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013040
13041 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013042 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013043 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13044 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013045 ProcessDeclAttributes(TUScope, NewPD, D);
13046 NewPD->setAccess(AS);
13047
13048 if (NewPD->isInvalidDecl())
13049 Record->setInvalidDecl();
13050
13051 if (D.getDeclSpec().isModulePrivateSpecified())
13052 NewPD->setModulePrivate();
13053
13054 if (NewPD->isInvalidDecl() && PrevDecl) {
13055 // Don't introduce NewFD into scope; there's already something
13056 // with the same name in the same scope.
13057 } else if (II) {
13058 PushOnScopeChains(NewPD, S);
13059 } else
13060 Record->addDecl(NewPD);
13061
13062 return NewPD;
13063}