blob: 03600d02f84bf56a202d39a510c6ee946ed8673f [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
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001299/// \brief Perform propagation of DLL attributes from a derived class to a
1300/// templated base class for MS compatibility.
1301static void propagateDLLAttrToBaseClassTemplate(
1302 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1303 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1304 if (getDLLAttr(
1305 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1306 // If the base class template has a DLL attribute, don't try to change it.
1307 return;
1308 }
1309
1310 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1311 // If the base class is not already specialized, we can do the propagation.
1312 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1313 NewAttr->setInherited(true);
1314 BaseTemplateSpec->addAttr(NewAttr);
1315 return;
1316 }
1317
1318 bool DifferentAttribute = false;
1319 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1320 if (!SpecializationAttr->isInherited()) {
1321 // The template has previously been specialized or instantiated with an
1322 // explicit attribute. We should not try to change it.
1323 return;
1324 }
1325 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1326 // The specialization already has the right attribute.
1327 return;
1328 }
1329 DifferentAttribute = true;
1330 }
1331
1332 // The template was previously instantiated or explicitly specialized without
1333 // a dll attribute, or the template was previously instantiated with a
1334 // different inherited attribute. It's too late for us to change the
1335 // attribute, so warn that this is unsupported.
1336 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1337 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1338 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1339 if (BaseTemplateSpec->isExplicitSpecialization()) {
1340 S.Diag(BaseTemplateSpec->getLocation(),
1341 diag::note_template_class_explicit_specialization_was_here)
1342 << BaseTemplateSpec;
1343 } else {
1344 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1345 diag::note_template_class_instantiation_was_here)
1346 << BaseTemplateSpec;
1347 }
1348}
1349
Mike Stump11289f42009-09-09 15:08:12 +00001350/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001351///
1352/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1353/// and returns NULL otherwise.
1354CXXBaseSpecifier *
1355Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1356 SourceRange SpecifierRange,
1357 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001358 TypeSourceInfo *TInfo,
1359 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001360 QualType BaseType = TInfo->getType();
1361
Douglas Gregor463421d2009-03-03 04:44:36 +00001362 // C++ [class.union]p1:
1363 // A union shall not have base classes.
1364 if (Class->isUnion()) {
1365 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1366 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001367 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001368 }
1369
Douglas Gregor752a5952011-01-03 22:36:02 +00001370 if (EllipsisLoc.isValid() &&
1371 !TInfo->getType()->containsUnexpandedParameterPack()) {
1372 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1373 << TInfo->getTypeLoc().getSourceRange();
1374 EllipsisLoc = SourceLocation();
1375 }
Douglas Gregor62004702012-11-10 01:18:17 +00001376
1377 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1378
1379 if (BaseType->isDependentType()) {
1380 // Make sure that we don't have circular inheritance among our dependent
1381 // bases. For non-dependent bases, the check for completeness below handles
1382 // this.
1383 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1384 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1385 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001386 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001387 Diag(BaseLoc, diag::err_circular_inheritance)
1388 << BaseType << Context.getTypeDeclType(Class);
1389
1390 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1391 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1392 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001393
1394 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001395 }
1396 }
1397
Mike Stump11289f42009-09-09 15:08:12 +00001398 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001399 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001400 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001401 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001402
1403 // Base specifiers must be record types.
1404 if (!BaseType->isRecordType()) {
1405 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001406 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001407 }
1408
1409 // C++ [class.union]p1:
1410 // A union shall not be used as a base class.
1411 if (BaseType->isUnionType()) {
1412 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001414 }
1415
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001416 // For the MS ABI, propagate DLL attributes to base class templates.
1417 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1418 if (Attr *ClassAttr = getDLLAttr(Class)) {
1419 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1420 BaseType->getAsCXXRecordDecl())) {
1421 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1422 BaseTemplate, BaseLoc);
1423 }
1424 }
1425 }
1426
Douglas Gregor463421d2009-03-03 04:44:36 +00001427 // C++ [class.derived]p2:
1428 // The class-name in a base-specifier shall not be an incompletely
1429 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001430 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001431 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001432 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001433 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001434 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001435
Eli Friedmanc96d4962009-08-15 21:55:26 +00001436 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001437 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001438 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001439 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001440 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001441 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001442 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001443
David Majnemer9b1754d2013-11-02 12:00:36 +00001444 // A class which contains a flexible array member is not suitable for use as a
1445 // base class:
1446 // - If the layout determines that a base comes before another base,
1447 // the flexible array member would index into the subsequent base.
1448 // - If the layout determines that base comes before the derived class,
1449 // the flexible array member would index into the derived class.
1450 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1451 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1452 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001453 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001454 }
1455
Anders Carlsson65c76d32011-03-25 14:55:14 +00001456 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001457 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001458 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001459 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001460 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001461 << CXXBaseDecl->getDeclName()
1462 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001463 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1464 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001465 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001466 }
1467
John McCall3696dcb2010-08-17 07:23:57 +00001468 if (BaseDecl->isInvalidDecl())
1469 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001470
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001471 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001472 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001473 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001474 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001475}
1476
Douglas Gregor556877c2008-04-13 21:30:24 +00001477/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1478/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001479/// example:
1480/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001481/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001482BaseResult
John McCall48871652010-08-21 09:40:31 +00001483Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001484 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001485 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001486 ParsedType basetype, SourceLocation BaseLoc,
1487 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001488 if (!classdecl)
1489 return true;
1490
Douglas Gregorc40290e2009-03-09 23:48:35 +00001491 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001492 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001493 if (!Class)
1494 return true;
1495
David Majnemer5ef4fe72014-06-13 06:43:46 +00001496 // We haven't yet attached the base specifiers.
1497 Class->setIsParsingBaseSpecifiers();
1498
Richard Smith4c96e992013-02-19 23:47:15 +00001499 // We do not support any C++11 attributes on base-specifiers yet.
1500 // Diagnose any attributes we see.
1501 if (!Attributes.empty()) {
1502 for (AttributeList *Attr = Attributes.getList(); Attr;
1503 Attr = Attr->getNext()) {
1504 if (Attr->isInvalid() ||
1505 Attr->getKind() == AttributeList::IgnoredAttribute)
1506 continue;
1507 Diag(Attr->getLoc(),
1508 Attr->getKind() == AttributeList::UnknownAttribute
1509 ? diag::warn_unknown_attribute_ignored
1510 : diag::err_base_specifier_attribute)
1511 << Attr->getName();
1512 }
1513 }
1514
Craig Topperc3ec1492014-05-26 06:22:03 +00001515 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001516 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001517
Douglas Gregor752a5952011-01-03 22:36:02 +00001518 if (EllipsisLoc.isInvalid() &&
1519 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001520 UPPC_BaseType))
1521 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001522
Douglas Gregor463421d2009-03-03 04:44:36 +00001523 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001524 Virtual, Access, TInfo,
1525 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001526 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001527 else
1528 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001529
Douglas Gregor463421d2009-03-03 04:44:36 +00001530 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001531}
Douglas Gregor556877c2008-04-13 21:30:24 +00001532
Douglas Gregor463421d2009-03-03 04:44:36 +00001533/// \brief Performs the actual work of attaching the given base class
1534/// specifiers to a C++ class.
1535bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1536 unsigned NumBases) {
1537 if (NumBases == 0)
1538 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001539
1540 // Used to keep track of which base types we have already seen, so
1541 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001542 // that the key is always the unqualified canonical type of the base
1543 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001544 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1545
1546 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001547 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001548 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001549 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001550 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001551 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001552 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001553
1554 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1555 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001556 // C++ [class.mi]p3:
1557 // A class shall not be specified as a direct base class of a
1558 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001559 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001560 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001561 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001562 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001563
1564 // Delete the duplicate base class specifier; we're going to
1565 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001566 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001567
1568 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001569 } else {
1570 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001571 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001572 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001573 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1574 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1575 if (Class->isInterface() &&
1576 (!RD->isInterface() ||
1577 KnownBase->getAccessSpecifier() != AS_public)) {
1578 // The Microsoft extension __interface does not permit bases that
1579 // are not themselves public interfaces.
1580 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1581 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1582 << RD->getSourceRange();
1583 Invalid = true;
1584 }
1585 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001586 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001587 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001588 }
1589 }
1590
1591 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001592 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001593
1594 // Delete the remaining (good) base class specifiers, since their
1595 // data has been copied into the CXXRecordDecl.
1596 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001597 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001598
1599 return Invalid;
1600}
1601
1602/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1603/// class, after checking whether there are any duplicate base
1604/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001605void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001606 unsigned NumBases) {
1607 if (!ClassDecl || !Bases || !NumBases)
1608 return;
1609
1610 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001611 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001612}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001613
Douglas Gregor36d1b142009-10-06 17:59:45 +00001614/// \brief Determine whether the type \p Derived is a C++ class that is
1615/// derived from the type \p Base.
1616bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001617 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001618 return false;
John McCalle78aac42010-03-10 03:28:59 +00001619
Douglas Gregor45bb4832013-03-26 23:36:30 +00001620 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001621 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001622 return false;
1623
Douglas Gregor45bb4832013-03-26 23:36:30 +00001624 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001625 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001626 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001627
1628 // If either the base or the derived type is invalid, don't try to
1629 // check whether one is derived from the other.
1630 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1631 return false;
1632
John McCall67da35c2010-02-04 22:26:26 +00001633 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1634 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001635}
1636
1637/// \brief Determine whether the type \p Derived is a C++ class that is
1638/// derived from the type \p Base.
1639bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001640 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001641 return false;
1642
Douglas Gregor45bb4832013-03-26 23:36:30 +00001643 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001644 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001645 return false;
1646
Douglas Gregor45bb4832013-03-26 23:36:30 +00001647 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001648 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001649 return false;
1650
Douglas Gregor36d1b142009-10-06 17:59:45 +00001651 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1652}
1653
Anders Carlssona70cff62010-04-24 19:06:50 +00001654void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001655 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001656 assert(BasePathArray.empty() && "Base path array must be empty!");
1657 assert(Paths.isRecordingPaths() && "Must record paths!");
1658
1659 const CXXBasePath &Path = Paths.front();
1660
1661 // We first go backward and check if we have a virtual base.
1662 // FIXME: It would be better if CXXBasePath had the base specifier for
1663 // the nearest virtual base.
1664 unsigned Start = 0;
1665 for (unsigned I = Path.size(); I != 0; --I) {
1666 if (Path[I - 1].Base->isVirtual()) {
1667 Start = I - 1;
1668 break;
1669 }
1670 }
1671
1672 // Now add all bases.
1673 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001674 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001675}
1676
Douglas Gregor88d292c2010-05-13 16:44:06 +00001677/// \brief Determine whether the given base path includes a virtual
1678/// base class.
John McCallcf142162010-08-07 06:22:56 +00001679bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1680 for (CXXCastPath::const_iterator B = BasePath.begin(),
1681 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001682 B != BEnd; ++B)
1683 if ((*B)->isVirtual())
1684 return true;
1685
1686 return false;
1687}
1688
Douglas Gregor36d1b142009-10-06 17:59:45 +00001689/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1690/// conversion (where Derived and Base are class types) is
1691/// well-formed, meaning that the conversion is unambiguous (and
1692/// that all of the base classes are accessible). Returns true
1693/// and emits a diagnostic if the code is ill-formed, returns false
1694/// otherwise. Loc is the location where this routine should point to
1695/// if there is an error, and Range is the source range to highlight
1696/// if there is an error.
1697bool
1698Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001699 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001700 unsigned AmbigiousBaseConvID,
1701 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001702 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001703 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001704 // First, determine whether the path from Derived to Base is
1705 // ambiguous. This is slightly more expensive than checking whether
1706 // the Derived to Base conversion exists, because here we need to
1707 // explore multiple paths to determine if there is an ambiguity.
1708 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1709 /*DetectVirtual=*/false);
1710 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1711 assert(DerivationOkay &&
1712 "Can only be used with a derived-to-base conversion");
1713 (void)DerivationOkay;
1714
1715 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001716 if (InaccessibleBaseID) {
1717 // Check that the base class can be accessed.
1718 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1719 InaccessibleBaseID)) {
1720 case AR_inaccessible:
1721 return true;
1722 case AR_accessible:
1723 case AR_dependent:
1724 case AR_delayed:
1725 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001726 }
John McCall5b0829a2010-02-10 09:31:12 +00001727 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001728
1729 // Build a base path if necessary.
1730 if (BasePath)
1731 BuildBasePathArray(Paths, *BasePath);
1732 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001733 }
1734
David Majnemer626032f2013-06-22 06:43:58 +00001735 if (AmbigiousBaseConvID) {
1736 // We know that the derived-to-base conversion is ambiguous, and
1737 // we're going to produce a diagnostic. Perform the derived-to-base
1738 // search just one more time to compute all of the possible paths so
1739 // that we can print them out. This is more expensive than any of
1740 // the previous derived-to-base checks we've done, but at this point
1741 // performance isn't as much of an issue.
1742 Paths.clear();
1743 Paths.setRecordingPaths(true);
1744 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1745 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1746 (void)StillOkay;
1747
1748 // Build up a textual representation of the ambiguous paths, e.g.,
1749 // D -> B -> A, that will be used to illustrate the ambiguous
1750 // conversions in the diagnostic. We only print one of the paths
1751 // to each base class subobject.
1752 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1753
1754 Diag(Loc, AmbigiousBaseConvID)
1755 << Derived << Base << PathDisplayStr << Range << Name;
1756 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001757 return true;
1758}
1759
1760bool
1761Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001762 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001763 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001764 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001765 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001766 IgnoreAccess ? 0
1767 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001768 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001769 Loc, Range, DeclarationName(),
1770 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001771}
1772
1773
1774/// @brief Builds a string representing ambiguous paths from a
1775/// specific derived class to different subobjects of the same base
1776/// class.
1777///
1778/// This function builds a string that can be used in error messages
1779/// to show the different paths that one can take through the
1780/// inheritance hierarchy to go from the derived class to different
1781/// subobjects of a base class. The result looks something like this:
1782/// @code
1783/// struct D -> struct B -> struct A
1784/// struct D -> struct C -> struct A
1785/// @endcode
1786std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1787 std::string PathDisplayStr;
1788 std::set<unsigned> DisplayedPaths;
1789 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1790 Path != Paths.end(); ++Path) {
1791 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1792 // We haven't displayed a path to this particular base
1793 // class subobject yet.
1794 PathDisplayStr += "\n ";
1795 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1796 for (CXXBasePath::const_iterator Element = Path->begin();
1797 Element != Path->end(); ++Element)
1798 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1799 }
1800 }
1801
1802 return PathDisplayStr;
1803}
1804
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001805//===----------------------------------------------------------------------===//
1806// C++ class member Handling
1807//===----------------------------------------------------------------------===//
1808
Abramo Bagnarad7340582010-06-05 05:09:32 +00001809/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001810bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1811 SourceLocation ASLoc,
1812 SourceLocation ColonLoc,
1813 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001814 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001815 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001816 ASLoc, ColonLoc);
1817 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001818 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001819}
1820
Richard Smith18f07db2012-08-06 03:25:17 +00001821/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001822void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001823 if (D->isInvalidDecl())
1824 return;
1825
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001826 // We only care about "override" and "final" declarations.
1827 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1828 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001829
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001830 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001831
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001832 // We can't check dependent instance methods.
1833 if (MD && MD->isInstance() &&
1834 (MD->getParent()->hasAnyDependentBases() ||
1835 MD->getType()->isDependentType()))
1836 return;
1837
1838 if (MD && !MD->isVirtual()) {
1839 // If we have a non-virtual method, check if if hides a virtual method.
1840 // (In that case, it's most likely the method has the wrong type.)
1841 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1842 FindHiddenVirtualMethods(MD, OverloadedMethods);
1843
1844 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001845 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1846 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001847 diag::override_keyword_hides_virtual_member_function)
1848 << "override" << (OverloadedMethods.size() > 1);
1849 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001850 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001851 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001852 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1853 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001854 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001855 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1856 MD->setInvalidDecl();
1857 return;
1858 }
1859 // Fall through into the general case diagnostic.
1860 // FIXME: We might want to attempt typo correction here.
1861 }
1862
1863 if (!MD || !MD->isVirtual()) {
1864 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1865 Diag(OA->getLocation(),
1866 diag::override_keyword_only_allowed_on_virtual_member_functions)
1867 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1868 D->dropAttr<OverrideAttr>();
1869 }
1870 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1871 Diag(FA->getLocation(),
1872 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001873 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1874 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001875 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001876 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001877 return;
1878 }
Richard Smith18f07db2012-08-06 03:25:17 +00001879
Richard Smith18f07db2012-08-06 03:25:17 +00001880 // C++11 [class.virtual]p5:
1881 // If a virtual function is marked with the virt-specifier override and
1882 // does not override a member function of a base class, the program is
1883 // ill-formed.
1884 bool HasOverriddenMethods =
1885 MD->begin_overridden_methods() != MD->end_overridden_methods();
1886 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1887 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1888 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001889}
1890
Richard Smith18f07db2012-08-06 03:25:17 +00001891/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001892/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001893/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001894bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1895 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001896 FinalAttr *FA = Old->getAttr<FinalAttr>();
1897 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001898 return false;
1899
1900 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001901 << New->getDeclName()
1902 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001903 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1904 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001905}
1906
Daniel Jasper0baec5492012-06-06 08:32:04 +00001907static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001908 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1909 // FIXME: Destruction of ObjC lifetime types has side-effects.
1910 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1911 return !RD->isCompleteDefinition() ||
1912 !RD->hasTrivialDefaultConstructor() ||
1913 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001914 return false;
1915}
1916
John McCall5e77d762013-04-16 07:28:30 +00001917static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001918 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001919 if (it->isDeclspecPropertyAttribute())
1920 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001922}
1923
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001924/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1925/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001926/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001927/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1928/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001929NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001930Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001931 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001932 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001933 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001934 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001935 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1936 DeclarationName Name = NameInfo.getName();
1937 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001938
1939 // For anonymous bitfields, the location should point to the type.
1940 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001941 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001942
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001943 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001944
John McCallb1cd7da2010-06-04 08:34:12 +00001945 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001946 assert(!DS.isFriendSpecified());
1947
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001948 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001949
John McCalldb632ac2012-09-25 07:32:39 +00001950 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1951 // The Microsoft extension __interface only permits public member functions
1952 // and prohibits constructors, destructors, operators, non-public member
1953 // functions, static methods and data members.
1954 unsigned InvalidDecl;
1955 bool ShowDeclName = true;
1956 if (!isFunc)
1957 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1958 else if (AS != AS_public)
1959 InvalidDecl = 2;
1960 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1961 InvalidDecl = 3;
1962 else switch (Name.getNameKind()) {
1963 case DeclarationName::CXXConstructorName:
1964 InvalidDecl = 4;
1965 ShowDeclName = false;
1966 break;
1967
1968 case DeclarationName::CXXDestructorName:
1969 InvalidDecl = 5;
1970 ShowDeclName = false;
1971 break;
1972
1973 case DeclarationName::CXXOperatorName:
1974 case DeclarationName::CXXConversionFunctionName:
1975 InvalidDecl = 6;
1976 break;
1977
1978 default:
1979 InvalidDecl = 0;
1980 break;
1981 }
1982
1983 if (InvalidDecl) {
1984 if (ShowDeclName)
1985 Diag(Loc, diag::err_invalid_member_in_interface)
1986 << (InvalidDecl-1) << Name;
1987 else
1988 Diag(Loc, diag::err_invalid_member_in_interface)
1989 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001990 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001991 }
1992 }
1993
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001994 // C++ 9.2p6: A member shall not be declared to have automatic storage
1995 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001996 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1997 // data members and cannot be applied to names declared const or static,
1998 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001999 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002000 case DeclSpec::SCS_unspecified:
2001 case DeclSpec::SCS_typedef:
2002 case DeclSpec::SCS_static:
2003 break;
2004 case DeclSpec::SCS_mutable:
2005 if (isFunc) {
2006 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002007
Richard Smithb4a9e862013-04-12 22:46:28 +00002008 // FIXME: It would be nicer if the keyword was ignored only for this
2009 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002010 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002011 }
2012 break;
2013 default:
2014 Diag(DS.getStorageClassSpecLoc(),
2015 diag::err_storageclass_invalid_for_member);
2016 D.getMutableDeclSpec().ClearStorageClassSpecs();
2017 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002018 }
2019
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002020 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2021 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002022 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002023
David Blaikie35506f82013-01-30 01:22:18 +00002024 if (DS.isConstexprSpecified() && isInstField) {
2025 SemaDiagnosticBuilder B =
2026 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2027 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2028 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002029 B << 0 << 0;
2030 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2031 B << FixItHint::CreateRemoval(ConstexprLoc);
2032 else {
2033 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2034 D.getMutableDeclSpec().ClearConstexprSpec();
2035 const char *PrevSpec;
2036 unsigned DiagID;
2037 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2038 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2039 (void)Failed;
2040 assert(!Failed && "Making a constexpr member const shouldn't fail");
2041 }
David Blaikie35506f82013-01-30 01:22:18 +00002042 } else {
2043 B << 1;
2044 const char *PrevSpec;
2045 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002046 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002047 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2048 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002049 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002050 "This is the only DeclSpec that should fail to be applied");
2051 B << 1;
2052 } else {
2053 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2054 isInstField = false;
2055 }
2056 }
2057 }
2058
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002059 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002060 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002061 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002062
2063 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002064 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002065 Diag(Loc, diag::err_bad_variable_name)
2066 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002067 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002068 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002069
Benjamin Kramer365082d2012-05-19 16:34:46 +00002070 IdentifierInfo *II = Name.getAsIdentifierInfo();
2071
Douglas Gregor7c26c042011-09-21 14:40:46 +00002072 // Member field could not be with "template" keyword.
2073 // So TemplateParameterLists should be empty in this case.
2074 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002075 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002076 if (TemplateParams->size()) {
2077 // There is no such thing as a member field template.
2078 Diag(D.getIdentifierLoc(), diag::err_template_member)
2079 << II
2080 << SourceRange(TemplateParams->getTemplateLoc(),
2081 TemplateParams->getRAngleLoc());
2082 } else {
2083 // There is an extraneous 'template<>' for this member.
2084 Diag(TemplateParams->getTemplateLoc(),
2085 diag::err_template_member_noparams)
2086 << II
2087 << SourceRange(TemplateParams->getTemplateLoc(),
2088 TemplateParams->getRAngleLoc());
2089 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002090 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002091 }
2092
Douglas Gregora007d362010-10-13 22:19:53 +00002093 if (SS.isSet() && !SS.isInvalid()) {
2094 // The user provided a superfluous scope specifier inside a class
2095 // definition:
2096 //
2097 // class X {
2098 // int X::member;
2099 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002100 if (DeclContext *DC = computeDeclContext(SS, false))
2101 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002102 else
2103 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2104 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002105
Douglas Gregora007d362010-10-13 22:19:53 +00002106 SS.clear();
2107 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002108
John McCall5e77d762013-04-16 07:28:30 +00002109 AttributeList *MSPropertyAttr =
2110 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002111 if (MSPropertyAttr) {
2112 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2113 BitWidth, InitStyle, AS, MSPropertyAttr);
2114 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002115 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002116 isInstField = false;
2117 } else {
2118 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2119 BitWidth, InitStyle, AS);
2120 assert(Member && "HandleField never returns null");
2121 }
2122 } else {
2123 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2124
2125 Member = HandleDeclarator(S, D, TemplateParameterLists);
2126 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002127 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002128
2129 // Non-instance-fields can't have a bitfield.
2130 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002131 if (Member->isInvalidDecl()) {
2132 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002133 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002134 // C++ 9.6p3: A bit-field shall not be a static member.
2135 // "static member 'A' cannot be a bit-field"
2136 Diag(Loc, diag::err_static_not_bitfield)
2137 << Name << BitWidth->getSourceRange();
2138 } else if (isa<TypedefDecl>(Member)) {
2139 // "typedef member 'x' cannot be a bit-field"
2140 Diag(Loc, diag::err_typedef_not_bitfield)
2141 << Name << BitWidth->getSourceRange();
2142 } else {
2143 // A function typedef ("typedef int f(); f a;").
2144 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2145 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002146 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002147 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Craig Topperc3ec1492014-05-26 06:22:03 +00002150 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002151 Member->setInvalidDecl();
2152 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002153
2154 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002155
Larisse Voufo39a1e502013-08-06 01:03:05 +00002156 // If we have declared a member function template or static data member
2157 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002158 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2159 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002160 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2161 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002162 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002163
Richard Smith18f07db2012-08-06 03:25:17 +00002164 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002165 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002166 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002167 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2168 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002169
Douglas Gregorf2f08062011-03-08 17:10:18 +00002170 if (VS.getLastLocation().isValid()) {
2171 // Update the end location of a method that has a virt-specifiers.
2172 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2173 MD->setRangeEnd(VS.getLastLocation());
2174 }
Richard Smith18f07db2012-08-06 03:25:17 +00002175
Anders Carlssonc87f8612011-01-20 06:29:02 +00002176 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002177
Douglas Gregor92751d42008-11-17 22:58:34 +00002178 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002179
Daniel Jasper0baec5492012-06-06 08:32:04 +00002180 if (isInstField) {
2181 FieldDecl *FD = cast<FieldDecl>(Member);
2182 FieldCollector->Add(FD);
2183
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002184 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002185 // Remember all explicit private FieldDecls that have a name, no side
2186 // effects and are not part of a dependent type declaration.
2187 if (!FD->isImplicit() && FD->getDeclName() &&
2188 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002189 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002190 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002191 !InitializationHasSideEffects(*FD))
2192 UnusedPrivateFields.insert(FD);
2193 }
2194 }
2195
John McCall48871652010-08-21 09:40:31 +00002196 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002197}
2198
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002199namespace {
2200 class UninitializedFieldVisitor
2201 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2202 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002203 // List of Decls to generate a warning on. Also remove Decls that become
2204 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002205 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002206 // If non-null, add a note to the warning pointing back to the constructor.
2207 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002208 public:
2209 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002210 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002211 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002212 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002213 : Inherited(S.Context), S(S), Decls(Decls),
2214 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002215
Richard Trieufd687772013-09-16 20:46:50 +00002216 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002217 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2218 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002219
Richard Trieu1bc22c12013-09-13 03:20:53 +00002220 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2221 // or union.
2222 MemberExpr *FieldME = ME;
2223
2224 Expr *Base = ME;
2225 while (isa<MemberExpr>(Base)) {
2226 ME = cast<MemberExpr>(Base);
2227
2228 if (isa<VarDecl>(ME->getMemberDecl()))
2229 return;
2230
2231 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2232 if (!FD->isAnonymousStructOrUnion())
2233 FieldME = ME;
2234
2235 Base = ME->getBase();
2236 }
2237
Richard Trieufd687772013-09-16 20:46:50 +00002238 if (!isa<CXXThisExpr>(Base))
2239 return;
2240
Richard Trieu406e65c2013-09-20 03:03:06 +00002241 ValueDecl* FoundVD = FieldME->getMemberDecl();
2242
Richard Trieuef64e942013-10-25 00:56:00 +00002243 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002244 return;
2245
Richard Trieuef64e942013-10-25 00:56:00 +00002246 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002247
Richard Trieuef64e942013-10-25 00:56:00 +00002248 // Prevent double warnings on use of unbounded references.
2249 if (IsReference != CheckReferenceOnly)
2250 return;
2251
2252 unsigned diag = IsReference
2253 ? diag::warn_reference_field_is_uninit
2254 : diag::warn_field_is_uninit;
2255 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2256 if (Constructor)
2257 S.Diag(Constructor->getLocation(),
2258 diag::note_uninit_in_this_constructor)
2259 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2260
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002261 }
2262
2263 void HandleValue(Expr *E) {
2264 E = E->IgnoreParens();
2265
2266 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002267 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002268 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002269 }
2270
2271 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2272 HandleValue(CO->getTrueExpr());
2273 HandleValue(CO->getFalseExpr());
2274 return;
2275 }
2276
2277 if (BinaryConditionalOperator *BCO =
2278 dyn_cast<BinaryConditionalOperator>(E)) {
2279 HandleValue(BCO->getCommon());
2280 HandleValue(BCO->getFalseExpr());
2281 return;
2282 }
2283
2284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2285 switch (BO->getOpcode()) {
2286 default:
2287 return;
2288 case(BO_PtrMemD):
2289 case(BO_PtrMemI):
2290 HandleValue(BO->getLHS());
2291 return;
2292 case(BO_Comma):
2293 HandleValue(BO->getRHS());
2294 return;
2295 }
2296 }
2297 }
2298
Richard Trieu1bc22c12013-09-13 03:20:53 +00002299 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002300 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002301 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002302
2303 Inherited::VisitMemberExpr(ME);
2304 }
2305
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002306 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2307 if (E->getCastKind() == CK_LValueToRValue)
2308 HandleValue(E->getSubExpr());
2309
2310 Inherited::VisitImplicitCastExpr(E);
2311 }
2312
Richard Trieu1bc22c12013-09-13 03:20:53 +00002313 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002314 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002315 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2316 if (ICE->getCastKind() == CK_NoOp)
2317 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002318 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002319
2320 Inherited::VisitCXXConstructExpr(E);
2321 }
2322
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002323 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2324 Expr *Callee = E->getCallee();
2325 if (isa<MemberExpr>(Callee))
2326 HandleValue(Callee);
2327
2328 Inherited::VisitCXXMemberCallExpr(E);
2329 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002330
2331 void VisitBinaryOperator(BinaryOperator *E) {
2332 // If a field assignment is detected, remove the field from the
2333 // uninitiailized field set.
2334 if (E->getOpcode() == BO_Assign)
2335 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2336 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002337 if (!FD->getType()->isReferenceType())
2338 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002339
2340 Inherited::VisitBinaryOperator(E);
2341 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002342 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002343 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002344 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2345 const CXXConstructorDecl *Constructor) {
2346 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002347 return;
2348
Richard Trieuef64e942013-10-25 00:56:00 +00002349 if (!E)
2350 return;
2351
2352 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2353 E = Default->getExpr();
2354 if (!E)
2355 return;
2356 // In class initializers will point to the constructor.
2357 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2358 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002359 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieuef64e942013-10-25 00:56:00 +00002360 }
2361 }
2362
2363 // Diagnose value-uses of fields to initialize themselves, e.g.
2364 // foo(foo)
2365 // where foo is not also a parameter to the constructor.
2366 // Also diagnose across field uninitialized use such as
2367 // x(y), y(x)
2368 // TODO: implement -Wuninitialized and fold this into that framework.
2369 static void DiagnoseUninitializedFields(
2370 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2371
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002372 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2373 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002374 return;
2375 }
2376
2377 if (Constructor->isInvalidDecl())
2378 return;
2379
2380 const CXXRecordDecl *RD = Constructor->getParent();
2381
2382 // Holds fields that are uninitialized.
2383 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2384
2385 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002386 for (auto *I : RD->decls()) {
2387 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002388 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002389 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002390 UninitializedFields.insert(IFD->getAnonField());
2391 }
2392 }
2393
Aaron Ballman0ad78302014-03-13 17:34:31 +00002394 for (const auto *FieldInit : Constructor->inits()) {
2395 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002396
2397 CheckInitExprContainsUninitializedFields(
2398 SemaRef, InitExpr, UninitializedFields, Constructor);
2399
Aaron Ballman0ad78302014-03-13 17:34:31 +00002400 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002401 UninitializedFields.erase(Field);
2402 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002403 }
2404} // namespace
2405
Richard Smith74108172014-01-17 03:11:34 +00002406/// \brief Enter a new C++ default initializer scope. After calling this, the
2407/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2408/// parsing or instantiating the initializer failed.
2409void Sema::ActOnStartCXXInClassMemberInitializer() {
2410 // Create a synthetic function scope to represent the call to the constructor
2411 // that notionally surrounds a use of this initializer.
2412 PushFunctionScope();
2413}
2414
2415/// \brief This is invoked after parsing an in-class initializer for a
2416/// non-static C++ class member, and after instantiating an in-class initializer
2417/// in a class template. Such actions are deferred until the class is complete.
2418void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2419 SourceLocation InitLoc,
2420 Expr *InitExpr) {
2421 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002422 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002423
Richard Smith938f40b2011-06-11 17:19:42 +00002424 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002425 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2426 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002427
2428 if (!InitExpr) {
2429 FD->setInvalidDecl();
2430 FD->removeInClassInitializer();
2431 return;
2432 }
2433
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002434 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2435 FD->setInvalidDecl();
2436 FD->removeInClassInitializer();
2437 return;
2438 }
2439
Richard Smith938f40b2011-06-11 17:19:42 +00002440 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002441 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002442 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002443 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002444 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002445 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002446 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2447 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002448 if (Init.isInvalid()) {
2449 FD->setInvalidDecl();
2450 return;
2451 }
Richard Smith938f40b2011-06-11 17:19:42 +00002452 }
2453
Richard Smith945f8d32013-01-14 22:39:08 +00002454 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002455 // The initialization of each base and member constitutes a
2456 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002457 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002458 if (Init.isInvalid()) {
2459 FD->setInvalidDecl();
2460 return;
2461 }
2462
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002463 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002464
2465 FD->setInClassInitializer(InitExpr);
2466}
2467
Douglas Gregor15e77a22009-12-31 09:10:24 +00002468/// \brief Find the direct and/or virtual base specifiers that
2469/// correspond to the given base type, for use in base initialization
2470/// within a constructor.
2471static bool FindBaseInitializer(Sema &SemaRef,
2472 CXXRecordDecl *ClassDecl,
2473 QualType BaseType,
2474 const CXXBaseSpecifier *&DirectBaseSpec,
2475 const CXXBaseSpecifier *&VirtualBaseSpec) {
2476 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002477 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002478 for (const auto &Base : ClassDecl->bases()) {
2479 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002480 // We found a direct base of this type. That's what we're
2481 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002482 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002483 break;
2484 }
2485 }
2486
2487 // Check for a virtual base class.
2488 // FIXME: We might be able to short-circuit this if we know in advance that
2489 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002490 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002491 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2492 // We haven't found a base yet; search the class hierarchy for a
2493 // virtual base class.
2494 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2495 /*DetectVirtual=*/false);
2496 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2497 BaseType, Paths)) {
2498 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2499 Path != Paths.end(); ++Path) {
2500 if (Path->back().Base->isVirtual()) {
2501 VirtualBaseSpec = Path->back().Base;
2502 break;
2503 }
2504 }
2505 }
2506 }
2507
2508 return DirectBaseSpec || VirtualBaseSpec;
2509}
2510
Sebastian Redla74948d2011-09-24 17:48:25 +00002511/// \brief Handle a C++ member initializer using braced-init-list syntax.
2512MemInitResult
2513Sema::ActOnMemInitializer(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,
2520 Expr *InitList,
2521 SourceLocation EllipsisLoc) {
2522 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002523 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002524 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002525}
2526
2527/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002528MemInitResult
John McCall48871652010-08-21 09:40:31 +00002529Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002530 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002531 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002532 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002533 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002534 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002535 SourceLocation IdLoc,
2536 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002537 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002538 SourceLocation RParenLoc,
2539 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002540 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002541 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002542 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002543 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002544}
2545
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002546namespace {
2547
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002548// Callback to only accept typo corrections that can be a valid C++ member
2549// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002550class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002551public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002552 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2553 : ClassDecl(ClassDecl) {}
2554
Craig Toppera798a9d2014-03-02 09:32:10 +00002555 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002556 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2557 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2558 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002559 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002560 }
2561 return false;
2562 }
2563
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002564private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002565 CXXRecordDecl *ClassDecl;
2566};
2567
2568}
2569
Sebastian Redla74948d2011-09-24 17:48:25 +00002570/// \brief Handle a C++ member initializer.
2571MemInitResult
2572Sema::BuildMemInitializer(Decl *ConstructorD,
2573 Scope *S,
2574 CXXScopeSpec &SS,
2575 IdentifierInfo *MemberOrBase,
2576 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002577 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002578 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002579 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002580 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002581 if (!ConstructorD)
2582 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002584 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002585
2586 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002587 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002588 if (!Constructor) {
2589 // The user wrote a constructor initializer on a function that is
2590 // not a C++ constructor. Ignore the error for now, because we may
2591 // have more member initializers coming; we'll diagnose it just
2592 // once in ActOnMemInitializers.
2593 return true;
2594 }
2595
2596 CXXRecordDecl *ClassDecl = Constructor->getParent();
2597
2598 // C++ [class.base.init]p2:
2599 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002600 // constructor's class and, if not found in that scope, are looked
2601 // up in the scope containing the constructor's definition.
2602 // [Note: if the constructor's class contains a member with the
2603 // same name as a direct or virtual base class of the class, a
2604 // mem-initializer-id naming the member or base class and composed
2605 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002606 // mem-initializer-id for the hidden base class may be specified
2607 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002608 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002609 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002610 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002611 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002612 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002613 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002614 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2615 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002616 if (EllipsisLoc.isValid())
2617 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002618 << MemberOrBase
2619 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002620
Sebastian Redla9351792012-02-11 23:51:47 +00002621 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002622 }
Francois Pichetd583da02010-12-04 09:14:42 +00002623 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002624 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002625 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002626 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002627 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002628
2629 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002630 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002631 } else if (DS.getTypeSpecType() == TST_decltype) {
2632 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002633 } else {
2634 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2635 LookupParsedName(R, S, &SS);
2636
2637 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2638 if (!TyD) {
2639 if (R.isAmbiguous()) return true;
2640
John McCallda6841b2010-04-09 19:01:14 +00002641 // We don't want access-control diagnostics here.
2642 R.suppressDiagnostics();
2643
Douglas Gregora3b624a2010-01-19 06:46:48 +00002644 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2645 bool NotUnknownSpecialization = false;
2646 DeclContext *DC = computeDeclContext(SS, false);
2647 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2648 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2649
2650 if (!NotUnknownSpecialization) {
2651 // When the scope specifier can refer to a member of an unknown
2652 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002653 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2654 SS.getWithLocInContext(Context),
2655 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002656 if (BaseType.isNull())
2657 return true;
2658
Douglas Gregora3b624a2010-01-19 06:46:48 +00002659 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002660 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002661 }
2662 }
2663
Douglas Gregor15e77a22009-12-31 09:10:24 +00002664 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002665 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002666 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002667 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002668 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002669 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002670 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002671 // We have found a non-static data member with a similar
2672 // name to what was typed; complain and initialize that
2673 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002674 diagnoseTypo(Corr,
2675 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2676 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002677 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002678 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002679 const CXXBaseSpecifier *DirectBaseSpec;
2680 const CXXBaseSpecifier *VirtualBaseSpec;
2681 if (FindBaseInitializer(*this, ClassDecl,
2682 Context.getTypeDeclType(Type),
2683 DirectBaseSpec, VirtualBaseSpec)) {
2684 // We have found a direct or virtual base class with a
2685 // similar name to what was typed; complain and initialize
2686 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002687 diagnoseTypo(Corr,
2688 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2689 << MemberOrBase << false,
2690 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002691
Richard Smithf9b15102013-08-17 00:46:16 +00002692 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2693 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002694 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002695 diag::note_base_class_specified_here)
2696 << BaseSpec->getType()
2697 << BaseSpec->getSourceRange();
2698
Douglas Gregor15e77a22009-12-31 09:10:24 +00002699 TyD = Type;
2700 }
2701 }
2702 }
2703
Douglas Gregora3b624a2010-01-19 06:46:48 +00002704 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002705 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002706 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002707 return true;
2708 }
John McCallb5a0d312009-12-21 10:41:20 +00002709 }
2710
Douglas Gregora3b624a2010-01-19 06:46:48 +00002711 if (BaseType.isNull()) {
2712 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002713 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002714 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002715 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2716 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002717 }
2718 }
Mike Stump11289f42009-09-09 15:08:12 +00002719
John McCallbcd03502009-12-07 02:54:59 +00002720 if (!TInfo)
2721 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002722
Sebastian Redla9351792012-02-11 23:51:47 +00002723 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002724}
2725
Chandler Carruth599deef2011-09-03 01:14:15 +00002726/// Checks a member initializer expression for cases where reference (or
2727/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002728static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2729 Expr *Init,
2730 SourceLocation IdLoc) {
2731 QualType MemberTy = Member->getType();
2732
2733 // We only handle pointers and references currently.
2734 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2735 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2736 return;
2737
2738 const bool IsPointer = MemberTy->isPointerType();
2739 if (IsPointer) {
2740 if (const UnaryOperator *Op
2741 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2742 // The only case we're worried about with pointers requires taking the
2743 // address.
2744 if (Op->getOpcode() != UO_AddrOf)
2745 return;
2746
2747 Init = Op->getSubExpr();
2748 } else {
2749 // We only handle address-of expression initializers for pointers.
2750 return;
2751 }
2752 }
2753
Richard Smithe3b28bc2013-06-12 21:51:50 +00002754 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002755 // We only warn when referring to a non-reference parameter declaration.
2756 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2757 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002758 return;
2759
2760 S.Diag(Init->getExprLoc(),
2761 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2762 : diag::warn_bind_ref_member_to_parameter)
2763 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002764 } else {
2765 // Other initializers are fine.
2766 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002767 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002768
2769 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2770 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002771}
2772
John McCallfaf5fb42010-08-26 23:41:50 +00002773MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002774Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002775 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002776 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2777 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2778 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002779 "Member must be a FieldDecl or IndirectFieldDecl");
2780
Sebastian Redla9351792012-02-11 23:51:47 +00002781 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002782 return true;
2783
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002784 if (Member->isInvalidDecl())
2785 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002786
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002787 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002788 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002789 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002790 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002791 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002792 } else {
2793 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002794 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002795 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002796
Sebastian Redla9351792012-02-11 23:51:47 +00002797 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002798
Sebastian Redla9351792012-02-11 23:51:47 +00002799 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002800 // Can't check initialization for a member of dependent type or when
2801 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002802 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002803 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002804 bool InitList = false;
2805 if (isa<InitListExpr>(Init)) {
2806 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002807 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002808 }
2809
Chandler Carruthd44c3102010-12-06 09:23:57 +00002810 // Initialize the member.
2811 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002812 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2813 : InitializedEntity::InitializeMember(IndirectMember,
2814 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002815 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002816 InitList ? InitializationKind::CreateDirectList(IdLoc)
2817 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2818 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002819
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002820 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002821 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2822 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002823 if (MemberInit.isInvalid())
2824 return true;
2825
Richard Smith736a9472013-06-12 20:42:33 +00002826 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2827
Richard Smith945f8d32013-01-14 22:39:08 +00002828 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002829 // The initialization of each base and member constitutes a
2830 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002831 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002832 if (MemberInit.isInvalid())
2833 return true;
2834
Richard Smithd59b8322012-12-19 01:39:02 +00002835 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002836 }
2837
Chandler Carruthd44c3102010-12-06 09:23:57 +00002838 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002839 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2840 InitRange.getBegin(), Init,
2841 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002842 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002843 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2844 InitRange.getBegin(), Init,
2845 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002846 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002847}
2848
John McCallfaf5fb42010-08-26 23:41:50 +00002849MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002850Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002851 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002852 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002853 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002854 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002855 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002856 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002857
Sebastian Redl0501c632012-02-12 16:37:36 +00002858 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002859 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002860 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2861 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002862 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002863 }
2864
Sebastian Redla9351792012-02-11 23:51:47 +00002865 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002866 // Initialize the object.
2867 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2868 QualType(ClassDecl->getTypeForDecl(), 0));
2869 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002870 InitList ? InitializationKind::CreateDirectList(NameLoc)
2871 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2872 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002873 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002874 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002876 if (DelegationInit.isInvalid())
2877 return true;
2878
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002879 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2880 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002881
Richard Smith945f8d32013-01-14 22:39:08 +00002882 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002883 // The initialization of each base and member constitutes a
2884 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002885 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2886 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002887 if (DelegationInit.isInvalid())
2888 return true;
2889
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002890 // If we are in a dependent context, template instantiation will
2891 // perform this type-checking again. Just save the arguments that we
2892 // received in a ParenListExpr.
2893 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2894 // of the information that we have about the base
2895 // initializer. However, deconstructing the ASTs is a dicey process,
2896 // and this approach is far more likely to get the corner cases right.
2897 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002898 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002899
Sebastian Redla9351792012-02-11 23:51:47 +00002900 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002901 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002902 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002903}
2904
2905MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002906Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002907 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002908 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002909 SourceLocation BaseLoc
2910 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002911
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002912 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2913 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2914 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2915
2916 // C++ [class.base.init]p2:
2917 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002918 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002919 // of that class, the mem-initializer is ill-formed. A
2920 // mem-initializer-list can initialize a base class using any
2921 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002922 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002923
Sebastian Redla9351792012-02-11 23:51:47 +00002924 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002925 if (EllipsisLoc.isValid()) {
2926 // This is a pack expansion.
2927 if (!BaseType->containsUnexpandedParameterPack()) {
2928 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002929 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002930
Douglas Gregor44e7df62011-01-04 00:32:56 +00002931 EllipsisLoc = SourceLocation();
2932 }
2933 } else {
2934 // Check for any unexpanded parameter packs.
2935 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2936 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002937
Sebastian Redla9351792012-02-11 23:51:47 +00002938 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002939 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002940 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002941
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002942 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002943 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2944 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002945 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002946 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2947 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002948 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002949
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002950 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2951 VirtualBaseSpec);
2952
2953 // C++ [base.class.init]p2:
2954 // Unless the mem-initializer-id names a nonstatic data member of the
2955 // constructor's class or a direct or virtual base of that class, the
2956 // mem-initializer is ill-formed.
2957 if (!DirectBaseSpec && !VirtualBaseSpec) {
2958 // If the class has any dependent bases, then it's possible that
2959 // one of those types will resolve to the same type as
2960 // BaseType. Therefore, just treat this as a dependent base
2961 // class initialization. FIXME: Should we try to check the
2962 // initialization anyway? It seems odd.
2963 if (ClassDecl->hasAnyDependentBases())
2964 Dependent = true;
2965 else
2966 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2967 << BaseType << Context.getTypeDeclType(ClassDecl)
2968 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2969 }
2970 }
2971
2972 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002973 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002974
Sebastian Redla74948d2011-09-24 17:48:25 +00002975 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2976 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002977 InitRange.getBegin(), Init,
2978 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002979 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002980
2981 // C++ [base.class.init]p2:
2982 // If a mem-initializer-id is ambiguous because it designates both
2983 // a direct non-virtual base class and an inherited virtual base
2984 // class, the mem-initializer is ill-formed.
2985 if (DirectBaseSpec && VirtualBaseSpec)
2986 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002987 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002988
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002989 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002990 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002991 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002992
2993 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002994 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002995 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002996 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002997 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002998 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002999 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003000
3001 InitializedEntity BaseEntity =
3002 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3003 InitializationKind Kind =
3004 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3005 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3006 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003007 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003008 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003009 if (BaseInit.isInvalid())
3010 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003011
Richard Smith945f8d32013-01-14 22:39:08 +00003012 // C++11 [class.base.init]p7:
3013 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003014 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003015 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003016 if (BaseInit.isInvalid())
3017 return true;
3018
3019 // If we are in a dependent context, template instantiation will
3020 // perform this type-checking again. Just save the arguments that we
3021 // received in a ParenListExpr.
3022 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3023 // of the information that we have about the base
3024 // initializer. However, deconstructing the ASTs is a dicey process,
3025 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003026 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003027 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003028
Alexis Hunt1d792652011-01-08 20:30:50 +00003029 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003030 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003031 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003032 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003033 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003034}
3035
Sebastian Redl22653ba2011-08-30 19:58:05 +00003036// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003037static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3038 if (T.isNull()) T = E->getType();
3039 QualType TargetType = SemaRef.BuildReferenceType(
3040 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003041 SourceLocation ExprLoc = E->getLocStart();
3042 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3043 TargetType, ExprLoc);
3044
3045 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3046 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003047 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003048}
3049
Anders Carlsson1b00e242010-04-23 03:10:23 +00003050/// ImplicitInitializerKind - How an implicit base or member initializer should
3051/// initialize its base or member.
3052enum ImplicitInitializerKind {
3053 IIK_Default,
3054 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003055 IIK_Move,
3056 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003057};
3058
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003059static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003060BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003061 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003062 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003063 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003064 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003065 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003066 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3067 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003068
John McCalldadc5752010-08-24 06:29:42 +00003069 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003070
3071 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003072 case IIK_Inherit: {
3073 const CXXRecordDecl *Inherited =
3074 Constructor->getInheritedConstructor()->getParent();
3075 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3076 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3077 // C++11 [class.inhctor]p8:
3078 // Each expression in the expression-list is of the form
3079 // static_cast<T&&>(p), where p is the name of the corresponding
3080 // constructor parameter and T is the declared type of p.
3081 SmallVector<Expr*, 16> Args;
3082 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3083 ParmVarDecl *PD = Constructor->getParamDecl(I);
3084 ExprResult ArgExpr =
3085 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3086 VK_LValue, SourceLocation());
3087 if (ArgExpr.isInvalid())
3088 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003089 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003090 }
3091
3092 InitializationKind InitKind = InitializationKind::CreateDirect(
3093 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003094 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003095 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3096 break;
3097 }
3098 }
3099 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003100 case IIK_Default: {
3101 InitializationKind InitKind
3102 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003103 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3104 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003105 break;
3106 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003107
Sebastian Redl22653ba2011-08-30 19:58:05 +00003108 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003109 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003110 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003111 ParmVarDecl *Param = Constructor->getParamDecl(0);
3112 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003113
Anders Carlsson1b00e242010-04-23 03:10:23 +00003114 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003115 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003116 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003117 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003118 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119
Eli Friedmanfa0df832012-02-02 03:46:19 +00003120 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3121
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003122 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003123 QualType ArgTy =
3124 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3125 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003126
Sebastian Redl22653ba2011-08-30 19:58:05 +00003127 if (Moving) {
3128 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3129 }
3130
John McCallcf142162010-08-07 06:22:56 +00003131 CXXCastPath BasePath;
3132 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003133 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3134 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003135 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003136 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003137
Anders Carlsson1b00e242010-04-23 03:10:23 +00003138 InitializationKind InitKind
3139 = InitializationKind::CreateDirect(Constructor->getLocation(),
3140 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003141 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3142 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003143 break;
3144 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003145 }
John McCallb268a282010-08-23 23:25:46 +00003146
Douglas Gregora40433a2010-12-07 00:41:46 +00003147 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003148 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003149 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003150
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003151 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003152 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003153 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3154 SourceLocation()),
3155 BaseSpec->isVirtual(),
3156 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003157 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003158 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003159 SourceLocation());
3160
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003161 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003162}
3163
Sebastian Redl22653ba2011-08-30 19:58:05 +00003164static bool RefersToRValueRef(Expr *MemRef) {
3165 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3166 return Referenced->getType()->isRValueReferenceType();
3167}
3168
Anders Carlsson3c1db572010-04-23 02:15:47 +00003169static bool
3170BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003171 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003172 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003173 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003174 if (Field->isInvalidDecl())
3175 return true;
3176
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003177 SourceLocation Loc = Constructor->getLocation();
3178
Sebastian Redl22653ba2011-08-30 19:58:05 +00003179 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3180 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003181 ParmVarDecl *Param = Constructor->getParamDecl(0);
3182 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003183
3184 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003185 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3186 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003187
Anders Carlsson423f5d82010-04-23 16:04:08 +00003188 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003189 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003190 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003191 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003192
Eli Friedmanfa0df832012-02-02 03:46:19 +00003193 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3194
Sebastian Redl22653ba2011-08-30 19:58:05 +00003195 if (Moving) {
3196 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3197 }
3198
Douglas Gregor94f9a482010-05-05 05:51:00 +00003199 // Build a reference to this field within the parameter.
3200 CXXScopeSpec SS;
3201 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3202 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003203 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3204 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003205 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003206 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003207 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 ParamType, Loc,
3209 /*IsArrow=*/false,
3210 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003211 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003212 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003213 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003214 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003215 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003216 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003217
3218 // C++11 [class.copy]p15:
3219 // - if a member m has rvalue reference type T&&, it is direct-initialized
3220 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003221 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003222 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003223 }
3224
Douglas Gregor94f9a482010-05-05 05:51:00 +00003225 // When the field we are copying is an array, create index variables for
3226 // each dimension of the array. We use these index variables to subscript
3227 // the source array, and other clients (e.g., CodeGen) will perform the
3228 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003229 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003230 QualType BaseType = Field->getType();
3231 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003232 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003233 while (const ConstantArrayType *Array
3234 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003235 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003236 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003237 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003238 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003239 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003240 llvm::raw_svector_ostream OS(Str);
3241 OS << "__i" << IndexVariables.size();
3242 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3243 }
3244 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003245 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003246 IterationVarName, SizeType,
3247 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003248 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003249 IndexVariables.push_back(IterationVar);
3250
3251 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003252 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003253 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003254 assert(!IterationVarRef.isInvalid() &&
3255 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003256 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003257 assert(!IterationVarRef.isInvalid() &&
3258 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003259
Douglas Gregor94f9a482010-05-05 05:51:00 +00003260 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003261 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3262 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003263 Loc);
3264 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003265 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003266
Douglas Gregor94f9a482010-05-05 05:51:00 +00003267 BaseType = Array->getElementType();
3268 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003269
3270 // The array subscript expression is an lvalue, which is wrong for moving.
3271 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003272 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003273
Douglas Gregor94f9a482010-05-05 05:51:00 +00003274 // Construct the entity that we will be initializing. For an array, this
3275 // will be first element in the array, which may require several levels
3276 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003277 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003278 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003279 if (Indirect)
3280 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3281 else
3282 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003283 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3284 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3285 0,
3286 Entities.back()));
3287
3288 // Direct-initialize to use the copy constructor.
3289 InitializationKind InitKind =
3290 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3291
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003292 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003293 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003294
John McCalldadc5752010-08-24 06:29:42 +00003295 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003296 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003297 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003298 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003299 if (MemberInit.isInvalid())
3300 return true;
3301
Douglas Gregor493627b2011-08-10 15:22:55 +00003302 if (Indirect) {
3303 assert(IndexVariables.size() == 0 &&
3304 "Indirect field improperly initialized");
3305 CXXMemberInit
3306 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3307 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003308 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003309 Loc);
3310 } else
3311 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003312 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003313 Loc,
3314 IndexVariables.data(),
3315 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003316 return false;
3317 }
3318
Richard Smithc2bc61b2013-03-18 21:12:30 +00003319 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3320 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003321
Anders Carlsson3c1db572010-04-23 02:15:47 +00003322 QualType FieldBaseElementType =
3323 SemaRef.Context.getBaseElementType(Field->getType());
3324
Anders Carlsson3c1db572010-04-23 02:15:47 +00003325 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003326 InitializedEntity InitEntity
3327 = Indirect? InitializedEntity::InitializeMember(Indirect)
3328 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003329 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003330 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003331
3332 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3333 ExprResult MemberInit =
3334 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003335
Douglas Gregora40433a2010-12-07 00:41:46 +00003336 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003337 if (MemberInit.isInvalid())
3338 return true;
3339
Douglas Gregor493627b2011-08-10 15:22:55 +00003340 if (Indirect)
3341 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3342 Indirect, Loc,
3343 Loc,
3344 MemberInit.get(),
3345 Loc);
3346 else
3347 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3348 Field, Loc, Loc,
3349 MemberInit.get(),
3350 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003351 return false;
3352 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003353
Alexis Hunt8b455182011-05-17 00:19:05 +00003354 if (!Field->getParent()->isUnion()) {
3355 if (FieldBaseElementType->isReferenceType()) {
3356 SemaRef.Diag(Constructor->getLocation(),
3357 diag::err_uninitialized_member_in_ctor)
3358 << (int)Constructor->isImplicit()
3359 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3360 << 0 << Field->getDeclName();
3361 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3362 return true;
3363 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003364
Alexis Hunt8b455182011-05-17 00:19:05 +00003365 if (FieldBaseElementType.isConstQualified()) {
3366 SemaRef.Diag(Constructor->getLocation(),
3367 diag::err_uninitialized_member_in_ctor)
3368 << (int)Constructor->isImplicit()
3369 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3370 << 1 << Field->getDeclName();
3371 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3372 return true;
3373 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003374 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003375
David Blaikiebbafb8a2012-03-11 07:00:24 +00003376 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003377 FieldBaseElementType->isObjCRetainableType() &&
3378 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3379 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003380 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003381 // Default-initialize Objective-C pointers to NULL.
3382 CXXMemberInit
3383 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3384 Loc, Loc,
3385 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3386 Loc);
3387 return false;
3388 }
3389
Anders Carlsson3c1db572010-04-23 02:15:47 +00003390 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003391 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003392 return false;
3393}
John McCallbc83b3f2010-05-20 23:23:51 +00003394
3395namespace {
3396struct BaseAndFieldInfo {
3397 Sema &S;
3398 CXXConstructorDecl *Ctor;
3399 bool AnyErrorsInInits;
3400 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003401 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003402 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003403 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003404
3405 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3406 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003407 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3408 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003409 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003410 else if (Generated && Ctor->isMoveConstructor())
3411 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003412 else if (Ctor->getInheritedConstructor())
3413 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003414 else
3415 IIK = IIK_Default;
3416 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003417
3418 bool isImplicitCopyOrMove() const {
3419 switch (IIK) {
3420 case IIK_Copy:
3421 case IIK_Move:
3422 return true;
3423
3424 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003425 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003426 return false;
3427 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003428
3429 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003430 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003431
3432 bool addFieldInitializer(CXXCtorInitializer *Init) {
3433 AllToInit.push_back(Init);
3434
3435 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003436 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003437 S.UnusedPrivateFields.remove(Init->getAnyMember());
3438
3439 return false;
3440 }
John McCallbc83b3f2010-05-20 23:23:51 +00003441
Richard Smithab44d5b2013-12-10 08:25:00 +00003442 bool isInactiveUnionMember(FieldDecl *Field) {
3443 RecordDecl *Record = Field->getParent();
3444 if (!Record->isUnion())
3445 return false;
3446
Richard Smith8d183852013-12-10 20:56:03 +00003447 if (FieldDecl *Active =
3448 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003449 return Active != Field->getCanonicalDecl();
3450
3451 // In an implicit copy or move constructor, ignore any in-class initializer.
3452 if (isImplicitCopyOrMove())
3453 return true;
3454
3455 // If there's no explicit initialization, the field is active only if it
3456 // has an in-class initializer...
3457 if (Field->hasInClassInitializer())
3458 return false;
3459 // ... or it's an anonymous struct or union whose class has an in-class
3460 // initializer.
3461 if (!Field->isAnonymousStructOrUnion())
3462 return true;
3463 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3464 return !FieldRD->hasInClassInitializer();
3465 }
3466
3467 /// \brief Determine whether the given field is, or is within, a union member
3468 /// that is inactive (because there was an initializer given for a different
3469 /// member of the union, or because the union was not initialized at all).
3470 bool isWithinInactiveUnionMember(FieldDecl *Field,
3471 IndirectFieldDecl *Indirect) {
3472 if (!Indirect)
3473 return isInactiveUnionMember(Field);
3474
Aaron Ballman29c94602014-03-07 18:36:15 +00003475 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003476 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003477 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003478 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003479 }
3480 return false;
3481 }
3482};
Richard Smithc94ec842011-09-19 13:34:43 +00003483}
3484
Douglas Gregor10f939c2011-11-02 23:04:16 +00003485/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3486/// array type.
3487static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3488 if (T->isIncompleteArrayType())
3489 return true;
3490
3491 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3492 if (!ArrayT->getSize())
3493 return true;
3494
3495 T = ArrayT->getElementType();
3496 }
3497
3498 return false;
3499}
3500
Richard Smith938f40b2011-06-11 17:19:42 +00003501static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003502 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003503 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003504 if (Field->isInvalidDecl())
3505 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003506
Chandler Carruth139e9622010-06-30 02:59:29 +00003507 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003508 if (CXXCtorInitializer *Init =
3509 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003510 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003511
Richard Smithab44d5b2013-12-10 08:25:00 +00003512 // C++11 [class.base.init]p8:
3513 // if the entity is a non-static data member that has a
3514 // brace-or-equal-initializer and either
3515 // -- the constructor's class is a union and no other variant member of that
3516 // union is designated by a mem-initializer-id or
3517 // -- the constructor's class is not a union, and, if the entity is a member
3518 // of an anonymous union, no other member of that union is designated by
3519 // a mem-initializer-id,
3520 // the entity is initialized as specified in [dcl.init].
3521 //
3522 // We also apply the same rules to handle anonymous structs within anonymous
3523 // unions.
3524 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3525 return false;
3526
Douglas Gregor7db3e952011-11-28 20:03:15 +00003527 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003528 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3529 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003530 CXXCtorInitializer *Init;
3531 if (Indirect)
3532 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3533 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003534 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003535 SourceLocation());
3536 else
3537 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3538 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003539 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003540 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003541 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003542 }
3543
Douglas Gregor10f939c2011-11-02 23:04:16 +00003544 // Don't initialize incomplete or zero-length arrays.
3545 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3546 return false;
3547
John McCallbc83b3f2010-05-20 23:23:51 +00003548 // Don't try to build an implicit initializer if there were semantic
3549 // errors in any of the initializers (and therefore we might be
3550 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003551 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003552 return false;
3553
Craig Topperc3ec1492014-05-26 06:22:03 +00003554 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003555 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3556 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003557 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003558
Richard Smith0a8cfc72012-08-07 21:30:42 +00003559 if (!Init)
3560 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003561
Richard Smith0a8cfc72012-08-07 21:30:42 +00003562 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003563}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003564
3565bool
3566Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3567 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003568 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003569 Constructor->setNumCtorInitializers(1);
3570 CXXCtorInitializer **initializer =
3571 new (Context) CXXCtorInitializer*[1];
3572 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3573 Constructor->setCtorInitializers(initializer);
3574
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003575 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003576 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003577 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3578 }
3579
Alexis Hunte2622992011-05-05 00:05:47 +00003580 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003581
Alexis Hunt61bc1732011-05-01 07:04:31 +00003582 return false;
3583}
Douglas Gregor493627b2011-08-10 15:22:55 +00003584
David Blaikie3fc2f912013-01-17 05:26:25 +00003585bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3586 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003587 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003588 // Just store the initializers as written, they will be checked during
3589 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003590 if (!Initializers.empty()) {
3591 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003592 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003593 new (Context) CXXCtorInitializer*[Initializers.size()];
3594 memcpy(baseOrMemberInitializers, Initializers.data(),
3595 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003596 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003597 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003598
3599 // Let template instantiation know whether we had errors.
3600 if (AnyErrors)
3601 Constructor->setInvalidDecl();
3602
Anders Carlssondb0a9652010-04-02 06:26:44 +00003603 return false;
3604 }
3605
John McCallbc83b3f2010-05-20 23:23:51 +00003606 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003607
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003608 // We need to build the initializer AST according to order of construction
3609 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003610 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003611 if (!ClassDecl)
3612 return true;
3613
Eli Friedman9cf6b592009-11-09 19:20:36 +00003614 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003615
David Blaikie3fc2f912013-01-17 05:26:25 +00003616 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003617 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003618
Anders Carlssondb0a9652010-04-02 06:26:44 +00003619 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003620 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003621 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003622 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003623
3624 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003625 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003626 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003627 if (FD && FD->getParent()->isUnion())
3628 Info.ActiveUnionMember.insert(std::make_pair(
3629 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3630 }
3631 } else if (FieldDecl *FD = Member->getMember()) {
3632 if (FD->getParent()->isUnion())
3633 Info.ActiveUnionMember.insert(std::make_pair(
3634 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3635 }
3636 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003637 }
3638
Anders Carlsson43c64af2010-04-21 19:52:01 +00003639 // Keep track of the direct virtual bases.
3640 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003641 for (auto &I : ClassDecl->bases()) {
3642 if (I.isVirtual())
3643 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003644 }
3645
Anders Carlssondb0a9652010-04-02 06:26:44 +00003646 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003647 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003648 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003649 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003650 // [class.base.init]p7, per DR257:
3651 // A mem-initializer where the mem-initializer-id names a virtual base
3652 // class is ignored during execution of a constructor of any class that
3653 // is not the most derived class.
3654 if (ClassDecl->isAbstract()) {
3655 // FIXME: Provide a fixit to remove the base specifier. This requires
3656 // tracking the location of the associated comma for a base specifier.
3657 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003658 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003659 DiagnoseAbstractType(ClassDecl);
3660 }
3661
John McCallbc83b3f2010-05-20 23:23:51 +00003662 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003663 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3664 // [class.base.init]p8, per DR257:
3665 // If a given [...] base class is not named by a mem-initializer-id
3666 // [...] and the entity is not a virtual base class of an abstract
3667 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003668 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003669 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003670 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003671 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003672 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003673 HadError = true;
3674 continue;
3675 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003676
John McCallbc83b3f2010-05-20 23:23:51 +00003677 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003678 }
3679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
John McCallbc83b3f2010-05-20 23:23:51 +00003681 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003682 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003683 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003684 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003685 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003686
Alexis Hunt1d792652011-01-08 20:30:50 +00003687 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003688 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003689 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003690 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003691 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003692 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003693 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003694 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003695 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003696 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003697 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003698
John McCallbc83b3f2010-05-20 23:23:51 +00003699 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003700 }
3701 }
Mike Stump11289f42009-09-09 15:08:12 +00003702
John McCallbc83b3f2010-05-20 23:23:51 +00003703 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003704 for (auto *Mem : ClassDecl->decls()) {
3705 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003706 // C++ [class.bit]p2:
3707 // A declaration for a bit-field that omits the identifier declares an
3708 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3709 // initialized.
3710 if (F->isUnnamedBitfield())
3711 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003712
Sebastian Redl22653ba2011-08-30 19:58:05 +00003713 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003714 // handle anonymous struct/union fields based on their individual
3715 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003716 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003717 continue;
3718
3719 if (CollectFieldInitializer(*this, Info, F))
3720 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003721 continue;
3722 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003723
3724 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003725 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003726 continue;
3727
Aaron Ballman629afae2014-03-07 19:56:05 +00003728 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003729 if (F->getType()->isIncompleteArrayType()) {
3730 assert(ClassDecl->hasFlexibleArrayMember() &&
3731 "Incomplete array type is not valid");
3732 continue;
3733 }
3734
Douglas Gregor493627b2011-08-10 15:22:55 +00003735 // Initialize each field of an anonymous struct individually.
3736 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3737 HadError = true;
3738
3739 continue;
3740 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003741 }
Mike Stump11289f42009-09-09 15:08:12 +00003742
David Blaikie3fc2f912013-01-17 05:26:25 +00003743 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003744 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003745 Constructor->setNumCtorInitializers(NumInitializers);
3746 CXXCtorInitializer **baseOrMemberInitializers =
3747 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003748 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003749 NumInitializers * sizeof(CXXCtorInitializer*));
3750 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003751
John McCalla6309952010-03-16 21:39:52 +00003752 // Constructors implicitly reference the base and member
3753 // destructors.
3754 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3755 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003756 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003757
3758 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003759}
3760
David Blaikieb61b8152013-01-17 08:49:22 +00003761static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003762 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003763 const RecordDecl *RD = RT->getDecl();
3764 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003765 for (auto *Field : RD->fields())
3766 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003767 return;
3768 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003769 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003770 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003771}
3772
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003773static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3774 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003775}
3776
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003777static const void *GetKeyForMember(ASTContext &Context,
3778 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003779 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003780 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003781
Richard Smithcd45dbc2014-04-19 03:48:30 +00003782 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003783}
3784
David Blaikie3fc2f912013-01-17 05:26:25 +00003785static void DiagnoseBaseOrMemInitializerOrder(
3786 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3787 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003788 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003789 return;
Mike Stump11289f42009-09-09 15:08:12 +00003790
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003791 // Don't check initializers order unless the warning is enabled at the
3792 // location of at least one initializer.
3793 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003794 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003795 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003796 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3797 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003798 ShouldCheckOrder = true;
3799 break;
3800 }
3801 }
3802 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003803 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003804
John McCallbb7b6582010-04-10 07:37:23 +00003805 // Build the list of bases and members in the order that they'll
3806 // actually be initialized. The explicit initializers should be in
3807 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003808 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003809
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003810 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3811
John McCallbb7b6582010-04-10 07:37:23 +00003812 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003813 for (const auto &VBase : ClassDecl->vbases())
3814 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003815
John McCallbb7b6582010-04-10 07:37:23 +00003816 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003817 for (const auto &Base : ClassDecl->bases()) {
3818 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003819 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003820 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003821 }
Mike Stump11289f42009-09-09 15:08:12 +00003822
John McCallbb7b6582010-04-10 07:37:23 +00003823 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003824 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003825 if (Field->isUnnamedBitfield())
3826 continue;
3827
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003828 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003829 }
3830
John McCallbb7b6582010-04-10 07:37:23 +00003831 unsigned NumIdealInits = IdealInitKeys.size();
3832 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003833
Craig Topperc3ec1492014-05-26 06:22:03 +00003834 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003835 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003836 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003837 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003838
3839 // Scan forward to try to find this initializer in the idealized
3840 // initializers list.
3841 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3842 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003843 break;
John McCallbb7b6582010-04-10 07:37:23 +00003844
3845 // If we didn't find this initializer, it must be because we
3846 // scanned past it on a previous iteration. That can only
3847 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003848 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003849 Sema::SemaDiagnosticBuilder D =
3850 SemaRef.Diag(PrevInit->getSourceLocation(),
3851 diag::warn_initializer_out_of_order);
3852
Francois Pichetd583da02010-12-04 09:14:42 +00003853 if (PrevInit->isAnyMemberInitializer())
3854 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003855 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003856 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003857
Francois Pichetd583da02010-12-04 09:14:42 +00003858 if (Init->isAnyMemberInitializer())
3859 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003860 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003861 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003862
3863 // Move back to the initializer's location in the ideal list.
3864 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3865 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003866 break;
John McCallbb7b6582010-04-10 07:37:23 +00003867
3868 assert(IdealIndex != NumIdealInits &&
3869 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003870 }
John McCallbb7b6582010-04-10 07:37:23 +00003871
3872 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003873 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003874}
3875
John McCall23eebd92010-04-10 09:28:51 +00003876namespace {
3877bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003878 CXXCtorInitializer *Init,
3879 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003880 if (!PrevInit) {
3881 PrevInit = Init;
3882 return false;
3883 }
3884
Douglas Gregorea306a12013-03-25 23:28:23 +00003885 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003886 S.Diag(Init->getSourceLocation(),
3887 diag::err_multiple_mem_initialization)
3888 << Field->getDeclName()
3889 << Init->getSourceRange();
3890 else {
John McCall424cec92011-01-19 06:33:43 +00003891 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003892 assert(BaseClass && "neither field nor base");
3893 S.Diag(Init->getSourceLocation(),
3894 diag::err_multiple_base_initialization)
3895 << QualType(BaseClass, 0)
3896 << Init->getSourceRange();
3897 }
3898 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3899 << 0 << PrevInit->getSourceRange();
3900
3901 return true;
3902}
3903
Alexis Hunt1d792652011-01-08 20:30:50 +00003904typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003905typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3906
3907bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003908 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003909 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003910 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003911 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003912 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003913
3914 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003915 if (Parent->isUnion()) {
3916 UnionEntry &En = Unions[Parent];
3917 if (En.first && En.first != Child) {
3918 S.Diag(Init->getSourceLocation(),
3919 diag::err_multiple_mem_union_initialization)
3920 << Field->getDeclName()
3921 << Init->getSourceRange();
3922 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3923 << 0 << En.second->getSourceRange();
3924 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003925 }
3926 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003927 En.first = Child;
3928 En.second = Init;
3929 }
David Blaikie0f65d592011-11-17 06:01:57 +00003930 if (!Parent->isAnonymousStructOrUnion())
3931 return false;
John McCall23eebd92010-04-10 09:28:51 +00003932 }
3933
3934 Child = Parent;
3935 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003936 }
John McCall23eebd92010-04-10 09:28:51 +00003937
3938 return false;
3939}
3940}
3941
Anders Carlssone857b292010-04-02 03:37:03 +00003942/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003943void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003944 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003945 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003946 bool AnyErrors) {
3947 if (!ConstructorDecl)
3948 return;
3949
3950 AdjustDeclIfTemplate(ConstructorDecl);
3951
3952 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003953 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003954
3955 if (!Constructor) {
3956 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3957 return;
3958 }
3959
John McCall23eebd92010-04-10 09:28:51 +00003960 // Mapping for the duplicate initializers check.
3961 // For member initializers, this is keyed with a FieldDecl*.
3962 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003963 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003964
3965 // Mapping for the inconsistent anonymous-union initializers check.
3966 RedundantUnionMap MemberUnions;
3967
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003968 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003969 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003970 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003971
Abramo Bagnara341d7832010-05-26 18:09:23 +00003972 // Set the source order index.
3973 Init->setSourceOrder(i);
3974
Francois Pichetd583da02010-12-04 09:14:42 +00003975 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003976 const void *Key = GetKeyForMember(Context, Init);
3977 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003978 CheckRedundantUnionInit(*this, Init, MemberUnions))
3979 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003980 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003981 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003982 if (CheckRedundantInit(*this, Init, Members[Key]))
3983 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003984 } else {
3985 assert(Init->isDelegatingInitializer());
3986 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003987 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003988 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003989 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003990 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003991 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003992 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003993 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003994 // Return immediately as the initializer is set.
3995 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003996 }
Anders Carlssone857b292010-04-02 03:37:03 +00003997 }
3998
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003999 if (HadError)
4000 return;
4001
David Blaikie3fc2f912013-01-17 05:26:25 +00004002 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004003
David Blaikie3fc2f912013-01-17 05:26:25 +00004004 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004005
Richard Trieuef64e942013-10-25 00:56:00 +00004006 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004007}
4008
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004009void
John McCalla6309952010-03-16 21:39:52 +00004010Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4011 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004012 // Ignore dependent contexts. Also ignore unions, since their members never
4013 // have destructors implicitly called.
4014 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004015 return;
John McCall1064d7e2010-03-16 05:22:47 +00004016
4017 // FIXME: all the access-control diagnostics are positioned on the
4018 // field/base declaration. That's probably good; that said, the
4019 // user might reasonably want to know why the destructor is being
4020 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004021
Anders Carlssondee9a302009-11-17 04:44:12 +00004022 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004023 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004024 if (Field->isInvalidDecl())
4025 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004026
4027 // Don't destroy incomplete or zero-length arrays.
4028 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4029 continue;
4030
Anders Carlssondee9a302009-11-17 04:44:12 +00004031 QualType FieldType = Context.getBaseElementType(Field->getType());
4032
4033 const RecordType* RT = FieldType->getAs<RecordType>();
4034 if (!RT)
4035 continue;
4036
4037 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004038 if (FieldClassDecl->isInvalidDecl())
4039 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004040 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004041 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004042 // The destructor for an implicit anonymous union member is never invoked.
4043 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4044 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004045
Douglas Gregore71edda2010-07-01 22:47:18 +00004046 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004047 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004048 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004049 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004050 << Field->getDeclName()
4051 << FieldType);
4052
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004053 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004054 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004055 }
4056
John McCall1064d7e2010-03-16 05:22:47 +00004057 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4058
Anders Carlssondee9a302009-11-17 04:44:12 +00004059 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004060 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004061 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004062 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004063
4064 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004065 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004066 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004067
John McCall1064d7e2010-03-16 05:22:47 +00004068 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004069 // If our base class is invalid, we probably can't get its dtor anyway.
4070 if (BaseClassDecl->isInvalidDecl())
4071 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004072 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004073 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004074
Douglas Gregore71edda2010-07-01 22:47:18 +00004075 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004076 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004077
4078 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004079 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004080 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004081 << Base.getType()
4082 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004083 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004084
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004085 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004086 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004087 }
4088
4089 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004090 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004091 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004092 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004093
4094 // Ignore direct virtual bases.
4095 if (DirectVirtualBases.count(RT))
4096 continue;
4097
John McCall1064d7e2010-03-16 05:22:47 +00004098 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004099 // If our base class is invalid, we probably can't get its dtor anyway.
4100 if (BaseClassDecl->isInvalidDecl())
4101 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004102 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004103 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004104
Douglas Gregore71edda2010-07-01 22:47:18 +00004105 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004106 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004107 if (CheckDestructorAccess(
4108 ClassDecl->getLocation(), Dtor,
4109 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004110 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004111 Context.getTypeDeclType(ClassDecl)) ==
4112 AR_accessible) {
4113 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004114 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004115 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004116 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004117 }
John McCall1064d7e2010-03-16 05:22:47 +00004118
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004119 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004120 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004121 }
4122}
4123
John McCall48871652010-08-21 09:40:31 +00004124void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004125 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004126 return;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Mike Stump11289f42009-09-09 15:08:12 +00004128 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004129 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004130 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004131 DiagnoseUninitializedFields(*this, Constructor);
4132 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004133}
4134
Mike Stump11289f42009-09-09 15:08:12 +00004135bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004136 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004137 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4138 unsigned DiagID;
4139 AbstractDiagSelID SelID;
4140
4141 public:
4142 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4143 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004144
Craig Toppera798a9d2014-03-02 09:32:10 +00004145 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004146 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004147 if (SelID == -1)
4148 S.Diag(Loc, DiagID) << T;
4149 else
4150 S.Diag(Loc, DiagID) << SelID << T;
4151 }
4152 } Diagnoser(DiagID, SelID);
4153
4154 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004155}
4156
Anders Carlssoneabf7702009-08-27 00:13:57 +00004157bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004158 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004159 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004160 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004161
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004162 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004163 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004164
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004165 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004166 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004167 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004168 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004169
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004170 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004171 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004172 }
Mike Stump11289f42009-09-09 15:08:12 +00004173
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004174 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004175 if (!RT)
4176 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004177
John McCall67da35c2010-02-04 22:26:26 +00004178 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004179
John McCall02db245d2010-08-18 09:41:07 +00004180 // We can't answer whether something is abstract until it has a
4181 // definition. If it's currently being defined, we'll walk back
4182 // over all the declarations when we have a full definition.
4183 const CXXRecordDecl *Def = RD->getDefinition();
4184 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004185 return false;
4186
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004187 if (!RD->isAbstract())
4188 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004189
Douglas Gregorae298422012-05-04 17:09:59 +00004190 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004191 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004192
John McCall02db245d2010-08-18 09:41:07 +00004193 return true;
4194}
4195
4196void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4197 // Check if we've already emitted the list of pure virtual functions
4198 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004199 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004200 return;
Mike Stump11289f42009-09-09 15:08:12 +00004201
Richard Smithbc46e432013-07-22 02:56:56 +00004202 // If the diagnostic is suppressed, don't emit the notes. We're only
4203 // going to emit them once, so try to attach them to a diagnostic we're
4204 // actually going to show.
4205 if (Diags.isLastDiagnosticIgnored())
4206 return;
4207
Douglas Gregor4165bd62010-03-23 23:47:56 +00004208 CXXFinalOverriderMap FinalOverriders;
4209 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004210
Anders Carlssona2f74f32010-06-03 01:00:02 +00004211 // Keep a set of seen pure methods so we won't diagnose the same method
4212 // more than once.
4213 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4214
Douglas Gregor4165bd62010-03-23 23:47:56 +00004215 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4216 MEnd = FinalOverriders.end();
4217 M != MEnd;
4218 ++M) {
4219 for (OverridingMethods::iterator SO = M->second.begin(),
4220 SOEnd = M->second.end();
4221 SO != SOEnd; ++SO) {
4222 // C++ [class.abstract]p4:
4223 // A class is abstract if it contains or inherits at least one
4224 // pure virtual function for which the final overrider is pure
4225 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004226
Douglas Gregor4165bd62010-03-23 23:47:56 +00004227 //
4228 if (SO->second.size() != 1)
4229 continue;
4230
4231 if (!SO->second.front().Method->isPure())
4232 continue;
4233
Anders Carlssona2f74f32010-06-03 01:00:02 +00004234 if (!SeenPureMethods.insert(SO->second.front().Method))
4235 continue;
4236
Douglas Gregor4165bd62010-03-23 23:47:56 +00004237 Diag(SO->second.front().Method->getLocation(),
4238 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004239 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004240 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004241 }
4242
4243 if (!PureVirtualClassDiagSet)
4244 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4245 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004246}
4247
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004248namespace {
John McCall02db245d2010-08-18 09:41:07 +00004249struct AbstractUsageInfo {
4250 Sema &S;
4251 CXXRecordDecl *Record;
4252 CanQualType AbstractType;
4253 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004254
John McCall02db245d2010-08-18 09:41:07 +00004255 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4256 : S(S), Record(Record),
4257 AbstractType(S.Context.getCanonicalType(
4258 S.Context.getTypeDeclType(Record))),
4259 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004260
John McCall02db245d2010-08-18 09:41:07 +00004261 void DiagnoseAbstractType() {
4262 if (Invalid) return;
4263 S.DiagnoseAbstractType(Record);
4264 Invalid = true;
4265 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004266
John McCall02db245d2010-08-18 09:41:07 +00004267 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4268};
4269
4270struct CheckAbstractUsage {
4271 AbstractUsageInfo &Info;
4272 const NamedDecl *Ctx;
4273
4274 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4275 : Info(Info), Ctx(Ctx) {}
4276
4277 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4278 switch (TL.getTypeLocClass()) {
4279#define ABSTRACT_TYPELOC(CLASS, PARENT)
4280#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004281 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004282#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004283 }
John McCall02db245d2010-08-18 09:41:07 +00004284 }
Mike Stump11289f42009-09-09 15:08:12 +00004285
John McCall02db245d2010-08-18 09:41:07 +00004286 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004287 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004288 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4289 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004290 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004291
4292 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004293 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004294 }
John McCall02db245d2010-08-18 09:41:07 +00004295 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004296
John McCall02db245d2010-08-18 09:41:07 +00004297 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4298 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4299 }
Mike Stump11289f42009-09-09 15:08:12 +00004300
John McCall02db245d2010-08-18 09:41:07 +00004301 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4302 // Visit the type parameters from a permissive context.
4303 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4304 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4305 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4306 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4307 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4308 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004309 }
John McCall02db245d2010-08-18 09:41:07 +00004310 }
Mike Stump11289f42009-09-09 15:08:12 +00004311
John McCall02db245d2010-08-18 09:41:07 +00004312 // Visit pointee types from a permissive context.
4313#define CheckPolymorphic(Type) \
4314 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4315 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4316 }
4317 CheckPolymorphic(PointerTypeLoc)
4318 CheckPolymorphic(ReferenceTypeLoc)
4319 CheckPolymorphic(MemberPointerTypeLoc)
4320 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004321 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004322
John McCall02db245d2010-08-18 09:41:07 +00004323 /// Handle all the types we haven't given a more specific
4324 /// implementation for above.
4325 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4326 // Every other kind of type that we haven't called out already
4327 // that has an inner type is either (1) sugar or (2) contains that
4328 // inner type in some way as a subobject.
4329 if (TypeLoc Next = TL.getNextTypeLoc())
4330 return Visit(Next, Sel);
4331
4332 // If there's no inner type and we're in a permissive context,
4333 // don't diagnose.
4334 if (Sel == Sema::AbstractNone) return;
4335
4336 // Check whether the type matches the abstract type.
4337 QualType T = TL.getType();
4338 if (T->isArrayType()) {
4339 Sel = Sema::AbstractArrayType;
4340 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004341 }
John McCall02db245d2010-08-18 09:41:07 +00004342 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4343 if (CT != Info.AbstractType) return;
4344
4345 // It matched; do some magic.
4346 if (Sel == Sema::AbstractArrayType) {
4347 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4348 << T << TL.getSourceRange();
4349 } else {
4350 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4351 << Sel << T << TL.getSourceRange();
4352 }
4353 Info.DiagnoseAbstractType();
4354 }
4355};
4356
4357void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4358 Sema::AbstractDiagSelID Sel) {
4359 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4360}
4361
4362}
4363
4364/// Check for invalid uses of an abstract type in a method declaration.
4365static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4366 CXXMethodDecl *MD) {
4367 // No need to do the check on definitions, which require that
4368 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004369 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004370 return;
4371
4372 // For safety's sake, just ignore it if we don't have type source
4373 // information. This should never happen for non-implicit methods,
4374 // but...
4375 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4376 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4377}
4378
4379/// Check for invalid uses of an abstract type within a class definition.
4380static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4381 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004382 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004383 if (D->isImplicit()) continue;
4384
4385 // Methods and method templates.
4386 if (isa<CXXMethodDecl>(D)) {
4387 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4388 } else if (isa<FunctionTemplateDecl>(D)) {
4389 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4391
4392 // Fields and static variables.
4393 } else if (isa<FieldDecl>(D)) {
4394 FieldDecl *FD = cast<FieldDecl>(D);
4395 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4396 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4397 } else if (isa<VarDecl>(D)) {
4398 VarDecl *VD = cast<VarDecl>(D);
4399 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4400 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4401
4402 // Nested classes and class templates.
4403 } else if (isa<CXXRecordDecl>(D)) {
4404 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4405 } else if (isa<ClassTemplateDecl>(D)) {
4406 CheckAbstractClassUsage(Info,
4407 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4408 }
4409 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004410}
4411
Hans Wennborg853ae942014-05-30 16:59:42 +00004412/// \brief Check class-level dllimport/dllexport attribute.
4413static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4414 Attr *ClassAttr = getDLLAttr(Class);
4415 if (!ClassAttr)
4416 return;
4417
4418 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4419
4420 // Force declaration of implicit members so they can inherit the attribute.
4421 S.ForceDeclarationOfImplicitMembers(Class);
4422
4423 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4424 // seem to be true in practice?
4425
Hans Wennborg853ae942014-05-30 16:59:42 +00004426 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004427 VarDecl *VD = dyn_cast<VarDecl>(Member);
4428 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4429
4430 // Only methods and static fields inherit the attributes.
4431 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004432 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004433
4434 // Don't process deleted methods.
4435 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004436 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004437
Hans Wennborge8ad3832014-06-11 22:44:39 +00004438 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4439 MD->isInlined()) {
4440 // Current MSVC versions don't export the move assignment operators, so
4441 // don't attempt to import them if we have a definition.
4442 continue;
4443 }
4444
Hans Wennborg496524b2014-05-31 02:08:49 +00004445 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4446 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00004447 !MemberAttr->isInherited() && !ClassAttr->isInherited()) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004448 S.Diag(MemberAttr->getLocation(),
4449 diag::err_attribute_dll_member_of_dll_class)
4450 << MemberAttr << ClassAttr;
4451 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4452 Member->setInvalidDecl();
4453 continue;
4454 }
4455 } else {
4456 auto *NewAttr =
4457 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4458 NewAttr->setInherited(true);
4459 Member->addAttr(NewAttr);
4460 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004461
4462 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
4463 if (ClassExported) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004464 if (MD->isUserProvided()) {
4465 // Instantiate non-default methods.
4466 S.MarkFunctionReferenced(Class->getLocation(), MD);
4467 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4468 MD->isCopyAssignmentOperator() ||
4469 MD->isMoveAssignmentOperator()) {
Alp Toker15e62a32014-06-06 12:02:07 +00004470 // Instantiate non-trivial or explicitly defaulted methods, and the
Hans Wennborg853ae942014-05-30 16:59:42 +00004471 // copy assignment / move assignment operators.
4472 S.MarkFunctionReferenced(Class->getLocation(), MD);
4473 // Resolve its exception specification; CodeGen needs it.
4474 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4475 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4476 S.ActOnFinishInlineMethodDef(MD);
4477 }
4478 }
4479 }
4480 }
4481}
4482
Douglas Gregorc99f1552009-12-03 18:33:45 +00004483/// \brief Perform semantic checks on a class definition that has been
4484/// completing, introducing implicitly-declared members, checking for
4485/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004486void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004487 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004488 return;
4489
John McCall02db245d2010-08-18 09:41:07 +00004490 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4491 AbstractUsageInfo Info(*this, Record);
4492 CheckAbstractClassUsage(Info, Record);
4493 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004494
4495 // If this is not an aggregate type and has no user-declared constructor,
4496 // complain about any non-static data members of reference or const scalar
4497 // type, since they will never get initializers.
4498 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004499 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4500 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004501 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004502 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004503 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004504 continue;
4505
Douglas Gregor454a5b62010-04-15 00:00:53 +00004506 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004507 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004508 if (!Complained) {
4509 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4510 << Record->getTagKind() << Record;
4511 Complained = true;
4512 }
4513
4514 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4515 << F->getType()->isReferenceType()
4516 << F->getDeclName();
4517 }
4518 }
4519 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004520
Anders Carlssone771e762011-01-25 18:08:22 +00004521 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004522 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004523
4524 if (Record->getIdentifier()) {
4525 // C++ [class.mem]p13:
4526 // If T is the name of a class, then each of the following shall have a
4527 // name different from T:
4528 // - every member of every anonymous union that is a member of class T.
4529 //
4530 // C++ [class.mem]p14:
4531 // In addition, if class T has a user-declared constructor (12.1), every
4532 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004533 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4534 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4535 ++I) {
4536 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004537 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4538 isa<IndirectFieldDecl>(D)) {
4539 Diag(D->getLocation(), diag::err_member_name_of_class)
4540 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004541 break;
4542 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004543 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004544 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004545
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004546 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004547 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004548 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004549 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4550 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004551 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4552 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4553 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004554
David Majnemera5433082013-10-18 00:33:31 +00004555 if (Record->isAbstract()) {
4556 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4557 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4558 << FA->isSpelledAsSealed();
4559 DiagnoseAbstractType(Record);
4560 }
David Blaikie348df502012-09-21 03:21:07 +00004561 }
4562
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004563 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004564 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004565 // See if a method overloads virtual methods in a base
4566 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004567 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004568 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004569
4570 // Check whether the explicitly-defaulted special members are valid.
4571 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004572 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004573
4574 // For an explicitly defaulted or deleted special member, we defer
4575 // determining triviality until the class is complete. That time is now!
4576 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004577 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004578 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004579 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004580
4581 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004582 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004583 }
4584 }
4585 }
4586 }
4587
4588 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4589 // function that is not a constructor declares that member function to be
4590 // const. [...] The class of which that function is a member shall be
4591 // a literal type.
4592 //
4593 // If the class has virtual bases, any constexpr members will already have
4594 // been diagnosed by the checks performed on the member declaration, so
4595 // suppress this (less useful) diagnostic.
4596 //
4597 // We delay this until we know whether an explicitly-defaulted (or deleted)
4598 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004599 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004600 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004601 for (const auto *M : Record->methods()) {
4602 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004603 switch (Record->getTemplateSpecializationKind()) {
4604 case TSK_ImplicitInstantiation:
4605 case TSK_ExplicitInstantiationDeclaration:
4606 case TSK_ExplicitInstantiationDefinition:
4607 // If a template instantiates to a non-literal type, but its members
4608 // instantiate to constexpr functions, the template is technically
4609 // ill-formed, but we allow it for sanity.
4610 continue;
4611
4612 case TSK_Undeclared:
4613 case TSK_ExplicitSpecialization:
4614 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4615 diag::err_constexpr_method_non_literal);
4616 break;
4617 }
4618
4619 // Only produce one error per class.
4620 break;
4621 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004622 }
4623 }
Sebastian Redl08905022011-02-05 19:23:19 +00004624
John McCall95833f32014-02-27 20:30:49 +00004625 // ms_struct is a request to use the same ABI rules as MSVC. Check
4626 // whether this class uses any C++ features that are implemented
4627 // completely differently in MSVC, and if so, emit a diagnostic.
4628 // That diagnostic defaults to an error, but we allow projects to
4629 // map it down to a warning (or ignore it). It's a fairly common
4630 // practice among users of the ms_struct pragma to mass-annotate
4631 // headers, sweeping up a bunch of types that the project doesn't
4632 // really rely on MSVC-compatible layout for. We must therefore
4633 // support "ms_struct except for C++ stuff" as a secondary ABI.
4634 if (Record->isMsStruct(Context) &&
4635 (Record->isPolymorphic() || Record->getNumBases())) {
4636 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004637 }
4638
Richard Smithc2bc61b2013-03-18 21:12:30 +00004639 // Declare inheriting constructors. We do this eagerly here because:
4640 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004641 // constructors from different classes.
4642 // - The lazy declaration of the other implicit constructors is so as to not
4643 // waste space and performance on classes that are not meant to be
4644 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004645 // have inheriting constructors.
4646 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004647
4648 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004649}
4650
Richard Smith41c35d62013-11-27 03:39:20 +00004651/// Look up the special member function that would be called by a special
4652/// member function for a subobject of class type.
4653///
4654/// \param Class The class type of the subobject.
4655/// \param CSM The kind of special member function.
4656/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4657/// \param ConstRHS True if this is a copy operation with a const object
4658/// on its RHS, that is, if the argument to the outer special member
4659/// function is 'const' and this is not a field marked 'mutable'.
4660static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4661 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4662 unsigned FieldQuals, bool ConstRHS) {
4663 unsigned LHSQuals = 0;
4664 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4665 LHSQuals = FieldQuals;
4666
4667 unsigned RHSQuals = FieldQuals;
4668 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4669 RHSQuals = 0;
4670 else if (ConstRHS)
4671 RHSQuals |= Qualifiers::Const;
4672
4673 return S.LookupSpecialMember(Class, CSM,
4674 RHSQuals & Qualifiers::Const,
4675 RHSQuals & Qualifiers::Volatile,
4676 false,
4677 LHSQuals & Qualifiers::Const,
4678 LHSQuals & Qualifiers::Volatile);
4679}
4680
Richard Smithb5800092012-06-10 05:43:50 +00004681/// Is the special member function which would be selected to perform the
4682/// specified operation on the specified class type a constexpr constructor?
4683static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4684 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004685 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004686 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004687 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004688 if (!SMOR || !SMOR->getMethod())
4689 // A constructor we wouldn't select can't be "involved in initializing"
4690 // anything.
4691 return true;
4692 return SMOR->getMethod()->isConstexpr();
4693}
4694
4695/// Determine whether the specified special member function would be constexpr
4696/// if it were implicitly defined.
4697static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4698 Sema::CXXSpecialMember CSM,
4699 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004700 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004701 return false;
4702
4703 // C++11 [dcl.constexpr]p4:
4704 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004705 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004706 switch (CSM) {
4707 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004708 // Since default constructor lookup is essentially trivial (and cannot
4709 // involve, for instance, template instantiation), we compute whether a
4710 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4711 //
4712 // This is important for performance; we need to know whether the default
4713 // constructor is constexpr to determine whether the type is a literal type.
4714 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4715
Richard Smithb5800092012-06-10 05:43:50 +00004716 case Sema::CXXCopyConstructor:
4717 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004718 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004719 break;
4720
4721 case Sema::CXXCopyAssignment:
4722 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004723 if (!S.getLangOpts().CPlusPlus1y)
4724 return false;
4725 // In C++1y, we need to perform overload resolution.
4726 Ctor = false;
4727 break;
4728
Richard Smithb5800092012-06-10 05:43:50 +00004729 case Sema::CXXDestructor:
4730 case Sema::CXXInvalid:
4731 return false;
4732 }
4733
4734 // -- if the class is a non-empty union, or for each non-empty anonymous
4735 // union member of a non-union class, exactly one non-static data member
4736 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004737 //
4738 // If we squint, this is guaranteed, since exactly one non-static data member
4739 // will be initialized (if the constructor isn't deleted), we just don't know
4740 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004741 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004742 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004743
4744 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004745 if (Ctor && ClassDecl->getNumVBases())
4746 return false;
4747
4748 // C++1y [class.copy]p26:
4749 // -- [the class] is a literal type, and
4750 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004751 return false;
4752
4753 // -- every constructor involved in initializing [...] base class
4754 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004755 // -- the assignment operator selected to copy/move each direct base
4756 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004757 for (const auto &B : ClassDecl->bases()) {
4758 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004759 if (!BaseType) continue;
4760
4761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004762 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004763 return false;
4764 }
4765
4766 // -- every constructor involved in initializing non-static data members
4767 // [...] shall be a constexpr constructor;
4768 // -- every non-static data member and base class sub-object shall be
4769 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004770 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004771 // thereof), the assignment operator selected to copy/move that member is
4772 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004773 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004774 if (F->isInvalidDecl())
4775 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004776 QualType BaseType = S.Context.getBaseElementType(F->getType());
4777 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004778 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004779 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4780 BaseType.getCVRQualifiers(),
4781 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004782 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004783 }
4784 }
4785
4786 // All OK, it's constexpr!
4787 return true;
4788}
4789
Richard Smithd3b5c9082012-07-27 04:22:15 +00004790static Sema::ImplicitExceptionSpecification
4791computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4792 switch (S.getSpecialMember(MD)) {
4793 case Sema::CXXDefaultConstructor:
4794 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4795 case Sema::CXXCopyConstructor:
4796 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4797 case Sema::CXXCopyAssignment:
4798 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4799 case Sema::CXXMoveConstructor:
4800 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4801 case Sema::CXXMoveAssignment:
4802 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4803 case Sema::CXXDestructor:
4804 return S.ComputeDefaultedDtorExceptionSpec(MD);
4805 case Sema::CXXInvalid:
4806 break;
4807 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004808 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4809 "only special members have implicit exception specs");
4810 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004811}
4812
Reid Kleckner78af0702013-08-27 23:08:25 +00004813static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4814 CXXMethodDecl *MD) {
4815 FunctionProtoType::ExtProtoInfo EPI;
4816
4817 // Build an exception specification pointing back at this member.
4818 EPI.ExceptionSpecType = EST_Unevaluated;
4819 EPI.ExceptionSpecDecl = MD;
4820
4821 // Set the calling convention to the default for C++ instance methods.
4822 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4823 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4824 /*IsCXXMethod=*/true));
4825 return EPI;
4826}
4827
Richard Smithd3b5c9082012-07-27 04:22:15 +00004828void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4829 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4830 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4831 return;
4832
Richard Smith7f782272012-07-30 23:48:14 +00004833 // Evaluate the exception specification.
4834 ImplicitExceptionSpecification ExceptSpec =
4835 computeImplicitExceptionSpec(*this, Loc, MD);
4836
Richard Smith564417a2014-03-20 21:47:22 +00004837 FunctionProtoType::ExtProtoInfo EPI;
4838 ExceptSpec.getEPI(EPI);
4839
Richard Smith7f782272012-07-30 23:48:14 +00004840 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004841 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004842
4843 // A user-provided destructor can be defined outside the class. When that
4844 // happens, be sure to update the exception specification on both
4845 // declarations.
4846 const FunctionProtoType *CanonicalFPT =
4847 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4848 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004849 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004850}
4851
Richard Smithb9e90b12012-05-15 04:39:51 +00004852void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4853 CXXRecordDecl *RD = MD->getParent();
4854 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004855
Richard Smithb9e90b12012-05-15 04:39:51 +00004856 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4857 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004858
4859 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004860 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004861 bool First = MD == MD->getCanonicalDecl();
4862
4863 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004864
4865 // C++11 [dcl.fct.def.default]p1:
4866 // A function that is explicitly defaulted shall
4867 // -- be a special member function (checked elsewhere),
4868 // -- have the same type (except for ref-qualifiers, and except that a
4869 // copy operation can take a non-const reference) as an implicit
4870 // declaration, and
4871 // -- not have default arguments.
4872 unsigned ExpectedParams = 1;
4873 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4874 ExpectedParams = 0;
4875 if (MD->getNumParams() != ExpectedParams) {
4876 // This also checks for default arguments: a copy or move constructor with a
4877 // default argument is classified as a default constructor, and assignment
4878 // operations and destructors can't have default arguments.
4879 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4880 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004881 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004882 } else if (MD->isVariadic()) {
4883 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4884 << CSM << MD->getSourceRange();
4885 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004886 }
4887
Richard Smithb9e90b12012-05-15 04:39:51 +00004888 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004889
Richard Smithb5800092012-06-10 05:43:50 +00004890 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004891 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004892 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004893 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004894 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004895
Richard Smithb9e90b12012-05-15 04:39:51 +00004896 QualType ReturnType = Context.VoidTy;
4897 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4898 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004899 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004900 QualType ExpectedReturnType =
4901 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4902 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4903 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4904 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4905 HadError = true;
4906 }
4907
4908 // A defaulted special member cannot have cv-qualifiers.
4909 if (Type->getTypeQuals()) {
4910 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004911 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004912 HadError = true;
4913 }
4914 }
4915
4916 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004917 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004918 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004919 if (ExpectedParams && ArgType->isReferenceType()) {
4920 // Argument must be reference to possibly-const T.
4921 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004922 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004923
4924 if (ReferentType.isVolatileQualified()) {
4925 Diag(MD->getLocation(),
4926 diag::err_defaulted_special_member_volatile_param) << CSM;
4927 HadError = true;
4928 }
4929
Richard Smithb5800092012-06-10 05:43:50 +00004930 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004931 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4932 Diag(MD->getLocation(),
4933 diag::err_defaulted_special_member_copy_const_param)
4934 << (CSM == CXXCopyAssignment);
4935 // FIXME: Explain why this special member can't be const.
4936 } else {
4937 Diag(MD->getLocation(),
4938 diag::err_defaulted_special_member_move_const_param)
4939 << (CSM == CXXMoveAssignment);
4940 }
4941 HadError = true;
4942 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004943 } else if (ExpectedParams) {
4944 // A copy assignment operator can take its argument by value, but a
4945 // defaulted one cannot.
4946 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004947 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004948 HadError = true;
4949 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004950
Richard Smithcc36f692011-12-22 02:22:31 +00004951 // C++11 [dcl.fct.def.default]p2:
4952 // An explicitly-defaulted function may be declared constexpr only if it
4953 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004954 // Do not apply this rule to members of class templates, since core issue 1358
4955 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004956 // functions which cannot be constexpr (for non-constructors in C++11 and for
4957 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004958 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4959 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004960 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4961 : isa<CXXConstructorDecl>(MD)) &&
4962 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004963 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4964 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004965 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004966 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004967 }
Richard Smithbd305122012-12-11 01:14:52 +00004968
Richard Smithcc36f692011-12-22 02:22:31 +00004969 // and may have an explicit exception-specification only if it is compatible
4970 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004971 if (Type->hasExceptionSpec()) {
4972 // Delay the check if this is the first declaration of the special member,
4973 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004974 if (First) {
4975 // If the exception specification needs to be instantiated, do so now,
4976 // before we clobber it with an EST_Unevaluated specification below.
4977 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4978 InstantiateExceptionSpec(MD->getLocStart(), MD);
4979 Type = MD->getType()->getAs<FunctionProtoType>();
4980 }
Richard Smithbd305122012-12-11 01:14:52 +00004981 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004982 } else
Richard Smithbd305122012-12-11 01:14:52 +00004983 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4984 }
Richard Smithcc36f692011-12-22 02:22:31 +00004985
4986 // If a function is explicitly defaulted on its first declaration,
4987 if (First) {
4988 // -- it is implicitly considered to be constexpr if the implicit
4989 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004990 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004991
Richard Smithb9e90b12012-05-15 04:39:51 +00004992 // -- it is implicitly considered to have the same exception-specification
4993 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004994 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4995 EPI.ExceptionSpecType = EST_Unevaluated;
4996 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004997 MD->setType(Context.getFunctionType(ReturnType,
4998 ArrayRef<QualType>(&ArgType,
4999 ExpectedParams),
5000 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005001 }
5002
Richard Smithb9e90b12012-05-15 04:39:51 +00005003 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005004 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005005 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005006 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005007 // C++11 [dcl.fct.def.default]p4:
5008 // [For a] user-provided explicitly-defaulted function [...] if such a
5009 // function is implicitly defined as deleted, the program is ill-formed.
5010 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005011 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005012 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005013 }
5014 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005015
Richard Smithb9e90b12012-05-15 04:39:51 +00005016 if (HadError)
5017 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005018}
5019
Richard Smithbd305122012-12-11 01:14:52 +00005020/// Check whether the exception specification provided for an
5021/// explicitly-defaulted special member matches the exception specification
5022/// that would have been generated for an implicit special member, per
5023/// C++11 [dcl.fct.def.default]p2.
5024void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5025 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5026 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005027 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5028 /*IsCXXMethod=*/true);
5029 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00005030 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
5031 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005032 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005033
5034 // Ensure that it matches.
5035 CheckEquivalentExceptionSpec(
5036 PDiag(diag::err_incorrect_defaulted_exception_spec)
5037 << getSpecialMember(MD), PDiag(),
5038 ImplicitType, SourceLocation(),
5039 SpecifiedType, MD->getLocation());
5040}
5041
Alp Tokerae3a9442013-10-18 05:54:19 +00005042void Sema::CheckDelayedMemberExceptionSpecs() {
5043 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5044 2> Checks;
5045 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005046
Alp Tokerae3a9442013-10-18 05:54:19 +00005047 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5048 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5049
5050 // Perform any deferred checking of exception specifications for virtual
5051 // destructors.
5052 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5053 const CXXDestructorDecl *Dtor = Checks[i].first;
5054 assert(!Dtor->getParent()->isDependentType() &&
5055 "Should not ever add destructors of templates into the list.");
5056 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5057 }
5058
5059 // Check that any explicitly-defaulted methods have exception specifications
5060 // compatible with their implicit exception specifications.
5061 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5062 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5063 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005064}
5065
Richard Smithd951a1d2012-02-18 02:02:13 +00005066namespace {
5067struct SpecialMemberDeletionInfo {
5068 Sema &S;
5069 CXXMethodDecl *MD;
5070 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005071 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005072
5073 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005074 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005075 SourceLocation Loc;
5076
5077 bool AllFieldsAreConst;
5078
5079 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005080 Sema::CXXSpecialMember CSM, bool Diagnose)
5081 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005082 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005083 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005084 AllFieldsAreConst(true) {
5085 switch (CSM) {
5086 case Sema::CXXDefaultConstructor:
5087 case Sema::CXXCopyConstructor:
5088 IsConstructor = true;
5089 break;
5090 case Sema::CXXMoveConstructor:
5091 IsConstructor = true;
5092 IsMove = true;
5093 break;
5094 case Sema::CXXCopyAssignment:
5095 IsAssignment = true;
5096 break;
5097 case Sema::CXXMoveAssignment:
5098 IsAssignment = true;
5099 IsMove = true;
5100 break;
5101 case Sema::CXXDestructor:
5102 break;
5103 case Sema::CXXInvalid:
5104 llvm_unreachable("invalid special member kind");
5105 }
5106
5107 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005108 if (const ReferenceType *RT =
5109 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5110 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005111 }
5112 }
5113
5114 bool inUnion() const { return MD->getParent()->isUnion(); }
5115
5116 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005117 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005118 unsigned Quals, bool IsMutable) {
5119 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5120 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005121 }
5122
Richard Smith852265f2012-03-30 20:53:28 +00005123 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005124
Richard Smith852265f2012-03-30 20:53:28 +00005125 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005126 bool shouldDeleteForField(FieldDecl *FD);
5127 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005128
Richard Smithaf136f82012-07-18 03:51:16 +00005129 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5130 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005131 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5132 Sema::SpecialMemberOverloadResult *SMOR,
5133 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005134
5135 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005136};
5137}
5138
John McCalld4274212012-04-09 20:53:23 +00005139/// Is the given special member inaccessible when used on the given
5140/// sub-object.
5141bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5142 CXXMethodDecl *target) {
5143 /// If we're operating on a base class, the object type is the
5144 /// type of this special member.
5145 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005146 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005147 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5148 objectTy = S.Context.getTypeDeclType(MD->getParent());
5149 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5150
5151 // If we're operating on a field, the object type is the type of the field.
5152 } else {
5153 objectTy = S.Context.getTypeDeclType(target->getParent());
5154 }
5155
5156 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5157}
5158
Richard Smith852265f2012-03-30 20:53:28 +00005159/// Check whether we should delete a special member due to the implicit
5160/// definition containing a call to a special member of a subobject.
5161bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5162 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5163 bool IsDtorCallInCtor) {
5164 CXXMethodDecl *Decl = SMOR->getMethod();
5165 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5166
5167 int DiagKind = -1;
5168
5169 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5170 DiagKind = !Decl ? 0 : 1;
5171 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5172 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005173 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005174 DiagKind = 3;
5175 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5176 !Decl->isTrivial()) {
5177 // A member of a union must have a trivial corresponding special member.
5178 // As a weird special case, a destructor call from a union's constructor
5179 // must be accessible and non-deleted, but need not be trivial. Such a
5180 // destructor is never actually called, but is semantically checked as
5181 // if it were.
5182 DiagKind = 4;
5183 }
5184
5185 if (DiagKind == -1)
5186 return false;
5187
5188 if (Diagnose) {
5189 if (Field) {
5190 S.Diag(Field->getLocation(),
5191 diag::note_deleted_special_member_class_subobject)
5192 << CSM << MD->getParent() << /*IsField*/true
5193 << Field << DiagKind << IsDtorCallInCtor;
5194 } else {
5195 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5196 S.Diag(Base->getLocStart(),
5197 diag::note_deleted_special_member_class_subobject)
5198 << CSM << MD->getParent() << /*IsField*/false
5199 << Base->getType() << DiagKind << IsDtorCallInCtor;
5200 }
5201
5202 if (DiagKind == 1)
5203 S.NoteDeletedFunction(Decl);
5204 // FIXME: Explain inaccessibility if DiagKind == 3.
5205 }
5206
5207 return true;
5208}
5209
Richard Smith921bd202012-02-26 09:11:52 +00005210/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005211/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005212bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005213 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005214 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005215 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005216
5217 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005218 // -- any direct or virtual base class, or non-static data member with no
5219 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005220 // either M has no default constructor or overload resolution as applied
5221 // to M's default constructor results in an ambiguity or in a function
5222 // that is deleted or inaccessible
5223 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5224 // -- a direct or virtual base class B that cannot be copied/moved because
5225 // overload resolution, as applied to B's corresponding special member,
5226 // results in an ambiguity or a function that is deleted or inaccessible
5227 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005228 // C++11 [class.dtor]p5:
5229 // -- any direct or virtual base class [...] has a type with a destructor
5230 // that is deleted or inaccessible
5231 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005232 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005233 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5234 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005235 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005236
Richard Smith852265f2012-03-30 20:53:28 +00005237 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5238 // -- any direct or virtual base class or non-static data member has a
5239 // type with a destructor that is deleted or inaccessible
5240 if (IsConstructor) {
5241 Sema::SpecialMemberOverloadResult *SMOR =
5242 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5243 false, false, false, false, false);
5244 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5245 return true;
5246 }
5247
Richard Smith921bd202012-02-26 09:11:52 +00005248 return false;
5249}
5250
5251/// Check whether we should delete a special member function due to the class
5252/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005253bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005254 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005255 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005256}
5257
5258/// Check whether we should delete a special member function due to the class
5259/// having a particular non-static data member.
5260bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5261 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5262 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5263
5264 if (CSM == Sema::CXXDefaultConstructor) {
5265 // For a default constructor, all references must be initialized in-class
5266 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005267 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5268 if (Diagnose)
5269 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5270 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005271 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005272 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005273 // C++11 [class.ctor]p5: any non-variant non-static data member of
5274 // const-qualified type (or array thereof) with no
5275 // brace-or-equal-initializer does not have a user-provided default
5276 // constructor.
5277 if (!inUnion() && FieldType.isConstQualified() &&
5278 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005279 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5280 if (Diagnose)
5281 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005282 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005283 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005284 }
5285
5286 if (inUnion() && !FieldType.isConstQualified())
5287 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005288 } else if (CSM == Sema::CXXCopyConstructor) {
5289 // For a copy constructor, data members must not be of rvalue reference
5290 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005291 if (FieldType->isRValueReferenceType()) {
5292 if (Diagnose)
5293 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5294 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005295 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005296 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005297 } else if (IsAssignment) {
5298 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005299 if (FieldType->isReferenceType()) {
5300 if (Diagnose)
5301 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5302 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005303 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005304 }
5305 if (!FieldRecord && FieldType.isConstQualified()) {
5306 // C++11 [class.copy]p23:
5307 // -- a non-static data member of const non-class type (or array thereof)
5308 if (Diagnose)
5309 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005310 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005311 return true;
5312 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005313 }
5314
5315 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005316 // Some additional restrictions exist on the variant members.
5317 if (!inUnion() && FieldRecord->isUnion() &&
5318 FieldRecord->isAnonymousStructOrUnion()) {
5319 bool AllVariantFieldsAreConst = true;
5320
Richard Smith5704fe82012-03-29 19:00:10 +00005321 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005322 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005323 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005324
5325 if (!UnionFieldType.isConstQualified())
5326 AllVariantFieldsAreConst = false;
5327
Richard Smith921bd202012-02-26 09:11:52 +00005328 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5329 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005330 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005331 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005332 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005333 }
5334
5335 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005336 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005337 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005338 if (Diagnose)
5339 S.Diag(FieldRecord->getLocation(),
5340 diag::note_deleted_default_ctor_all_const)
5341 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005342 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005343 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005344
Richard Smith5704fe82012-03-29 19:00:10 +00005345 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005346 // This is technically non-conformant, but sanity demands it.
5347 return false;
5348 }
5349
Richard Smithaf136f82012-07-18 03:51:16 +00005350 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5351 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005352 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005353 }
5354
5355 return false;
5356}
5357
5358/// C++11 [class.ctor] p5:
5359/// A defaulted default constructor for a class X is defined as deleted if
5360/// X is a union and all of its variant members are of const-qualified type.
5361bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005362 // This is a silly definition, because it gives an empty union a deleted
5363 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005364 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005365 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005366 if (Diagnose)
5367 S.Diag(MD->getParent()->getLocation(),
5368 diag::note_deleted_default_ctor_all_const)
5369 << MD->getParent() << /*not anonymous union*/0;
5370 return true;
5371 }
5372 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005373}
5374
5375/// Determine whether a defaulted special member function should be defined as
5376/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5377/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005378bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5379 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005380 if (MD->isInvalidDecl())
5381 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005382 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005383 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005384 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005385 return false;
5386
Richard Smithd951a1d2012-02-18 02:02:13 +00005387 // C++11 [expr.lambda.prim]p19:
5388 // The closure type associated with a lambda-expression has a
5389 // deleted (8.4.3) default constructor and a deleted copy
5390 // assignment operator.
5391 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005392 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5393 if (Diagnose)
5394 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005395 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005396 }
5397
Richard Smith6f1e2c62012-04-02 20:59:25 +00005398 // For an anonymous struct or union, the copy and assignment special members
5399 // will never be used, so skip the check. For an anonymous union declared at
5400 // namespace scope, the constructor and destructor are used.
5401 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5402 RD->isAnonymousStructOrUnion())
5403 return false;
5404
Richard Smith852265f2012-03-30 20:53:28 +00005405 // C++11 [class.copy]p7, p18:
5406 // If the class definition declares a move constructor or move assignment
5407 // operator, an implicitly declared copy constructor or copy assignment
5408 // operator is defined as deleted.
5409 if (MD->isImplicit() &&
5410 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005411 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005412
5413 // In Microsoft mode, a user-declared move only causes the deletion of the
5414 // corresponding copy operation, not both copy operations.
5415 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005416 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005417 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005418
5419 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005420 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005421 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005422 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005423 break;
5424 }
5425 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005426 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005427 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005428 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005429 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005430
5431 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005432 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005433 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005434 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005435 break;
5436 }
5437 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005438 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005439 }
5440
5441 if (UserDeclaredMove) {
5442 Diag(UserDeclaredMove->getLocation(),
5443 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005444 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005445 << UserDeclaredMove->isMoveAssignmentOperator();
5446 return true;
5447 }
5448 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005449
Richard Smith6f1e2c62012-04-02 20:59:25 +00005450 // Do access control from the special member function
5451 ContextRAII MethodContext(*this, MD);
5452
Richard Smith921bd202012-02-26 09:11:52 +00005453 // C++11 [class.dtor]p5:
5454 // -- for a virtual destructor, lookup of the non-array deallocation function
5455 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005456 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005457 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005458 DeclarationName Name =
5459 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5460 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005461 OperatorDelete, false)) {
5462 if (Diagnose)
5463 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005464 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005465 }
Richard Smith921bd202012-02-26 09:11:52 +00005466 }
5467
Richard Smith852265f2012-03-30 20:53:28 +00005468 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005469
Aaron Ballman574705e2014-03-13 15:41:46 +00005470 for (auto &BI : RD->bases())
5471 if (!BI.isVirtual() &&
5472 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005473 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005474
Richard Smithd1627032013-07-22 18:06:23 +00005475 // Per DR1611, do not consider virtual bases of constructors of abstract
5476 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005477 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005478 for (auto &BI : RD->vbases())
5479 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005480 return true;
5481 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005482
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005483 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005484 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005485 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005486 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005487
Richard Smithd951a1d2012-02-18 02:02:13 +00005488 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005489 return true;
5490
5491 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005492}
5493
Richard Smith92f241f2012-12-08 02:53:02 +00005494/// Perform lookup for a special member of the specified kind, and determine
5495/// whether it is trivial. If the triviality can be determined without the
5496/// lookup, skip it. This is intended for use when determining whether a
5497/// special member of a containing object is trivial, and thus does not ever
5498/// perform overload resolution for default constructors.
5499///
5500/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5501/// member that was most likely to be intended to be trivial, if any.
5502static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5503 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005504 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005505 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005506 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005507
5508 switch (CSM) {
5509 case Sema::CXXInvalid:
5510 llvm_unreachable("not a special member");
5511
5512 case Sema::CXXDefaultConstructor:
5513 // C++11 [class.ctor]p5:
5514 // A default constructor is trivial if:
5515 // - all the [direct subobjects] have trivial default constructors
5516 //
5517 // Note, no overload resolution is performed in this case.
5518 if (RD->hasTrivialDefaultConstructor())
5519 return true;
5520
5521 if (Selected) {
5522 // If there's a default constructor which could have been trivial, dig it
5523 // out. Otherwise, if there's any user-provided default constructor, point
5524 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005525 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005526 if (RD->needsImplicitDefaultConstructor())
5527 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005528 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005529 if (!CI->isDefaultConstructor())
5530 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005531 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005532 if (!DefCtor->isUserProvided())
5533 break;
5534 }
5535
5536 *Selected = DefCtor;
5537 }
5538
5539 return false;
5540
5541 case Sema::CXXDestructor:
5542 // C++11 [class.dtor]p5:
5543 // A destructor is trivial if:
5544 // - all the direct [subobjects] have trivial destructors
5545 if (RD->hasTrivialDestructor())
5546 return true;
5547
5548 if (Selected) {
5549 if (RD->needsImplicitDestructor())
5550 S.DeclareImplicitDestructor(RD);
5551 *Selected = RD->getDestructor();
5552 }
5553
5554 return false;
5555
5556 case Sema::CXXCopyConstructor:
5557 // C++11 [class.copy]p12:
5558 // A copy constructor is trivial if:
5559 // - the constructor selected to copy each direct [subobject] is trivial
5560 if (RD->hasTrivialCopyConstructor()) {
5561 if (Quals == Qualifiers::Const)
5562 // We must either select the trivial copy constructor or reach an
5563 // ambiguity; no need to actually perform overload resolution.
5564 return true;
5565 } else if (!Selected) {
5566 return false;
5567 }
5568 // In C++98, we are not supposed to perform overload resolution here, but we
5569 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5570 // cases like B as having a non-trivial copy constructor:
5571 // struct A { template<typename T> A(T&); };
5572 // struct B { mutable A a; };
5573 goto NeedOverloadResolution;
5574
5575 case Sema::CXXCopyAssignment:
5576 // C++11 [class.copy]p25:
5577 // A copy assignment operator is trivial if:
5578 // - the assignment operator selected to copy each direct [subobject] is
5579 // trivial
5580 if (RD->hasTrivialCopyAssignment()) {
5581 if (Quals == Qualifiers::Const)
5582 return true;
5583 } else if (!Selected) {
5584 return false;
5585 }
5586 // In C++98, we are not supposed to perform overload resolution here, but we
5587 // treat that as a language defect.
5588 goto NeedOverloadResolution;
5589
5590 case Sema::CXXMoveConstructor:
5591 case Sema::CXXMoveAssignment:
5592 NeedOverloadResolution:
5593 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005594 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005595
5596 // The standard doesn't describe how to behave if the lookup is ambiguous.
5597 // We treat it as not making the member non-trivial, just like the standard
5598 // mandates for the default constructor. This should rarely matter, because
5599 // the member will also be deleted.
5600 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5601 return true;
5602
5603 if (!SMOR->getMethod()) {
5604 assert(SMOR->getKind() ==
5605 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5606 return false;
5607 }
5608
5609 // We deliberately don't check if we found a deleted special member. We're
5610 // not supposed to!
5611 if (Selected)
5612 *Selected = SMOR->getMethod();
5613 return SMOR->getMethod()->isTrivial();
5614 }
5615
5616 llvm_unreachable("unknown special method kind");
5617}
5618
Benjamin Kramer3e350262013-02-15 12:30:38 +00005619static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005620 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005621 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005622 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005623
5624 // Look for constructor templates.
5625 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5626 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5627 if (CXXConstructorDecl *CD =
5628 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5629 return CD;
5630 }
5631
Craig Topperc3ec1492014-05-26 06:22:03 +00005632 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005633}
5634
5635/// The kind of subobject we are checking for triviality. The values of this
5636/// enumeration are used in diagnostics.
5637enum TrivialSubobjectKind {
5638 /// The subobject is a base class.
5639 TSK_BaseClass,
5640 /// The subobject is a non-static data member.
5641 TSK_Field,
5642 /// The object is actually the complete object.
5643 TSK_CompleteObject
5644};
5645
5646/// Check whether the special member selected for a given type would be trivial.
5647static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005648 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005649 Sema::CXXSpecialMember CSM,
5650 TrivialSubobjectKind Kind,
5651 bool Diagnose) {
5652 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5653 if (!SubRD)
5654 return true;
5655
5656 CXXMethodDecl *Selected;
5657 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005658 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005659 return true;
5660
5661 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005662 if (ConstRHS)
5663 SubType.addConst();
5664
Richard Smith92f241f2012-12-08 02:53:02 +00005665 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5666 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5667 << Kind << SubType.getUnqualifiedType();
5668 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5669 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5670 } else if (!Selected)
5671 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5672 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5673 else if (Selected->isUserProvided()) {
5674 if (Kind == TSK_CompleteObject)
5675 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5676 << Kind << SubType.getUnqualifiedType() << CSM;
5677 else {
5678 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5679 << Kind << SubType.getUnqualifiedType() << CSM;
5680 S.Diag(Selected->getLocation(), diag::note_declared_at);
5681 }
5682 } else {
5683 if (Kind != TSK_CompleteObject)
5684 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5685 << Kind << SubType.getUnqualifiedType() << CSM;
5686
5687 // Explain why the defaulted or deleted special member isn't trivial.
5688 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5689 }
5690 }
5691
5692 return false;
5693}
5694
5695/// Check whether the members of a class type allow a special member to be
5696/// trivial.
5697static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5698 Sema::CXXSpecialMember CSM,
5699 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005700 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005701 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5702 continue;
5703
5704 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5705
5706 // Pretend anonymous struct or union members are members of this class.
5707 if (FI->isAnonymousStructOrUnion()) {
5708 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5709 CSM, ConstArg, Diagnose))
5710 return false;
5711 continue;
5712 }
5713
5714 // C++11 [class.ctor]p5:
5715 // A default constructor is trivial if [...]
5716 // -- no non-static data member of its class has a
5717 // brace-or-equal-initializer
5718 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5719 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005720 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005721 return false;
5722 }
5723
5724 // Objective C ARC 4.3.5:
5725 // [...] nontrivally ownership-qualified types are [...] not trivially
5726 // default constructible, copy constructible, move constructible, copy
5727 // assignable, move assignable, or destructible [...]
5728 if (S.getLangOpts().ObjCAutoRefCount &&
5729 FieldType.hasNonTrivialObjCLifetime()) {
5730 if (Diagnose)
5731 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5732 << RD << FieldType.getObjCLifetime();
5733 return false;
5734 }
5735
Richard Smith41c35d62013-11-27 03:39:20 +00005736 bool ConstRHS = ConstArg && !FI->isMutable();
5737 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5738 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005739 return false;
5740 }
5741
5742 return true;
5743}
5744
5745/// Diagnose why the specified class does not have a trivial special member of
5746/// the given kind.
5747void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5748 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005749
Richard Smith41c35d62013-11-27 03:39:20 +00005750 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5751 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005752 TSK_CompleteObject, /*Diagnose*/true);
5753}
5754
5755/// Determine whether a defaulted or deleted special member function is trivial,
5756/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5757/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5758bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5759 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005760 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5761
5762 CXXRecordDecl *RD = MD->getParent();
5763
5764 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005765
Richard Smith2002bfe2013-11-04 02:02:27 +00005766 // C++11 [class.copy]p12, p25: [DR1593]
5767 // A [special member] is trivial if [...] its parameter-type-list is
5768 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005769 switch (CSM) {
5770 case CXXDefaultConstructor:
5771 case CXXDestructor:
5772 // Trivial default constructors and destructors cannot have parameters.
5773 break;
5774
5775 case CXXCopyConstructor:
5776 case CXXCopyAssignment: {
5777 // Trivial copy operations always have const, non-volatile parameter types.
5778 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005779 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005780 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5781 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5782 if (Diagnose)
5783 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5784 << Param0->getSourceRange() << Param0->getType()
5785 << Context.getLValueReferenceType(
5786 Context.getRecordType(RD).withConst());
5787 return false;
5788 }
5789 break;
5790 }
5791
5792 case CXXMoveConstructor:
5793 case CXXMoveAssignment: {
5794 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005795 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005796 const RValueReferenceType *RT =
5797 Param0->getType()->getAs<RValueReferenceType>();
5798 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5799 if (Diagnose)
5800 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5801 << Param0->getSourceRange() << Param0->getType()
5802 << Context.getRValueReferenceType(Context.getRecordType(RD));
5803 return false;
5804 }
5805 break;
5806 }
5807
5808 case CXXInvalid:
5809 llvm_unreachable("not a special member");
5810 }
5811
Richard Smith92f241f2012-12-08 02:53:02 +00005812 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5813 if (Diagnose)
5814 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5815 diag::note_nontrivial_default_arg)
5816 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5817 return false;
5818 }
5819 if (MD->isVariadic()) {
5820 if (Diagnose)
5821 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5822 return false;
5823 }
5824
5825 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5826 // A copy/move [constructor or assignment operator] is trivial if
5827 // -- the [member] selected to copy/move each direct base class subobject
5828 // is trivial
5829 //
5830 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5831 // A [default constructor or destructor] is trivial if
5832 // -- all the direct base classes have trivial [default constructors or
5833 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005834 for (const auto &BI : RD->bases())
5835 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005836 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005837 return false;
5838
5839 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5840 // A copy/move [constructor or assignment operator] for a class X is
5841 // trivial if
5842 // -- for each non-static data member of X that is of class type (or array
5843 // thereof), the constructor selected to copy/move that member is
5844 // trivial
5845 //
5846 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5847 // A [default constructor or destructor] is trivial if
5848 // -- for all of the non-static data members of its class that are of class
5849 // type (or array thereof), each such class has a trivial [default
5850 // constructor or destructor]
5851 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5852 return false;
5853
5854 // C++11 [class.dtor]p5:
5855 // A destructor is trivial if [...]
5856 // -- the destructor is not virtual
5857 if (CSM == CXXDestructor && MD->isVirtual()) {
5858 if (Diagnose)
5859 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5860 return false;
5861 }
5862
5863 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5864 // A [special member] for class X is trivial if [...]
5865 // -- class X has no virtual functions and no virtual base classes
5866 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5867 if (!Diagnose)
5868 return false;
5869
5870 if (RD->getNumVBases()) {
5871 // Check for virtual bases. We already know that the corresponding
5872 // member in all bases is trivial, so vbases must all be direct.
5873 CXXBaseSpecifier &BS = *RD->vbases_begin();
5874 assert(BS.isVirtual());
5875 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5876 return false;
5877 }
5878
5879 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005880 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005881 if (MI->isVirtual()) {
5882 SourceLocation MLoc = MI->getLocStart();
5883 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5884 return false;
5885 }
5886 }
5887
5888 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5889 }
5890
5891 // Looks like it's trivial!
5892 return true;
5893}
5894
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005895/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005896namespace {
5897 struct FindHiddenVirtualMethodData {
5898 Sema *S;
5899 CXXMethodDecl *Method;
5900 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005901 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005902 };
5903}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005904
David Blaikie282c92a2012-10-19 00:53:08 +00005905/// \brief Check whether any most overriden method from MD in Methods
5906static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5907 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5908 if (MD->size_overridden_methods() == 0)
5909 return Methods.count(MD->getCanonicalDecl());
5910 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5911 E = MD->end_overridden_methods();
5912 I != E; ++I)
5913 if (CheckMostOverridenMethods(*I, Methods))
5914 return true;
5915 return false;
5916}
5917
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005918/// \brief Member lookup function that determines whether a given C++
5919/// method overloads virtual methods in a base class without overriding any,
5920/// to be used with CXXRecordDecl::lookupInBases().
5921static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5922 CXXBasePath &Path,
5923 void *UserData) {
5924 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5925
5926 FindHiddenVirtualMethodData &Data
5927 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5928
5929 DeclarationName Name = Data.Method->getDeclName();
5930 assert(Name.getNameKind() == DeclarationName::Identifier);
5931
5932 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005933 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005934 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005935 !Path.Decls.empty();
5936 Path.Decls = Path.Decls.slice(1)) {
5937 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005938 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005939 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005940 foundSameNameMethod = true;
5941 // Interested only in hidden virtual methods.
5942 if (!MD->isVirtual())
5943 continue;
5944 // If the method we are checking overrides a method from its base
5945 // don't warn about the other overloaded methods.
5946 if (!Data.S->IsOverload(Data.Method, MD, false))
5947 return true;
5948 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005949 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005950 overloadedMethods.push_back(MD);
5951 }
5952 }
5953
5954 if (foundSameNameMethod)
5955 Data.OverloadedMethods.append(overloadedMethods.begin(),
5956 overloadedMethods.end());
5957 return foundSameNameMethod;
5958}
5959
David Blaikie282c92a2012-10-19 00:53:08 +00005960/// \brief Add the most overriden methods from MD to Methods
5961static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5962 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5963 if (MD->size_overridden_methods() == 0)
5964 Methods.insert(MD->getCanonicalDecl());
5965 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5966 E = MD->end_overridden_methods();
5967 I != E; ++I)
5968 AddMostOverridenMethods(*I, Methods);
5969}
5970
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005971/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005972/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005973void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5974 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005975 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005976 return;
5977
5978 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5979 /*bool RecordPaths=*/false,
5980 /*bool DetectVirtual=*/false);
5981 FindHiddenVirtualMethodData Data;
5982 Data.Method = MD;
5983 Data.S = this;
5984
5985 // Keep the base methods that were overriden or introduced in the subclass
5986 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005987 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005988 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5989 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5990 NamedDecl *ND = *I;
5991 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005992 ND = shad->getTargetDecl();
5993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5994 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005995 }
5996
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005997 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5998 OverloadedMethods = Data.OverloadedMethods;
5999}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006000
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006001void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6002 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6003 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6004 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6005 PartialDiagnostic PD = PDiag(
6006 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6007 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6008 Diag(overloadedMD->getLocation(), PD);
6009 }
6010}
6011
6012/// \brief Diagnose methods which overload virtual methods in a base class
6013/// without overriding any.
6014void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6015 if (MD->isInvalidDecl())
6016 return;
6017
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006018 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006019 return;
6020
6021 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6022 FindHiddenVirtualMethods(MD, OverloadedMethods);
6023 if (!OverloadedMethods.empty()) {
6024 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6025 << MD << (OverloadedMethods.size() > 1);
6026
6027 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006028 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006029}
6030
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006031void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006032 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006033 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006034 SourceLocation RBrac,
6035 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006036 if (!TagDecl)
6037 return;
Mike Stump11289f42009-09-09 15:08:12 +00006038
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006039 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006040
Rafael Espindola06e1b132012-07-12 04:32:30 +00006041 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6042 if (l->getKind() != AttributeList::AT_Visibility)
6043 continue;
6044 l->setInvalid();
6045 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6046 l->getName();
6047 }
6048
David Blaikie751c5582011-09-22 02:58:26 +00006049 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006050 // strict aliasing violation!
6051 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006052 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006053
Douglas Gregor0be31a22010-07-02 17:43:08 +00006054 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006055 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006056}
6057
Douglas Gregor05379422008-11-03 17:51:48 +00006058/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6059/// special functions, such as the default constructor, copy
6060/// constructor, or destructor, to the given C++ class (C++
6061/// [special]p1). This routine can only be executed just before the
6062/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006063void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006064 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006065 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006066
Richard Smith6b02d462012-12-08 08:32:28 +00006067 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006068 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006069
Richard Smith6b02d462012-12-08 08:32:28 +00006070 // If the properties or semantics of the copy constructor couldn't be
6071 // determined while the class was being declared, force a declaration
6072 // of it now.
6073 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6074 DeclareImplicitCopyConstructor(ClassDecl);
6075 }
6076
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006077 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006078 ++ASTContext::NumImplicitMoveConstructors;
6079
Richard Smith6b02d462012-12-08 08:32:28 +00006080 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6081 DeclareImplicitMoveConstructor(ClassDecl);
6082 }
6083
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006084 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6085 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006086
6087 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006088 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006089 // it shows up in the right place in the vtable and that we diagnose
6090 // problems with the implicit exception specification.
6091 if (ClassDecl->isDynamicClass() ||
6092 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006093 DeclareImplicitCopyAssignment(ClassDecl);
6094 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006095
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006096 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006097 ++ASTContext::NumImplicitMoveAssignmentOperators;
6098
6099 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006100 if (ClassDecl->isDynamicClass() ||
6101 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006102 DeclareImplicitMoveAssignment(ClassDecl);
6103 }
6104
Douglas Gregor7454c562010-07-02 20:37:36 +00006105 if (!ClassDecl->hasUserDeclaredDestructor()) {
6106 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006107
6108 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006109 // have to declare the destructor immediately. This ensures that, e.g., it
6110 // shows up in the right place in the vtable and that we diagnose problems
6111 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006112 if (ClassDecl->isDynamicClass() ||
6113 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006114 DeclareImplicitDestructor(ClassDecl);
6115 }
Douglas Gregor05379422008-11-03 17:51:48 +00006116}
6117
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006118unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006119 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006120 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006121
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006122 // The order of template parameters is not important here. All names
6123 // get added to the same scope.
6124 SmallVector<TemplateParameterList *, 4> ParameterLists;
6125
6126 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6127 D = TD->getTemplatedDecl();
6128
6129 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6130 ParameterLists.push_back(PSD->getTemplateParameters());
6131
6132 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6133 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6134 ParameterLists.push_back(DD->getTemplateParameterList(i));
6135
6136 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6137 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6138 ParameterLists.push_back(FTD->getTemplateParameters());
6139 }
6140 }
6141
6142 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6143 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6144 ParameterLists.push_back(TD->getTemplateParameterList(i));
6145
6146 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6147 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6148 ParameterLists.push_back(CTD->getTemplateParameters());
6149 }
6150 }
6151
6152 unsigned Count = 0;
6153 for (TemplateParameterList *Params : ParameterLists) {
6154 if (Params->size() > 0)
6155 // Ignore explicit specializations; they don't contribute to the template
6156 // depth.
6157 ++Count;
6158 for (NamedDecl *Param : *Params) {
6159 if (Param->getDeclName()) {
6160 S->AddDecl(Param);
6161 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006162 }
6163 }
6164 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006165
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006166 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006167}
6168
John McCall48871652010-08-21 09:40:31 +00006169void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006170 if (!RecordD) return;
6171 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006172 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006173 PushDeclContext(S, Record);
6174}
6175
John McCall48871652010-08-21 09:40:31 +00006176void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006177 if (!RecordD) return;
6178 PopDeclContext();
6179}
6180
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006181/// This is used to implement the constant expression evaluation part of the
6182/// attribute enable_if extension. There is nothing in standard C++ which would
6183/// require reentering parameters.
6184void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6185 if (!Param)
6186 return;
6187
6188 S->AddDecl(Param);
6189 if (Param->getDeclName())
6190 IdResolver.AddDecl(Param);
6191}
6192
Douglas Gregor4d87df52008-12-16 21:30:33 +00006193/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6194/// parsing a top-level (non-nested) C++ class, and we are now
6195/// parsing those parts of the given Method declaration that could
6196/// not be parsed earlier (C++ [class.mem]p2), such as default
6197/// arguments. This action should enter the scope of the given
6198/// Method declaration as if we had just parsed the qualified method
6199/// name. However, it should not bring the parameters into scope;
6200/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006201void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006202}
6203
6204/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6205/// C++ method declaration. We're (re-)introducing the given
6206/// function parameter into scope for use in parsing later parts of
6207/// the method declaration. For example, we could see an
6208/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006209void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006210 if (!ParamD)
6211 return;
Mike Stump11289f42009-09-09 15:08:12 +00006212
John McCall48871652010-08-21 09:40:31 +00006213 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006214
6215 // If this parameter has an unparsed default argument, clear it out
6216 // to make way for the parsed default argument.
6217 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006218 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006219
John McCall48871652010-08-21 09:40:31 +00006220 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006221 if (Param->getDeclName())
6222 IdResolver.AddDecl(Param);
6223}
6224
6225/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6226/// processing the delayed method declaration for Method. The method
6227/// declaration is now considered finished. There may be a separate
6228/// ActOnStartOfFunctionDef action later (not necessarily
6229/// immediately!) for this method, if it was also defined inside the
6230/// class body.
John McCall48871652010-08-21 09:40:31 +00006231void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006232 if (!MethodD)
6233 return;
Mike Stump11289f42009-09-09 15:08:12 +00006234
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006235 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006236
John McCall48871652010-08-21 09:40:31 +00006237 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006238
6239 // Now that we have our default arguments, check the constructor
6240 // again. It could produce additional diagnostics or affect whether
6241 // the class has implicitly-declared destructors, among other
6242 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006243 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6244 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006245
6246 // Check the default arguments, which we may have added.
6247 if (!Method->isInvalidDecl())
6248 CheckCXXDefaultArguments(Method);
6249}
6250
Douglas Gregor831c93f2008-11-05 20:51:48 +00006251/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006252/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006253/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006254/// emit diagnostics and set the invalid bit to true. In any case, the type
6255/// will be updated to reflect a well-formed type for the constructor and
6256/// returned.
6257QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006258 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006259 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006260
6261 // C++ [class.ctor]p3:
6262 // A constructor shall not be virtual (10.3) or static (9.4). A
6263 // constructor can be invoked for a const, volatile or const
6264 // volatile object. A constructor shall not be declared const,
6265 // volatile, or const volatile (9.3.2).
6266 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006267 if (!D.isInvalidType())
6268 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6269 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6270 << SourceRange(D.getIdentifierLoc());
6271 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006272 }
John McCall8e7d6562010-08-26 03:08:43 +00006273 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006274 if (!D.isInvalidType())
6275 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6276 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6277 << SourceRange(D.getIdentifierLoc());
6278 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006279 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006280 }
Mike Stump11289f42009-09-09 15:08:12 +00006281
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006282 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006283 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006284 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006285 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6286 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006287 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006288 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6289 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006290 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006291 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6292 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006293 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006294 }
Mike Stump11289f42009-09-09 15:08:12 +00006295
Douglas Gregordb9d6642011-01-26 05:01:58 +00006296 // C++0x [class.ctor]p4:
6297 // A constructor shall not be declared with a ref-qualifier.
6298 if (FTI.hasRefQualifier()) {
6299 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6300 << FTI.RefQualifierIsLValueRef
6301 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6302 D.setInvalidType();
6303 }
6304
Douglas Gregor831c93f2008-11-05 20:51:48 +00006305 // Rebuild the function type "R" without any type qualifiers (in
6306 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006307 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006308 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006309 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006310 return R;
6311
6312 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6313 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006314 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006315
6316 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006317}
6318
Douglas Gregor4d87df52008-12-16 21:30:33 +00006319/// CheckConstructor - Checks a fully-formed constructor for
6320/// well-formedness, issuing any diagnostics required. Returns true if
6321/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006322void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006323 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006324 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6325 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006326 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006327
6328 // C++ [class.copy]p3:
6329 // A declaration of a constructor for a class X is ill-formed if
6330 // its first parameter is of type (optionally cv-qualified) X and
6331 // either there are no other parameters or else all other
6332 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006333 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006334 ((Constructor->getNumParams() == 1) ||
6335 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006336 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6337 Constructor->getTemplateSpecializationKind()
6338 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006339 QualType ParamType = Constructor->getParamDecl(0)->getType();
6340 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6341 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006342 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006343 const char *ConstRef
6344 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6345 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006346 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006347 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006348
6349 // FIXME: Rather that making the constructor invalid, we should endeavor
6350 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006351 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006352 }
6353 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006354}
6355
John McCalldeb646e2010-08-04 01:04:25 +00006356/// CheckDestructor - Checks a fully-formed destructor definition for
6357/// well-formedness, issuing any diagnostics required. Returns true
6358/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006359bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006360 CXXRecordDecl *RD = Destructor->getParent();
6361
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006362 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006363 SourceLocation Loc;
6364
6365 if (!Destructor->isImplicit())
6366 Loc = Destructor->getLocation();
6367 else
6368 Loc = RD->getLocation();
6369
6370 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006371 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006372 DeclarationName Name =
6373 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006374 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006375 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006376 // If there's no class-specific operator delete, look up the global
6377 // non-array delete.
6378 if (!OperatorDelete)
6379 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006380
Eli Friedmanfa0df832012-02-02 03:46:19 +00006381 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006382
6383 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006384 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006385
6386 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006387}
6388
Douglas Gregor831c93f2008-11-05 20:51:48 +00006389/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6390/// the well-formednes of the destructor declarator @p D with type @p
6391/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006392/// emit diagnostics and set the declarator to invalid. Even if this happens,
6393/// will be updated to reflect a well-formed type for the destructor and
6394/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006395QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006396 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006397 // C++ [class.dtor]p1:
6398 // [...] A typedef-name that names a class is a class-name
6399 // (7.1.3); however, a typedef-name that names a class shall not
6400 // be used as the identifier in the declarator for a destructor
6401 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006402 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006403 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006404 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006405 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006406 else if (const TemplateSpecializationType *TST =
6407 DeclaratorType->getAs<TemplateSpecializationType>())
6408 if (TST->isTypeAlias())
6409 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6410 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006411
6412 // C++ [class.dtor]p2:
6413 // A destructor is used to destroy objects of its class type. A
6414 // destructor takes no parameters, and no return type can be
6415 // specified for it (not even void). The address of a destructor
6416 // shall not be taken. A destructor shall not be static. A
6417 // destructor can be invoked for a const, volatile or const
6418 // volatile object. A destructor shall not be declared const,
6419 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006420 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006421 if (!D.isInvalidType())
6422 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6423 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006424 << SourceRange(D.getIdentifierLoc())
6425 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6426
John McCall8e7d6562010-08-26 03:08:43 +00006427 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006428 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006429 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006430 // Destructors don't have return types, but the parser will
6431 // happily parse something like:
6432 //
6433 // class X {
6434 // float ~X();
6435 // };
6436 //
6437 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006438 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6439 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6440 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006441 }
Mike Stump11289f42009-09-09 15:08:12 +00006442
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006443 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006444 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006445 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006446 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6447 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006448 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006449 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6450 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006451 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006452 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6453 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006454 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006455 }
6456
Douglas Gregordb9d6642011-01-26 05:01:58 +00006457 // C++0x [class.dtor]p2:
6458 // A destructor shall not be declared with a ref-qualifier.
6459 if (FTI.hasRefQualifier()) {
6460 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6461 << FTI.RefQualifierIsLValueRef
6462 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6463 D.setInvalidType();
6464 }
6465
Douglas Gregor831c93f2008-11-05 20:51:48 +00006466 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006467 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006468 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6469
6470 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006471 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006472 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006473 }
6474
Mike Stump11289f42009-09-09 15:08:12 +00006475 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006476 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006477 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006478 D.setInvalidType();
6479 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006480
6481 // Rebuild the function type "R" without any type qualifiers or
6482 // parameters (in case any of the errors above fired) and with
6483 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006484 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006485 if (!D.isInvalidType())
6486 return R;
6487
Douglas Gregor95755162010-07-01 05:10:53 +00006488 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006489 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6490 EPI.Variadic = false;
6491 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006492 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006493 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006494}
6495
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006496/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6497/// well-formednes of the conversion function declarator @p D with
6498/// type @p R. If there are any errors in the declarator, this routine
6499/// will emit diagnostics and return true. Otherwise, it will return
6500/// false. Either way, the type @p R will be updated to reflect a
6501/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006502void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006503 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006504 // C++ [class.conv.fct]p1:
6505 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006506 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006507 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006508 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006509 if (!D.isInvalidType())
6510 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006511 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6512 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006513 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006514 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006515 }
John McCall212fa2e2010-04-13 00:04:31 +00006516
6517 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6518
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006519 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006520 // Conversion functions don't have return types, but the parser will
6521 // happily parse something like:
6522 //
6523 // class X {
6524 // float operator bool();
6525 // };
6526 //
6527 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006528 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6529 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6530 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006531 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006532 }
6533
John McCall212fa2e2010-04-13 00:04:31 +00006534 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6535
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006536 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006537 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006538 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6539
6540 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006541 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006542 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006543 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006544 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006545 D.setInvalidType();
6546 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006547
John McCall212fa2e2010-04-13 00:04:31 +00006548 // Diagnose "&operator bool()" and other such nonsense. This
6549 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006550 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006551 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006552 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006553 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006554 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006555 }
6556
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006557 // C++ [class.conv.fct]p4:
6558 // The conversion-type-id shall not represent a function type nor
6559 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006560 if (ConvType->isArrayType()) {
6561 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6562 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006563 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006564 } else if (ConvType->isFunctionType()) {
6565 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6566 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006567 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006568 }
6569
6570 // Rebuild the function type "R" without any parameters (in case any
6571 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006572 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006573 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006574 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006575
Douglas Gregor5fb53972009-01-14 15:45:31 +00006576 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006577 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006578 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006579 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006580 diag::warn_cxx98_compat_explicit_conversion_functions :
6581 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006582 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006583}
6584
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006585/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6586/// the declaration of the given C++ conversion function. This routine
6587/// is responsible for recording the conversion function in the C++
6588/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006589Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006590 assert(Conversion && "Expected to receive a conversion function declaration");
6591
Douglas Gregor4287b372008-12-12 08:25:50 +00006592 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006593
6594 // Make sure we aren't redeclaring the conversion function.
6595 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006596
6597 // C++ [class.conv.fct]p1:
6598 // [...] A conversion function is never used to convert a
6599 // (possibly cv-qualified) object to the (possibly cv-qualified)
6600 // same object type (or a reference to it), to a (possibly
6601 // cv-qualified) base class of that type (or a reference to it),
6602 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006603 // FIXME: Suppress this warning if the conversion function ends up being a
6604 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006605 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006606 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006607 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006608 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006609 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6610 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006611 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006612 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006613 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6614 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006615 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006616 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006617 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006618 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006619 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006620 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006621 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006622 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006623 }
6624
Douglas Gregor457104e2010-09-29 04:25:11 +00006625 if (FunctionTemplateDecl *ConversionTemplate
6626 = Conversion->getDescribedFunctionTemplate())
6627 return ConversionTemplate;
6628
John McCall48871652010-08-21 09:40:31 +00006629 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006630}
6631
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006632//===----------------------------------------------------------------------===//
6633// Namespace Handling
6634//===----------------------------------------------------------------------===//
6635
Richard Smith45bb8852012-10-04 22:13:39 +00006636/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6637/// reopened.
6638static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6639 SourceLocation Loc,
6640 IdentifierInfo *II, bool *IsInline,
6641 NamespaceDecl *PrevNS) {
6642 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006643
Richard Smithf501cc32012-10-05 01:46:25 +00006644 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6645 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6646 // inline namespaces, with the intention of bringing names into namespace std.
6647 //
6648 // We support this just well enough to get that case working; this is not
6649 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006650 if (*IsInline && II && II->getName().startswith("__atomic") &&
6651 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006652 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006653 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6654 NS = NS->getPreviousDecl())
6655 NS->setInline(*IsInline);
6656 // Patch up the lookup table for the containing namespace. This isn't really
6657 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006658 for (auto *I : PrevNS->decls())
6659 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006660 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6661 return;
6662 }
6663
6664 if (PrevNS->isInline())
6665 // The user probably just forgot the 'inline', so suggest that it
6666 // be added back.
6667 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6668 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6669 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006670 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006671
6672 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6673 *IsInline = PrevNS->isInline();
6674}
John McCallb1be5232010-08-26 09:15:37 +00006675
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006676/// ActOnStartNamespaceDef - This is called at the start of a namespace
6677/// definition.
John McCall48871652010-08-21 09:40:31 +00006678Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006679 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006680 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006681 SourceLocation IdentLoc,
6682 IdentifierInfo *II,
6683 SourceLocation LBrace,
6684 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006685 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6686 // For anonymous namespace, take the location of the left brace.
6687 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006688 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006689 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006690 bool IsStd = false;
6691 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006692 Scope *DeclRegionScope = NamespcScope->getParent();
6693
Craig Topperc3ec1492014-05-26 06:22:03 +00006694 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006695 if (II) {
6696 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006697 // The identifier in an original-namespace-definition shall not
6698 // have been previously defined in the declarative region in
6699 // which the original-namespace-definition appears. The
6700 // identifier in an original-namespace-definition is the name of
6701 // the namespace. Subsequently in that declarative region, it is
6702 // treated as an original-namespace-name.
6703 //
6704 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006705 // look through using directives, just look for any ordinary names.
6706
6707 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006708 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6709 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006710 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006711 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6712 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6713 ++I) {
6714 if ((*I)->getIdentifierNamespace() & IDNS) {
6715 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006716 break;
6717 }
6718 }
6719
Douglas Gregore57e7522012-01-07 09:11:48 +00006720 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6721
6722 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006723 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006724 if (IsInline != PrevNS->isInline())
6725 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6726 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006727 } else if (PrevDecl) {
6728 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006729 Diag(Loc, diag::err_redefinition_different_kind)
6730 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006731 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006732 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006733 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006734 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006735 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006736 // This is the first "real" definition of the namespace "std", so update
6737 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006738 PrevNS = getStdNamespace();
6739 IsStd = true;
6740 AddToKnown = !IsInline;
6741 } else {
6742 // We've seen this namespace for the first time.
6743 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006744 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006745 } else {
John McCall4fa53422009-10-01 00:25:31 +00006746 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006747
6748 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006749 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006750 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006751 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006752 } else {
6753 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006754 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006755 }
6756
Richard Smith45bb8852012-10-04 22:13:39 +00006757 if (PrevNS && IsInline != PrevNS->isInline())
6758 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6759 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006760 }
6761
6762 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6763 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006764 if (IsInvalid)
6765 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006766
6767 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006768
Douglas Gregore57e7522012-01-07 09:11:48 +00006769 // FIXME: Should we be merging attributes?
6770 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006771 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006772
6773 if (IsStd)
6774 StdNamespace = Namespc;
6775 if (AddToKnown)
6776 KnownNamespaces[Namespc] = false;
6777
6778 if (II) {
6779 PushOnScopeChains(Namespc, DeclRegionScope);
6780 } else {
6781 // Link the anonymous namespace into its parent.
6782 DeclContext *Parent = CurContext->getRedeclContext();
6783 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6784 TU->setAnonymousNamespace(Namespc);
6785 } else {
6786 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006787 }
John McCall4fa53422009-10-01 00:25:31 +00006788
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006789 CurContext->addDecl(Namespc);
6790
John McCall4fa53422009-10-01 00:25:31 +00006791 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6792 // behaves as if it were replaced by
6793 // namespace unique { /* empty body */ }
6794 // using namespace unique;
6795 // namespace unique { namespace-body }
6796 // where all occurrences of 'unique' in a translation unit are
6797 // replaced by the same identifier and this identifier differs
6798 // from all other identifiers in the entire program.
6799
6800 // We just create the namespace with an empty name and then add an
6801 // implicit using declaration, just like the standard suggests.
6802 //
6803 // CodeGen enforces the "universally unique" aspect by giving all
6804 // declarations semantically contained within an anonymous
6805 // namespace internal linkage.
6806
Douglas Gregore57e7522012-01-07 09:11:48 +00006807 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006808 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006809 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006810 /* 'using' */ LBrace,
6811 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006812 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006813 /* identifier */ SourceLocation(),
6814 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006815 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006816 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006817 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006818 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006819 }
6820
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006821 ActOnDocumentableDecl(Namespc);
6822
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006823 // Although we could have an invalid decl (i.e. the namespace name is a
6824 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006825 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6826 // for the namespace has the declarations that showed up in that particular
6827 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006828 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006829 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006830}
6831
Sebastian Redla6602e92009-11-23 15:34:23 +00006832/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6833/// is a namespace alias, returns the namespace it points to.
6834static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6835 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6836 return AD->getNamespace();
6837 return dyn_cast_or_null<NamespaceDecl>(D);
6838}
6839
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006840/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6841/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006842void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006843 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6844 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006845 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006846 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006847 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006848 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006849}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006850
John McCall28a0cf72010-08-25 07:42:41 +00006851CXXRecordDecl *Sema::getStdBadAlloc() const {
6852 return cast_or_null<CXXRecordDecl>(
6853 StdBadAlloc.get(Context.getExternalSource()));
6854}
6855
6856NamespaceDecl *Sema::getStdNamespace() const {
6857 return cast_or_null<NamespaceDecl>(
6858 StdNamespace.get(Context.getExternalSource()));
6859}
6860
Douglas Gregorcdf87022010-06-29 17:53:46 +00006861/// \brief Retrieve the special "std" namespace, which may require us to
6862/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006863NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006864 if (!StdNamespace) {
6865 // The "std" namespace has not yet been defined, so build one implicitly.
6866 StdNamespace = NamespaceDecl::Create(Context,
6867 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006868 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006869 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006870 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006871 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006872 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006873 }
6874
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006875 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006876}
6877
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006878bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006879 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006880 "Looking for std::initializer_list outside of C++.");
6881
6882 // We're looking for implicit instantiations of
6883 // template <typename E> class std::initializer_list.
6884
6885 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6886 return false;
6887
Craig Topperc3ec1492014-05-26 06:22:03 +00006888 ClassTemplateDecl *Template = nullptr;
6889 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006890
Sebastian Redl43144e72012-01-17 22:49:58 +00006891 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006892
Sebastian Redl43144e72012-01-17 22:49:58 +00006893 ClassTemplateSpecializationDecl *Specialization =
6894 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6895 if (!Specialization)
6896 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006897
Sebastian Redl43144e72012-01-17 22:49:58 +00006898 Template = Specialization->getSpecializedTemplate();
6899 Arguments = Specialization->getTemplateArgs().data();
6900 } else if (const TemplateSpecializationType *TST =
6901 Ty->getAs<TemplateSpecializationType>()) {
6902 Template = dyn_cast_or_null<ClassTemplateDecl>(
6903 TST->getTemplateName().getAsTemplateDecl());
6904 Arguments = TST->getArgs();
6905 }
6906 if (!Template)
6907 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006908
6909 if (!StdInitializerList) {
6910 // Haven't recognized std::initializer_list yet, maybe this is it.
6911 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6912 if (TemplateClass->getIdentifier() !=
6913 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006914 !getStdNamespace()->InEnclosingNamespaceSetOf(
6915 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006916 return false;
6917 // This is a template called std::initializer_list, but is it the right
6918 // template?
6919 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006920 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006921 return false;
6922 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6923 return false;
6924
6925 // It's the right template.
6926 StdInitializerList = Template;
6927 }
6928
6929 if (Template != StdInitializerList)
6930 return false;
6931
6932 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006933 if (Element)
6934 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006935 return true;
6936}
6937
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006938static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6939 NamespaceDecl *Std = S.getStdNamespace();
6940 if (!Std) {
6941 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006942 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006943 }
6944
6945 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6946 Loc, Sema::LookupOrdinaryName);
6947 if (!S.LookupQualifiedName(Result, Std)) {
6948 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006949 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006950 }
6951 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6952 if (!Template) {
6953 Result.suppressDiagnostics();
6954 // We found something weird. Complain about the first thing we found.
6955 NamedDecl *Found = *Result.begin();
6956 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006957 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006958 }
6959
6960 // We found some template called std::initializer_list. Now verify that it's
6961 // correct.
6962 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006963 if (Params->getMinRequiredArguments() != 1 ||
6964 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006965 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006966 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006967 }
6968
6969 return Template;
6970}
6971
6972QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6973 if (!StdInitializerList) {
6974 StdInitializerList = LookupStdInitializerList(*this, Loc);
6975 if (!StdInitializerList)
6976 return QualType();
6977 }
6978
6979 TemplateArgumentListInfo Args(Loc, Loc);
6980 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6981 Context.getTrivialTypeSourceInfo(Element,
6982 Loc)));
6983 return Context.getCanonicalType(
6984 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6985}
6986
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006987bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6988 // C++ [dcl.init.list]p2:
6989 // A constructor is an initializer-list constructor if its first parameter
6990 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6991 // std::initializer_list<E> for some type E, and either there are no other
6992 // parameters or else all other parameters have default arguments.
6993 if (Ctor->getNumParams() < 1 ||
6994 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6995 return false;
6996
6997 QualType ArgType = Ctor->getParamDecl(0)->getType();
6998 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6999 ArgType = RT->getPointeeType().getUnqualifiedType();
7000
Craig Topperc3ec1492014-05-26 06:22:03 +00007001 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007002}
7003
Douglas Gregora172e082011-03-26 22:25:30 +00007004/// \brief Determine whether a using statement is in a context where it will be
7005/// apply in all contexts.
7006static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7007 switch (CurContext->getDeclKind()) {
7008 case Decl::TranslationUnit:
7009 return true;
7010 case Decl::LinkageSpec:
7011 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7012 default:
7013 return false;
7014 }
7015}
7016
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007017namespace {
7018
7019// Callback to only accept typo corrections that are namespaces.
7020class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007021public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007022 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007023 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007024 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007025 return false;
7026 }
7027};
7028
7029}
7030
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007031static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7032 CXXScopeSpec &SS,
7033 SourceLocation IdentLoc,
7034 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007035 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007036 R.clear();
7037 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007038 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00007039 Validator,
7040 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007041 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007042 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7043 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007044 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007045 S.diagnoseTypo(Corrected,
7046 S.PDiag(diag::err_using_directive_member_suggest)
7047 << Ident << DC << DroppedSpecifier << SS.getRange(),
7048 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007049 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007050 S.diagnoseTypo(Corrected,
7051 S.PDiag(diag::err_using_directive_suggest) << Ident,
7052 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007053 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007054 R.addDecl(Corrected.getCorrectionDecl());
7055 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007056 }
7057 return false;
7058}
7059
John McCall48871652010-08-21 09:40:31 +00007060Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007061 SourceLocation UsingLoc,
7062 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007063 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007064 SourceLocation IdentLoc,
7065 IdentifierInfo *NamespcName,
7066 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007067 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7068 assert(NamespcName && "Invalid NamespcName.");
7069 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007070
7071 // This can only happen along a recovery path.
7072 while (S->getFlags() & Scope::TemplateParamScope)
7073 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007074 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007075
Craig Topperc3ec1492014-05-26 06:22:03 +00007076 UsingDirectiveDecl *UDir = nullptr;
7077 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007078 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007079 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007080
Douglas Gregor34074322009-01-14 22:20:51 +00007081 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007082 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7083 LookupParsedName(R, S, &SS);
7084 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007085 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007086
Douglas Gregorcdf87022010-06-29 17:53:46 +00007087 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007088 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007089 // Allow "using namespace std;" or "using namespace ::std;" even if
7090 // "std" hasn't been defined yet, for GCC compatibility.
7091 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7092 NamespcName->isStr("std")) {
7093 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007094 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007095 R.resolveKind();
7096 }
7097 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007098 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007099 }
7100
John McCall9f3059a2009-10-09 21:13:30 +00007101 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007102 NamedDecl *Named = R.getFoundDecl();
7103 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7104 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007105 // C++ [namespace.udir]p1:
7106 // A using-directive specifies that the names in the nominated
7107 // namespace can be used in the scope in which the
7108 // using-directive appears after the using-directive. During
7109 // unqualified name lookup (3.4.1), the names appear as if they
7110 // were declared in the nearest enclosing namespace which
7111 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007112 // namespace. [Note: in this context, "contains" means "contains
7113 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007114
7115 // Find enclosing context containing both using-directive and
7116 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007117 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007118 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7119 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7120 CommonAncestor = CommonAncestor->getParent();
7121
Sebastian Redla6602e92009-11-23 15:34:23 +00007122 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007123 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007124 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007125
Douglas Gregora172e082011-03-26 22:25:30 +00007126 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007127 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007128 Diag(IdentLoc, diag::warn_using_directive_in_header);
7129 }
7130
Douglas Gregor889ceb72009-02-03 19:21:40 +00007131 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007132 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007133 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007134 }
7135
Richard Smith54ecd982013-02-20 19:22:51 +00007136 if (UDir)
7137 ProcessDeclAttributeList(S, UDir, AttrList);
7138
John McCall48871652010-08-21 09:40:31 +00007139 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007140}
7141
7142void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007143 // If the scope has an associated entity and the using directive is at
7144 // namespace or translation unit scope, add the UsingDirectiveDecl into
7145 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007146 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007147 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007148 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007149 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007150 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007151 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007152 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007153}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007154
Douglas Gregorfec52632009-06-20 00:51:54 +00007155
John McCall48871652010-08-21 09:40:31 +00007156Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007157 AccessSpecifier AS,
7158 bool HasUsingKeyword,
7159 SourceLocation UsingLoc,
7160 CXXScopeSpec &SS,
7161 UnqualifiedId &Name,
7162 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007163 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007164 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007165 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007166
Douglas Gregor220f4272009-11-04 16:30:06 +00007167 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007168 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007169 case UnqualifiedId::IK_Identifier:
7170 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007171 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007172 case UnqualifiedId::IK_ConversionFunctionId:
7173 break;
7174
7175 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007176 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007177 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007178 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007179 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007180 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007181 diag::err_using_decl_constructor)
7182 << SS.getRange();
7183
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007184 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007185
Craig Topperc3ec1492014-05-26 06:22:03 +00007186 return nullptr;
7187
Douglas Gregor220f4272009-11-04 16:30:06 +00007188 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007189 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007190 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007191 return nullptr;
7192
Douglas Gregor220f4272009-11-04 16:30:06 +00007193 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007194 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007195 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007196 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007197 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007198
7199 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7200 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007201 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007202 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007203
Richard Smithc2bc61b2013-03-18 21:12:30 +00007204 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007205 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007206 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007207 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7208 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007209 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007210 }
7211
Douglas Gregorc4356532010-12-16 00:46:58 +00007212 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7213 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007214 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007215
John McCall3f746822009-11-17 05:59:44 +00007216 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007217 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007218 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007219 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007220 if (UD)
7221 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007222
John McCall48871652010-08-21 09:40:31 +00007223 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007224}
7225
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007226/// \brief Determine whether a using declaration considers the given
7227/// declarations as "equivalent", e.g., if they are redeclarations of
7228/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007229static bool
7230IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7231 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007232 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007233
Richard Smithdda56e42011-04-15 14:24:37 +00007234 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007235 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007236 return Context.hasSameType(TD1->getUnderlyingType(),
7237 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007238
7239 return false;
7240}
7241
7242
John McCall84d87672009-12-10 09:41:52 +00007243/// Determines whether to create a using shadow decl for a particular
7244/// decl, given the set of decls existing prior to this using lookup.
7245bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007246 const LookupResult &Previous,
7247 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007248 // Diagnose finding a decl which is not from a base class of the
7249 // current class. We do this now because there are cases where this
7250 // function will silently decide not to build a shadow decl, which
7251 // will pre-empt further diagnostics.
7252 //
7253 // We don't need to do this in C++0x because we do the check once on
7254 // the qualifier.
7255 //
7256 // FIXME: diagnose the following if we care enough:
7257 // struct A { int foo; };
7258 // struct B : A { using A::foo; };
7259 // template <class T> struct C : A {};
7260 // template <class T> struct D : C<T> { using B::foo; } // <---
7261 // This is invalid (during instantiation) in C++03 because B::foo
7262 // resolves to the using decl in B, which is not a base class of D<T>.
7263 // We can't diagnose it immediately because C<T> is an unknown
7264 // specialization. The UsingShadowDecl in D<T> then points directly
7265 // to A::foo, which will look well-formed when we instantiate.
7266 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007267 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007268 DeclContext *OrigDC = Orig->getDeclContext();
7269
7270 // Handle enums and anonymous structs.
7271 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7272 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7273 while (OrigRec->isAnonymousStructOrUnion())
7274 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7275
7276 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7277 if (OrigDC == CurContext) {
7278 Diag(Using->getLocation(),
7279 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007280 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007281 Diag(Orig->getLocation(), diag::note_using_decl_target);
7282 return true;
7283 }
7284
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007285 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007286 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007287 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007288 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007289 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007290 Diag(Orig->getLocation(), diag::note_using_decl_target);
7291 return true;
7292 }
7293 }
7294
7295 if (Previous.empty()) return false;
7296
7297 NamedDecl *Target = Orig;
7298 if (isa<UsingShadowDecl>(Target))
7299 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7300
John McCalla17e83e2009-12-11 02:33:26 +00007301 // If the target happens to be one of the previous declarations, we
7302 // don't have a conflict.
7303 //
7304 // FIXME: but we might be increasing its access, in which case we
7305 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007306 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007307 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007308 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7309 I != E; ++I) {
7310 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007311 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7312 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7313 PrevShadow = Shadow;
7314 FoundEquivalentDecl = true;
7315 }
John McCalla17e83e2009-12-11 02:33:26 +00007316
7317 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7318 }
7319
Richard Smithfd8634a2013-10-23 02:17:46 +00007320 if (FoundEquivalentDecl)
7321 return false;
7322
Alp Tokera2794f92014-01-22 07:29:52 +00007323 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007324 NamedDecl *OldDecl = nullptr;
7325 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7326 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007327 case Ovl_Overload:
7328 return false;
7329
7330 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007331 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007332 break;
Richard Smith18819302014-02-06 01:31:33 +00007333
John McCall84d87672009-12-10 09:41:52 +00007334 // We found a decl with the exact signature.
7335 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007336 // If we're in a record, we want to hide the target, so we
7337 // return true (without a diagnostic) to tell the caller not to
7338 // build a shadow decl.
7339 if (CurContext->isRecord())
7340 return true;
7341
7342 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007343 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007344 break;
7345 }
7346
7347 Diag(Target->getLocation(), diag::note_using_decl_target);
7348 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7349 return true;
7350 }
7351
7352 // Target is not a function.
7353
John McCall84d87672009-12-10 09:41:52 +00007354 if (isa<TagDecl>(Target)) {
7355 // No conflict between a tag and a non-tag.
7356 if (!Tag) return false;
7357
John McCalle29c5cd2009-12-10 19:51:03 +00007358 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007359 Diag(Target->getLocation(), diag::note_using_decl_target);
7360 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7361 return true;
7362 }
7363
7364 // No conflict between a tag and a non-tag.
7365 if (!NonTag) return false;
7366
John McCalle29c5cd2009-12-10 19:51:03 +00007367 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007368 Diag(Target->getLocation(), diag::note_using_decl_target);
7369 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7370 return true;
7371}
7372
John McCall3f746822009-11-17 05:59:44 +00007373/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007374UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007375 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007376 NamedDecl *Orig,
7377 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007378
7379 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007380 NamedDecl *Target = Orig;
7381 if (isa<UsingShadowDecl>(Target)) {
7382 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7383 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007384 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007385
John McCall3f746822009-11-17 05:59:44 +00007386 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007387 = UsingShadowDecl::Create(Context, CurContext,
7388 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007389 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007390
Douglas Gregor457104e2010-09-29 04:25:11 +00007391 Shadow->setAccess(UD->getAccess());
7392 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7393 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007394
7395 Shadow->setPreviousDecl(PrevDecl);
7396
John McCall3f746822009-11-17 05:59:44 +00007397 if (S)
John McCall3969e302009-12-08 07:46:18 +00007398 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007399 else
John McCall3969e302009-12-08 07:46:18 +00007400 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007401
John McCall3969e302009-12-08 07:46:18 +00007402
John McCall84d87672009-12-10 09:41:52 +00007403 return Shadow;
7404}
John McCall3969e302009-12-08 07:46:18 +00007405
John McCall84d87672009-12-10 09:41:52 +00007406/// Hides a using shadow declaration. This is required by the current
7407/// using-decl implementation when a resolvable using declaration in a
7408/// class is followed by a declaration which would hide or override
7409/// one or more of the using decl's targets; for example:
7410///
7411/// struct Base { void foo(int); };
7412/// struct Derived : Base {
7413/// using Base::foo;
7414/// void foo(int);
7415/// };
7416///
7417/// The governing language is C++03 [namespace.udecl]p12:
7418///
7419/// When a using-declaration brings names from a base class into a
7420/// derived class scope, member functions in the derived class
7421/// override and/or hide member functions with the same name and
7422/// parameter types in a base class (rather than conflicting).
7423///
7424/// There are two ways to implement this:
7425/// (1) optimistically create shadow decls when they're not hidden
7426/// by existing declarations, or
7427/// (2) don't create any shadow decls (or at least don't make them
7428/// visible) until we've fully parsed/instantiated the class.
7429/// The problem with (1) is that we might have to retroactively remove
7430/// a shadow decl, which requires several O(n) operations because the
7431/// decl structures are (very reasonably) not designed for removal.
7432/// (2) avoids this but is very fiddly and phase-dependent.
7433void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007434 if (Shadow->getDeclName().getNameKind() ==
7435 DeclarationName::CXXConversionFunctionName)
7436 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7437
John McCall84d87672009-12-10 09:41:52 +00007438 // Remove it from the DeclContext...
7439 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007440
John McCall84d87672009-12-10 09:41:52 +00007441 // ...and the scope, if applicable...
7442 if (S) {
John McCall48871652010-08-21 09:40:31 +00007443 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007444 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007445 }
7446
John McCall84d87672009-12-10 09:41:52 +00007447 // ...and the using decl.
7448 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7449
7450 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007451 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007452}
7453
Richard Smith09d5b3a2014-05-01 00:35:04 +00007454/// Find the base specifier for a base class with the given type.
7455static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7456 QualType DesiredBase,
7457 bool &AnyDependentBases) {
7458 // Check whether the named type is a direct base class.
7459 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7460 for (auto &Base : Derived->bases()) {
7461 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7462 if (CanonicalDesiredBase == BaseType)
7463 return &Base;
7464 if (BaseType->isDependentType())
7465 AnyDependentBases = true;
7466 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007467 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007468}
7469
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007470namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007471class UsingValidatorCCC : public CorrectionCandidateCallback {
7472public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007473 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007474 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007475 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007476 IsInstantiation(IsInstantiation), OldNNS(NNS),
7477 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007478
Craig Toppera798a9d2014-03-02 09:32:10 +00007479 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007480 NamedDecl *ND = Candidate.getCorrectionDecl();
7481
7482 // Keywords are not valid here.
7483 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007484 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007485
7486 // Completely unqualified names are invalid for a 'using' declaration.
7487 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7488 return false;
7489
Richard Smith09d5b3a2014-05-01 00:35:04 +00007490 if (RequireMemberOf) {
7491 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7492 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7493 // No-one ever wants a using-declaration to name an injected-class-name
7494 // of a base class, unless they're declaring an inheriting constructor.
7495 ASTContext &Ctx = ND->getASTContext();
7496 if (!Ctx.getLangOpts().CPlusPlus11)
7497 return false;
7498 QualType FoundType = Ctx.getRecordType(FoundRecord);
7499
7500 // Check that the injected-class-name is named as a member of its own
7501 // type; we don't want to suggest 'using Derived::Base;', since that
7502 // means something else.
7503 NestedNameSpecifier *Specifier =
7504 Candidate.WillReplaceSpecifier()
7505 ? Candidate.getCorrectionSpecifier()
7506 : OldNNS;
7507 if (!Specifier->getAsType() ||
7508 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7509 return false;
7510
7511 // Check that this inheriting constructor declaration actually names a
7512 // direct base class of the current class.
7513 bool AnyDependentBases = false;
7514 if (!findDirectBaseWithType(RequireMemberOf,
7515 Ctx.getRecordType(FoundRecord),
7516 AnyDependentBases) &&
7517 !AnyDependentBases)
7518 return false;
7519 } else {
7520 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7521 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7522 return false;
7523
7524 // FIXME: Check that the base class member is accessible?
7525 }
7526 }
7527
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007528 if (isa<TypeDecl>(ND))
7529 return HasTypenameKeyword || !IsInstantiation;
7530
7531 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007532 }
7533
7534private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007535 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007536 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007537 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007538 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007539};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007540} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007541
John McCalle61f2ba2009-11-18 02:36:19 +00007542/// Builds a using declaration.
7543///
7544/// \param IsInstantiation - Whether this call arises from an
7545/// instantiation of an unresolved using declaration. We treat
7546/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007547NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7548 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007549 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007550 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007551 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007552 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007553 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007554 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007555 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007556 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007557 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007558
Anders Carlssonf038fc22009-08-28 05:49:21 +00007559 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007560
Anders Carlsson59140b32009-08-28 03:16:11 +00007561 if (SS.isEmpty()) {
7562 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007563 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007564 }
Mike Stump11289f42009-09-09 15:08:12 +00007565
John McCall84d87672009-12-10 09:41:52 +00007566 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007567 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007568 ForRedeclaration);
7569 Previous.setHideTags(false);
7570 if (S) {
7571 LookupName(Previous, S);
7572
7573 // It is really dumb that we have to do this.
7574 LookupResult::Filter F = Previous.makeFilter();
7575 while (F.hasNext()) {
7576 NamedDecl *D = F.next();
7577 if (!isDeclInScope(D, CurContext, S))
7578 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007579 // If we found a local extern declaration that's not ordinarily visible,
7580 // and this declaration is being added to a non-block scope, ignore it.
7581 // We're only checking for scope conflicts here, not also for violations
7582 // of the linkage rules.
7583 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7584 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7585 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007586 }
7587 F.done();
7588 } else {
7589 assert(IsInstantiation && "no scope in non-instantiation");
7590 assert(CurContext->isRecord() && "scope not record in instantiation");
7591 LookupQualifiedName(Previous, CurContext);
7592 }
7593
John McCall84d87672009-12-10 09:41:52 +00007594 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007595 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7596 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007597 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007598
7599 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007600 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007601 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007602
John McCall84c16cf2009-11-12 03:15:40 +00007603 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007604 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007605 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007606 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007607 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007608 // FIXME: not all declaration name kinds are legal here
7609 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7610 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007611 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007612 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007613 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007614 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7615 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007616 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007617 D->setAccess(AS);
7618 CurContext->addDecl(D);
7619 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007620 }
John McCallb96ec562009-12-04 22:46:56 +00007621
Richard Smith09d5b3a2014-05-01 00:35:04 +00007622 auto Build = [&](bool Invalid) {
7623 UsingDecl *UD =
7624 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7625 HasTypenameKeyword);
7626 UD->setAccess(AS);
7627 CurContext->addDecl(UD);
7628 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007629 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007630 };
7631 auto BuildInvalid = [&]{ return Build(true); };
7632 auto BuildValid = [&]{ return Build(false); };
7633
7634 if (RequireCompleteDeclContext(SS, LookupContext))
7635 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007636
Richard Smith23d55872012-04-02 01:30:27 +00007637 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007638 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007639 UsingDecl *UD = BuildValid();
7640 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007641 return UD;
7642 }
7643
7644 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007645
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007646 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007647
John McCall3969e302009-12-08 07:46:18 +00007648 // Unlike most lookups, we don't always want to hide tag
7649 // declarations: tag names are visible through the using declaration
7650 // even if hidden by ordinary names, *except* in a dependent context
7651 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007652 if (!IsInstantiation)
7653 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007654
John McCall5dadb652012-04-07 03:04:20 +00007655 // For the purposes of this lookup, we have a base object type
7656 // equal to that of the current context.
7657 if (CurContext->isRecord()) {
7658 R.setBaseObjectType(
7659 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7660 }
7661
John McCall27b18f82009-11-17 02:14:36 +00007662 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007663
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007664 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007665 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007666 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007667 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007668 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007669 R.getLookupKind(), S, &SS, CCC,
7670 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007671 // We reject any correction for which ND would be NULL.
7672 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007673
Richard Smithf9b15102013-08-17 00:46:16 +00007674 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007675 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007676 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7677 << NameInfo.getName() << LookupContext << 0
7678 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007679
7680 // If we corrected to an inheriting constructor, handle it as one.
7681 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7682 if (RD && RD->isInjectedClassName()) {
7683 // Fix up the information we'll use to build the using declaration.
7684 if (Corrected.WillReplaceSpecifier()) {
7685 NestedNameSpecifierLocBuilder Builder;
7686 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7687 QualifierLoc.getSourceRange());
7688 QualifierLoc = Builder.getWithLocInContext(Context);
7689 }
7690
7691 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7692 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007693 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007694
7695 // Build it and process it as an inheriting constructor.
7696 UsingDecl *UD = BuildValid();
7697 CheckInheritingConstructorUsingDecl(UD);
7698 return UD;
7699 }
7700
7701 // FIXME: Pick up all the declarations if we found an overloaded function.
7702 R.setLookupName(Corrected.getCorrection());
7703 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007704 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007705 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007706 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007707 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007708 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007709 }
7710
Richard Smith09d5b3a2014-05-01 00:35:04 +00007711 if (R.isAmbiguous())
7712 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007713
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007714 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007715 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007716 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007717 Diag(IdentLoc, diag::err_using_typename_non_type);
7718 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7719 Diag((*I)->getUnderlyingDecl()->getLocation(),
7720 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007721 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007722 }
7723 } else {
7724 // If we asked for a non-typename and we got a type, error out,
7725 // but only if this is an instantiation of an unresolved using
7726 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007727 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007728 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7729 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007730 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007731 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007732 }
7733
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007734 // C++0x N2914 [namespace.udecl]p6:
7735 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007736 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007737 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7738 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007739 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007740 }
Mike Stump11289f42009-09-09 15:08:12 +00007741
Richard Smith09d5b3a2014-05-01 00:35:04 +00007742 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007743 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007744 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007745 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7746 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007747 }
John McCall3f746822009-11-17 05:59:44 +00007748
7749 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007750}
7751
Sebastian Redl08905022011-02-05 19:23:19 +00007752/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007753bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007754 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007755
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007756 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007757 assert(SourceType &&
7758 "Using decl naming constructor doesn't have type in scope spec.");
7759 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7760
7761 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007762 bool AnyDependentBases = false;
7763 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7764 AnyDependentBases);
7765 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007766 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007767 diag::err_using_decl_constructor_not_in_direct_base)
7768 << UD->getNameInfo().getSourceRange()
7769 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007770 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007771 return true;
7772 }
7773
Richard Smith09d5b3a2014-05-01 00:35:04 +00007774 if (Base)
7775 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007776
7777 return false;
7778}
7779
John McCall84d87672009-12-10 09:41:52 +00007780/// Checks that the given using declaration is not an invalid
7781/// redeclaration. Note that this is checking only for the using decl
7782/// itself, not for any ill-formedness among the UsingShadowDecls.
7783bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007784 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007785 const CXXScopeSpec &SS,
7786 SourceLocation NameLoc,
7787 const LookupResult &Prev) {
7788 // C++03 [namespace.udecl]p8:
7789 // C++0x [namespace.udecl]p10:
7790 // A using-declaration is a declaration and can therefore be used
7791 // repeatedly where (and only where) multiple declarations are
7792 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007793 //
John McCall032092f2010-11-29 18:01:58 +00007794 // That's in non-member contexts.
7795 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007796 return false;
7797
Aaron Ballman4a979672014-01-03 13:56:08 +00007798 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007799
7800 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7801 NamedDecl *D = *I;
7802
7803 bool DTypename;
7804 NestedNameSpecifier *DQual;
7805 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007806 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007807 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007808 } else if (UnresolvedUsingValueDecl *UD
7809 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7810 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007811 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007812 } else if (UnresolvedUsingTypenameDecl *UD
7813 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7814 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007815 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007816 } else continue;
7817
7818 // using decls differ if one says 'typename' and the other doesn't.
7819 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007820 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007821
7822 // using decls differ if they name different scopes (but note that
7823 // template instantiation can cause this check to trigger when it
7824 // didn't before instantiation).
7825 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7826 Context.getCanonicalNestedNameSpecifier(DQual))
7827 continue;
7828
7829 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007830 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007831 return true;
7832 }
7833
7834 return false;
7835}
7836
John McCall3969e302009-12-08 07:46:18 +00007837
John McCallb96ec562009-12-04 22:46:56 +00007838/// Checks that the given nested-name qualifier used in a using decl
7839/// in the current context is appropriately related to the current
7840/// scope. If an error is found, diagnoses it and returns true.
7841bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7842 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007843 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007844 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007845 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007846
John McCall3969e302009-12-08 07:46:18 +00007847 if (!CurContext->isRecord()) {
7848 // C++03 [namespace.udecl]p3:
7849 // C++0x [namespace.udecl]p8:
7850 // A using-declaration for a class member shall be a member-declaration.
7851
7852 // If we weren't able to compute a valid scope, it must be a
7853 // dependent class scope.
7854 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007855 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7856 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007857 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007858
John McCall3969e302009-12-08 07:46:18 +00007859 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7860 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007861
7862 // If we have a complete, non-dependent source type, try to suggest a
7863 // way to get the same effect.
7864 if (!RD)
7865 return true;
7866
7867 // Find what this using-declaration was referring to.
7868 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7869 R.setHideTags(false);
7870 R.suppressDiagnostics();
7871 LookupQualifiedName(R, RD);
7872
7873 if (R.getAsSingle<TypeDecl>()) {
7874 if (getLangOpts().CPlusPlus11) {
7875 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7876 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7877 << 0 // alias declaration
7878 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7879 NameInfo.getName().getAsString() +
7880 " = ");
7881 } else {
7882 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7883 SourceLocation InsertLoc =
7884 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7885 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7886 << 1 // typedef declaration
7887 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7888 << FixItHint::CreateInsertion(
7889 InsertLoc, " " + NameInfo.getName().getAsString());
7890 }
7891 } else if (R.getAsSingle<VarDecl>()) {
7892 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7893 // repeating the type of the static data member here.
7894 FixItHint FixIt;
7895 if (getLangOpts().CPlusPlus11) {
7896 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7897 FixIt = FixItHint::CreateReplacement(
7898 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7899 }
7900
7901 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7902 << 2 // reference declaration
7903 << FixIt;
7904 }
John McCall3969e302009-12-08 07:46:18 +00007905 return true;
7906 }
7907
7908 // Otherwise, everything is known to be fine.
7909 return false;
7910 }
7911
7912 // The current scope is a record.
7913
7914 // If the named context is dependent, we can't decide much.
7915 if (!NamedContext) {
7916 // FIXME: in C++0x, we can diagnose if we can prove that the
7917 // nested-name-specifier does not refer to a base class, which is
7918 // still possible in some cases.
7919
7920 // Otherwise we have to conservatively report that things might be
7921 // okay.
7922 return false;
7923 }
7924
7925 if (!NamedContext->isRecord()) {
7926 // Ideally this would point at the last name in the specifier,
7927 // but we don't have that level of source info.
7928 Diag(SS.getRange().getBegin(),
7929 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007930 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007931 return true;
7932 }
7933
Douglas Gregor7c842292010-12-21 07:41:49 +00007934 if (!NamedContext->isDependentContext() &&
7935 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7936 return true;
7937
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007938 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007939 // C++0x [namespace.udecl]p3:
7940 // In a using-declaration used as a member-declaration, the
7941 // nested-name-specifier shall name a base class of the class
7942 // being defined.
7943
7944 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7945 cast<CXXRecordDecl>(NamedContext))) {
7946 if (CurContext == NamedContext) {
7947 Diag(NameLoc,
7948 diag::err_using_decl_nested_name_specifier_is_current_class)
7949 << SS.getRange();
7950 return true;
7951 }
7952
7953 Diag(SS.getRange().getBegin(),
7954 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007955 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007956 << cast<CXXRecordDecl>(CurContext)
7957 << SS.getRange();
7958 return true;
7959 }
7960
7961 return false;
7962 }
7963
7964 // C++03 [namespace.udecl]p4:
7965 // A using-declaration used as a member-declaration shall refer
7966 // to a member of a base class of the class being defined [etc.].
7967
7968 // Salient point: SS doesn't have to name a base class as long as
7969 // lookup only finds members from base classes. Therefore we can
7970 // diagnose here only if we can prove that that can't happen,
7971 // i.e. if the class hierarchies provably don't intersect.
7972
7973 // TODO: it would be nice if "definitely valid" results were cached
7974 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7975 // need to be repeated.
7976
7977 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007978 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007979
7980 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7981 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7982 Data->Bases.insert(Base);
7983 return true;
7984 }
7985
7986 bool hasDependentBases(const CXXRecordDecl *Class) {
7987 return !Class->forallBases(collect, this);
7988 }
7989
7990 /// Returns true if the base is dependent or is one of the
7991 /// accumulated base classes.
7992 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7993 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7994 return !Data->Bases.count(Base);
7995 }
7996
7997 bool mightShareBases(const CXXRecordDecl *Class) {
7998 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7999 }
8000 };
8001
8002 UserData Data;
8003
8004 // Returns false if we find a dependent base.
8005 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8006 return false;
8007
8008 // Returns false if the class has a dependent base or if it or one
8009 // of its bases is present in the base set of the current context.
8010 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8011 return false;
8012
8013 Diag(SS.getRange().getBegin(),
8014 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008015 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008016 << cast<CXXRecordDecl>(CurContext)
8017 << SS.getRange();
8018
8019 return true;
John McCallb96ec562009-12-04 22:46:56 +00008020}
8021
Richard Smithdda56e42011-04-15 14:24:37 +00008022Decl *Sema::ActOnAliasDeclaration(Scope *S,
8023 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008024 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008025 SourceLocation UsingLoc,
8026 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008027 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008028 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008029 // Skip up to the relevant declaration scope.
8030 while (S->getFlags() & Scope::TemplateParamScope)
8031 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008032 assert((S->getFlags() & Scope::DeclScope) &&
8033 "got alias-declaration outside of declaration scope");
8034
8035 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008036 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008037
8038 bool Invalid = false;
8039 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008040 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008041 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008042
8043 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008044 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008045
8046 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008047 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008048 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008049 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8050 TInfo->getTypeLoc().getBeginLoc());
8051 }
Richard Smithdda56e42011-04-15 14:24:37 +00008052
8053 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8054 LookupName(Previous, S);
8055
8056 // Warn about shadowing the name of a template parameter.
8057 if (Previous.isSingleResult() &&
8058 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008059 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008060 Previous.clear();
8061 }
8062
8063 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8064 "name in alias declaration must be an identifier");
8065 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8066 Name.StartLocation,
8067 Name.Identifier, TInfo);
8068
8069 NewTD->setAccess(AS);
8070
8071 if (Invalid)
8072 NewTD->setInvalidDecl();
8073
Richard Smith54ecd982013-02-20 19:22:51 +00008074 ProcessDeclAttributeList(S, NewTD, AttrList);
8075
Richard Smith3f1b5d02011-05-05 21:57:07 +00008076 CheckTypedefForVariablyModifiedType(S, NewTD);
8077 Invalid |= NewTD->isInvalidDecl();
8078
Richard Smithdda56e42011-04-15 14:24:37 +00008079 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008080
8081 NamedDecl *NewND;
8082 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008083 TypeAliasTemplateDecl *OldDecl = nullptr;
8084 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008085
8086 if (TemplateParamLists.size() != 1) {
8087 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008088 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8089 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008090 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008091 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008092
8093 // Only consider previous declarations in the same scope.
8094 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8095 /*ExplicitInstantiationOrSpecialization*/false);
8096 if (!Previous.empty()) {
8097 Redeclaration = true;
8098
8099 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8100 if (!OldDecl && !Invalid) {
8101 Diag(UsingLoc, diag::err_redefinition_different_kind)
8102 << Name.Identifier;
8103
8104 NamedDecl *OldD = Previous.getRepresentativeDecl();
8105 if (OldD->getLocation().isValid())
8106 Diag(OldD->getLocation(), diag::note_previous_definition);
8107
8108 Invalid = true;
8109 }
8110
8111 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8112 if (TemplateParameterListsAreEqual(TemplateParams,
8113 OldDecl->getTemplateParameters(),
8114 /*Complain=*/true,
8115 TPL_TemplateMatch))
8116 OldTemplateParams = OldDecl->getTemplateParameters();
8117 else
8118 Invalid = true;
8119
8120 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8121 if (!Invalid &&
8122 !Context.hasSameType(OldTD->getUnderlyingType(),
8123 NewTD->getUnderlyingType())) {
8124 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8125 // but we can't reasonably accept it.
8126 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8127 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8128 if (OldTD->getLocation().isValid())
8129 Diag(OldTD->getLocation(), diag::note_previous_definition);
8130 Invalid = true;
8131 }
8132 }
8133 }
8134
8135 // Merge any previous default template arguments into our parameters,
8136 // and check the parameter list.
8137 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8138 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008139 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008140
8141 TypeAliasTemplateDecl *NewDecl =
8142 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8143 Name.Identifier, TemplateParams,
8144 NewTD);
8145
8146 NewDecl->setAccess(AS);
8147
8148 if (Invalid)
8149 NewDecl->setInvalidDecl();
8150 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008151 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008152
8153 NewND = NewDecl;
8154 } else {
8155 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8156 NewND = NewTD;
8157 }
Richard Smithdda56e42011-04-15 14:24:37 +00008158
8159 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008160 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008161
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008162 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008163 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008164}
8165
John McCall48871652010-08-21 09:40:31 +00008166Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008167 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008168 SourceLocation AliasLoc,
8169 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008170 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008171 SourceLocation IdentLoc,
8172 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008173
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008174 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008175 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8176 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008177
Anders Carlssondca83c42009-03-28 06:23:46 +00008178 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008179 NamedDecl *PrevDecl
8180 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8181 ForRedeclaration);
8182 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Craig Topperc3ec1492014-05-26 06:22:03 +00008183 PrevDecl = nullptr;
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008184
8185 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008186 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008187 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008188 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008189 // FIXME: At some point, we'll want to create the (redundant)
8190 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008191 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008192 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00008193 return nullptr;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008194 }
Mike Stump11289f42009-09-09 15:08:12 +00008195
Anders Carlssondca83c42009-03-28 06:23:46 +00008196 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8197 diag::err_redefinition_different_kind;
8198 Diag(AliasLoc, DiagID) << Alias;
8199 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00008200 return nullptr;
Anders Carlssondca83c42009-03-28 06:23:46 +00008201 }
8202
John McCall27b18f82009-11-17 02:14:36 +00008203 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008204 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008205
John McCall9f3059a2009-10-09 21:13:30 +00008206 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008207 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008208 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008209 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008210 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008211 }
Mike Stump11289f42009-09-09 15:08:12 +00008212
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008213 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008214 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008215 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008216 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008217
John McCalld8d0d432010-02-16 06:53:13 +00008218 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008219 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008220}
8221
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008222Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008223Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8224 CXXMethodDecl *MD) {
8225 CXXRecordDecl *ClassDecl = MD->getParent();
8226
Douglas Gregor6d880b12010-07-01 22:31:05 +00008227 // C++ [except.spec]p14:
8228 // An implicitly declared special member function (Clause 12) shall have an
8229 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008230 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008231 if (ClassDecl->isInvalidDecl())
8232 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008233
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008234 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008235 for (const auto &B : ClassDecl->bases()) {
8236 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008237 continue;
8238
Aaron Ballman574705e2014-03-13 15:41:46 +00008239 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008241 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8242 // If this is a deleted function, add it anyway. This might be conformant
8243 // with the standard. This might not. I'm not sure. It might not matter.
8244 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008245 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008246 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008247 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008248
8249 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008250 for (const auto &B : ClassDecl->vbases()) {
8251 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008252 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008253 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8254 // If this is a deleted function, add it anyway. This might be conformant
8255 // with the standard. This might not. I'm not sure. It might not matter.
8256 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008257 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008258 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008259 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008260
8261 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008262 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008263 if (F->hasInClassInitializer()) {
8264 if (Expr *E = F->getInClassInitializer())
8265 ExceptSpec.CalledExpr(E);
8266 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008267 // DR1351:
8268 // If the brace-or-equal-initializer of a non-static data member
8269 // invokes a defaulted default constructor of its class or of an
8270 // enclosing class in a potentially evaluated subexpression, the
8271 // program is ill-formed.
8272 //
8273 // This resolution is unworkable: the exception specification of the
8274 // default constructor can be needed in an unevaluated context, in
8275 // particular, in the operand of a noexcept-expression, and we can be
8276 // unable to compute an exception specification for an enclosed class.
8277 //
8278 // We do not allow an in-class initializer to require the evaluation
8279 // of the exception specification for any in-class initializer whose
8280 // definition is not lexically complete.
8281 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008282 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008283 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008284 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8285 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8286 // If this is a deleted function, add it anyway. This might be conformant
8287 // with the standard. This might not. I'm not sure. It might not matter.
8288 // In particular, the problem is that this function never gets called. It
8289 // might just be ill-formed because this function attempts to refer to
8290 // a deleted function here.
8291 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008292 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008293 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008294 }
John McCalldb40c7f2010-12-14 08:05:40 +00008295
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008296 return ExceptSpec;
8297}
8298
Richard Smithc2bc61b2013-03-18 21:12:30 +00008299Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008300Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8301 CXXRecordDecl *ClassDecl = CD->getParent();
8302
8303 // C++ [except.spec]p14:
8304 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008305 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008306 if (ClassDecl->isInvalidDecl())
8307 return ExceptSpec;
8308
8309 // Inherited constructor.
8310 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8311 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8312 // FIXME: Copying or moving the parameters could add extra exceptions to the
8313 // set, as could the default arguments for the inherited constructor. This
8314 // will be addressed when we implement the resolution of core issue 1351.
8315 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8316
8317 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008318 for (const auto &B : ClassDecl->bases()) {
8319 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008320 continue;
8321
Aaron Ballman574705e2014-03-13 15:41:46 +00008322 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008323 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8324 if (BaseClassDecl == InheritedDecl)
8325 continue;
8326 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8327 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008328 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008329 }
8330 }
8331
8332 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008333 for (const auto &B : ClassDecl->vbases()) {
8334 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008335 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8336 if (BaseClassDecl == InheritedDecl)
8337 continue;
8338 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8339 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008340 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008341 }
8342 }
8343
8344 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008345 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008346 if (F->hasInClassInitializer()) {
8347 if (Expr *E = F->getInClassInitializer())
8348 ExceptSpec.CalledExpr(E);
8349 else if (!F->isInvalidDecl())
8350 Diag(CD->getLocation(),
8351 diag::err_in_class_initializer_references_def_ctor) << CD;
8352 } else if (const RecordType *RecordTy
8353 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8354 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8355 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8356 if (Constructor)
8357 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8358 }
8359 }
8360
Richard Smithc2bc61b2013-03-18 21:12:30 +00008361 return ExceptSpec;
8362}
8363
Richard Smith8bf22e52012-11-29 01:34:07 +00008364namespace {
8365/// RAII object to register a special member as being currently declared.
8366struct DeclaringSpecialMember {
8367 Sema &S;
8368 Sema::SpecialMemberDecl D;
8369 bool WasAlreadyBeingDeclared;
8370
8371 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8372 : S(S), D(RD, CSM) {
8373 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8374 if (WasAlreadyBeingDeclared)
8375 // This almost never happens, but if it does, ensure that our cache
8376 // doesn't contain a stale result.
8377 S.SpecialMemberCache.clear();
8378
8379 // FIXME: Register a note to be produced if we encounter an error while
8380 // declaring the special member.
8381 }
8382 ~DeclaringSpecialMember() {
8383 if (!WasAlreadyBeingDeclared)
8384 S.SpecialMembersBeingDeclared.erase(D);
8385 }
8386
8387 /// \brief Are we already trying to declare this special member?
8388 bool isAlreadyBeingDeclared() const {
8389 return WasAlreadyBeingDeclared;
8390 }
8391};
8392}
8393
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008394CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8395 CXXRecordDecl *ClassDecl) {
8396 // C++ [class.ctor]p5:
8397 // A default constructor for a class X is a constructor of class X
8398 // that can be called without an argument. If there is no
8399 // user-declared constructor for class X, a default constructor is
8400 // implicitly declared. An implicitly-declared default constructor
8401 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008402 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008403 "Should not build implicit default constructor!");
8404
Richard Smith8bf22e52012-11-29 01:34:07 +00008405 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8406 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008407 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008408
Richard Smithb5800092012-06-10 05:43:50 +00008409 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8410 CXXDefaultConstructor,
8411 false);
8412
Douglas Gregor6d880b12010-07-01 22:31:05 +00008413 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008414 CanQualType ClassType
8415 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008416 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008417 DeclarationName Name
8418 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008419 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008420 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008421 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8422 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8423 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008424 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008425 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008426 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008427
8428 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008429 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008430 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008431
Richard Smith6b02d462012-12-08 08:32:28 +00008432 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8433 // constructors is easy to compute.
8434 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8435
8436 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008437 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008438
Douglas Gregor9672f922010-07-03 00:47:00 +00008439 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008440 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008441
Douglas Gregor0be31a22010-07-02 17:43:08 +00008442 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008443 PushOnScopeChains(DefaultCon, S, false);
8444 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008445
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008446 return DefaultCon;
8447}
8448
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008449void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8450 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008451 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008452 !Constructor->doesThisDeclarationHaveABody() &&
8453 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008454 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008455
Anders Carlsson423f5d82010-04-23 16:04:08 +00008456 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008457 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008458
Eli Friedmaneaf34142012-10-18 20:14:08 +00008459 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008460 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008461 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008462 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008463 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008464 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008465 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008466 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008467 }
Douglas Gregor73193272010-09-20 16:48:21 +00008468
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008469 SourceLocation Loc = Constructor->getLocEnd().isValid()
8470 ? Constructor->getLocEnd()
8471 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008472 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008473
Eli Friedman276dd182013-09-05 00:02:25 +00008474 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008475 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008476
8477 if (ASTMutationListener *L = getASTMutationListener()) {
8478 L->CompletedImplicitDefinition(Constructor);
8479 }
Richard Trieuef64e942013-10-25 00:56:00 +00008480
8481 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008482}
8483
Richard Smith938f40b2011-06-11 17:19:42 +00008484void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008485 // Perform any delayed checks on exception specifications.
8486 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008487}
8488
Richard Smith185be182013-04-10 05:48:59 +00008489namespace {
8490/// Information on inheriting constructors to declare.
8491class InheritingConstructorInfo {
8492public:
8493 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8494 : SemaRef(SemaRef), Derived(Derived) {
8495 // Mark the constructors that we already have in the derived class.
8496 //
8497 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8498 // unless there is a user-declared constructor with the same signature in
8499 // the class where the using-declaration appears.
8500 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8501 }
8502
8503 void inheritAll(CXXRecordDecl *RD) {
8504 visitAll(RD, &InheritingConstructorInfo::inherit);
8505 }
8506
8507private:
8508 /// Information about an inheriting constructor.
8509 struct InheritingConstructor {
8510 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008511 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008512
8513 /// If \c true, a constructor with this signature is already declared
8514 /// in the derived class.
8515 bool DeclaredInDerived;
8516
8517 /// The constructor which is inherited.
8518 const CXXConstructorDecl *BaseCtor;
8519
8520 /// The derived constructor we declared.
8521 CXXConstructorDecl *DerivedCtor;
8522 };
8523
8524 /// Inheriting constructors with a given canonical type. There can be at
8525 /// most one such non-template constructor, and any number of templated
8526 /// constructors.
8527 struct InheritingConstructorsForType {
8528 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008529 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8530 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008531
8532 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8533 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8534 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8535 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8536 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8537 false, S.TPL_TemplateMatch))
8538 return Templates[I].second;
8539 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8540 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008541 }
Richard Smith185be182013-04-10 05:48:59 +00008542
8543 return NonTemplate;
8544 }
8545 };
8546
8547 /// Get or create the inheriting constructor record for a constructor.
8548 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8549 QualType CtorType) {
8550 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8551 .getEntry(SemaRef, Ctor);
8552 }
8553
8554 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8555
8556 /// Process all constructors for a class.
8557 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008558 for (const auto *Ctor : RD->ctors())
8559 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008560 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8561 I(RD->decls_begin()), E(RD->decls_end());
8562 I != E; ++I) {
8563 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8564 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8565 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008566 }
8567 }
Richard Smith185be182013-04-10 05:48:59 +00008568
8569 /// Note that a constructor (or constructor template) was declared in Derived.
8570 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8571 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8572 }
8573
8574 /// Inherit a single constructor.
8575 void inherit(const CXXConstructorDecl *Ctor) {
8576 const FunctionProtoType *CtorType =
8577 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008578 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008579 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8580
8581 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8582
8583 // Core issue (no number yet): the ellipsis is always discarded.
8584 if (EPI.Variadic) {
8585 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8586 SemaRef.Diag(Ctor->getLocation(),
8587 diag::note_using_decl_constructor_ellipsis);
8588 EPI.Variadic = false;
8589 }
8590
8591 // Declare a constructor for each number of parameters.
8592 //
8593 // C++11 [class.inhctor]p1:
8594 // The candidate set of inherited constructors from the class X named in
8595 // the using-declaration consists of [... modulo defects ...] for each
8596 // constructor or constructor template of X, the set of constructors or
8597 // constructor templates that results from omitting any ellipsis parameter
8598 // specification and successively omitting parameters with a default
8599 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008600 unsigned MinParams = minParamsToInherit(Ctor);
8601 unsigned Params = Ctor->getNumParams();
8602 if (Params >= MinParams) {
8603 do
8604 declareCtor(UsingLoc, Ctor,
8605 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008606 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008607 while (Params > MinParams &&
8608 Ctor->getParamDecl(--Params)->hasDefaultArg());
8609 }
Richard Smith185be182013-04-10 05:48:59 +00008610 }
8611
8612 /// Find the using-declaration which specified that we should inherit the
8613 /// constructors of \p Base.
8614 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8615 // No fancy lookup required; just look for the base constructor name
8616 // directly within the derived class.
8617 ASTContext &Context = SemaRef.Context;
8618 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8619 Context.getCanonicalType(Context.getRecordType(Base)));
8620 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8621 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8622 }
8623
8624 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8625 // C++11 [class.inhctor]p3:
8626 // [F]or each constructor template in the candidate set of inherited
8627 // constructors, a constructor template is implicitly declared
8628 if (Ctor->getDescribedFunctionTemplate())
8629 return 0;
8630
8631 // For each non-template constructor in the candidate set of inherited
8632 // constructors other than a constructor having no parameters or a
8633 // copy/move constructor having a single parameter, a constructor is
8634 // implicitly declared [...]
8635 if (Ctor->getNumParams() == 0)
8636 return 1;
8637 if (Ctor->isCopyOrMoveConstructor())
8638 return 2;
8639
8640 // Per discussion on core reflector, never inherit a constructor which
8641 // would become a default, copy, or move constructor of Derived either.
8642 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8643 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8644 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8645 }
8646
8647 /// Declare a single inheriting constructor, inheriting the specified
8648 /// constructor, with the given type.
8649 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8650 QualType DerivedType) {
8651 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8652
8653 // C++11 [class.inhctor]p3:
8654 // ... a constructor is implicitly declared with the same constructor
8655 // characteristics unless there is a user-declared constructor with
8656 // the same signature in the class where the using-declaration appears
8657 if (Entry.DeclaredInDerived)
8658 return;
8659
8660 // C++11 [class.inhctor]p7:
8661 // If two using-declarations declare inheriting constructors with the
8662 // same signature, the program is ill-formed
8663 if (Entry.DerivedCtor) {
8664 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8665 // Only diagnose this once per constructor.
8666 if (Entry.DerivedCtor->isInvalidDecl())
8667 return;
8668 Entry.DerivedCtor->setInvalidDecl();
8669
8670 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8671 SemaRef.Diag(BaseCtor->getLocation(),
8672 diag::note_using_decl_constructor_conflict_current_ctor);
8673 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8674 diag::note_using_decl_constructor_conflict_previous_ctor);
8675 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8676 diag::note_using_decl_constructor_conflict_previous_using);
8677 } else {
8678 // Core issue (no number): if the same inheriting constructor is
8679 // produced by multiple base class constructors from the same base
8680 // class, the inheriting constructor is defined as deleted.
8681 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8682 }
8683
8684 return;
8685 }
8686
8687 ASTContext &Context = SemaRef.Context;
8688 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8689 Context.getCanonicalType(Context.getRecordType(Derived)));
8690 DeclarationNameInfo NameInfo(Name, UsingLoc);
8691
Craig Topperc3ec1492014-05-26 06:22:03 +00008692 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008693 if (const FunctionTemplateDecl *FTD =
8694 BaseCtor->getDescribedFunctionTemplate()) {
8695 TemplateParams = FTD->getTemplateParameters();
8696 // We're reusing template parameters from a different DeclContext. This
8697 // is questionable at best, but works out because the template depth in
8698 // both places is guaranteed to be 0.
8699 // FIXME: Rebuild the template parameters in the new context, and
8700 // transform the function type to refer to them.
8701 }
8702
8703 // Build type source info pointing at the using-declaration. This is
8704 // required by template instantiation.
8705 TypeSourceInfo *TInfo =
8706 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8707 FunctionProtoTypeLoc ProtoLoc =
8708 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8709
8710 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8711 Context, Derived, UsingLoc, NameInfo, DerivedType,
8712 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8713 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8714
8715 // Build an unevaluated exception specification for this constructor.
8716 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8717 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8718 EPI.ExceptionSpecType = EST_Unevaluated;
8719 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008720 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008721 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008722
8723 // Build the parameter declarations.
8724 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008725 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008726 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008727 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008728 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008729 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8730 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008731 PD->setScopeInfo(0, I);
8732 PD->setImplicit();
8733 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008734 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008735 }
8736
8737 // Set up the new constructor.
8738 DerivedCtor->setAccess(BaseCtor->getAccess());
8739 DerivedCtor->setParams(ParamDecls);
8740 DerivedCtor->setInheritedConstructor(BaseCtor);
8741 if (BaseCtor->isDeleted())
8742 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8743
8744 // If this is a constructor template, build the template declaration.
8745 if (TemplateParams) {
8746 FunctionTemplateDecl *DerivedTemplate =
8747 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8748 TemplateParams, DerivedCtor);
8749 DerivedTemplate->setAccess(BaseCtor->getAccess());
8750 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8751 Derived->addDecl(DerivedTemplate);
8752 } else {
8753 Derived->addDecl(DerivedCtor);
8754 }
8755
8756 Entry.BaseCtor = BaseCtor;
8757 Entry.DerivedCtor = DerivedCtor;
8758 }
8759
8760 Sema &SemaRef;
8761 CXXRecordDecl *Derived;
8762 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8763 MapType Map;
8764};
8765}
8766
8767void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8768 // Defer declaring the inheriting constructors until the class is
8769 // instantiated.
8770 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008771 return;
8772
Richard Smith185be182013-04-10 05:48:59 +00008773 // Find base classes from which we might inherit constructors.
8774 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008775 for (const auto &BaseIt : ClassDecl->bases())
8776 if (BaseIt.getInheritConstructors())
8777 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008778
Richard Smith185be182013-04-10 05:48:59 +00008779 // Go no further if we're not inheriting any constructors.
8780 if (InheritedBases.empty())
8781 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008782
Richard Smith185be182013-04-10 05:48:59 +00008783 // Declare the inherited constructors.
8784 InheritingConstructorInfo ICI(*this, ClassDecl);
8785 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8786 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008787}
8788
Richard Smithc2bc61b2013-03-18 21:12:30 +00008789void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8790 CXXConstructorDecl *Constructor) {
8791 CXXRecordDecl *ClassDecl = Constructor->getParent();
8792 assert(Constructor->getInheritedConstructor() &&
8793 !Constructor->doesThisDeclarationHaveABody() &&
8794 !Constructor->isDeleted());
8795
8796 SynthesizedFunctionScope Scope(*this, Constructor);
8797 DiagnosticErrorTrap Trap(Diags);
8798 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8799 Trap.hasErrorOccurred()) {
8800 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8801 << Context.getTagDeclType(ClassDecl);
8802 Constructor->setInvalidDecl();
8803 return;
8804 }
8805
8806 SourceLocation Loc = Constructor->getLocation();
8807 Constructor->setBody(new (Context) CompoundStmt(Loc));
8808
Eli Friedman276dd182013-09-05 00:02:25 +00008809 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008810 MarkVTableUsed(CurrentLocation, ClassDecl);
8811
8812 if (ASTMutationListener *L = getASTMutationListener()) {
8813 L->CompletedImplicitDefinition(Constructor);
8814 }
8815}
8816
8817
Alexis Huntf91729462011-05-12 22:46:25 +00008818Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008819Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8820 CXXRecordDecl *ClassDecl = MD->getParent();
8821
Douglas Gregorf1203042010-07-01 19:09:28 +00008822 // C++ [except.spec]p14:
8823 // An implicitly declared special member function (Clause 12) shall have
8824 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008825 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008826 if (ClassDecl->isInvalidDecl())
8827 return ExceptSpec;
8828
Douglas Gregorf1203042010-07-01 19:09:28 +00008829 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008830 for (const auto &B : ClassDecl->bases()) {
8831 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008832 continue;
8833
Aaron Ballman574705e2014-03-13 15:41:46 +00008834 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8835 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008836 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008837 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008838
Douglas Gregorf1203042010-07-01 19:09:28 +00008839 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008840 for (const auto &B : ClassDecl->vbases()) {
8841 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8842 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008843 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008844 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008845
Douglas Gregorf1203042010-07-01 19:09:28 +00008846 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008847 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008848 if (const RecordType *RecordTy
8849 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008850 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008851 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008852 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008853
Alexis Huntf91729462011-05-12 22:46:25 +00008854 return ExceptSpec;
8855}
8856
8857CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8858 // C++ [class.dtor]p2:
8859 // If a class has no user-declared destructor, a destructor is
8860 // declared implicitly. An implicitly-declared destructor is an
8861 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008862 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008863
Richard Smith8bf22e52012-11-29 01:34:07 +00008864 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8865 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008866 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008867
Douglas Gregor7454c562010-07-02 20:37:36 +00008868 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008869 CanQualType ClassType
8870 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008871 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008872 DeclarationName Name
8873 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008874 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008875 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008876 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008877 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008878 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008879 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008880 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008881 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008882
8883 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008884 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008885 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008886
Richard Smith6b02d462012-12-08 08:32:28 +00008887 AddOverriddenMethods(ClassDecl, Destructor);
8888
8889 // We don't need to use SpecialMemberIsTrivial here; triviality for
8890 // destructors is easy to compute.
8891 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8892
8893 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008894 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008895
Douglas Gregor7454c562010-07-02 20:37:36 +00008896 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008897 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008898
Douglas Gregor7454c562010-07-02 20:37:36 +00008899 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008900 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008901 PushOnScopeChains(Destructor, S, false);
8902 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008903
Douglas Gregorf1203042010-07-01 19:09:28 +00008904 return Destructor;
8905}
8906
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008907void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008908 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008909 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008910 !Destructor->doesThisDeclarationHaveABody() &&
8911 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008912 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008913 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008914 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008915
Douglas Gregor54818f02010-05-12 16:39:35 +00008916 if (Destructor->isInvalidDecl())
8917 return;
8918
Eli Friedmaneaf34142012-10-18 20:14:08 +00008919 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008920
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008921 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008922 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8923 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008924
Douglas Gregor54818f02010-05-12 16:39:35 +00008925 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008926 Diag(CurrentLocation, diag::note_member_synthesized_at)
8927 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8928
8929 Destructor->setInvalidDecl();
8930 return;
8931 }
8932
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008933 SourceLocation Loc = Destructor->getLocEnd().isValid()
8934 ? Destructor->getLocEnd()
8935 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008936 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008937 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008938 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008939
8940 if (ASTMutationListener *L = getASTMutationListener()) {
8941 L->CompletedImplicitDefinition(Destructor);
8942 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008943}
8944
Richard Smith84973e52012-04-21 18:42:51 +00008945/// \brief Perform any semantic analysis which needs to be delayed until all
8946/// pending class member declarations have been parsed.
8947void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008948 // If the context is an invalid C++ class, just suppress these checks.
8949 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8950 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008951 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008952 DelayedDestructorExceptionSpecChecks.clear();
8953 return;
8954 }
8955 }
Richard Smith84973e52012-04-21 18:42:51 +00008956}
8957
Richard Smithd3b5c9082012-07-27 04:22:15 +00008958void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8959 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008960 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008961 "adjusting dtor exception specs was introduced in c++11");
8962
Sebastian Redl623ea822011-05-19 05:13:44 +00008963 // C++11 [class.dtor]p3:
8964 // A declaration of a destructor that does not have an exception-
8965 // specification is implicitly considered to have the same exception-
8966 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008967 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008968 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008969 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008970 return;
8971
Chandler Carruth9a797572011-09-20 04:55:26 +00008972 // Replace the destructor's type, building off the existing one. Fortunately,
8973 // the only thing of interest in the destructor type is its extended info.
8974 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008975 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8976 EPI.ExceptionSpecType = EST_Unevaluated;
8977 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008978 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008979
Sebastian Redl623ea822011-05-19 05:13:44 +00008980 // FIXME: If the destructor has a body that could throw, and the newly created
8981 // spec doesn't allow exceptions, we should emit a warning, because this
8982 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008983 // However, we don't have a body or an exception specification yet, so it
8984 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008985}
8986
Pavel Labath58934982013-08-30 08:52:28 +00008987namespace {
8988/// \brief An abstract base class for all helper classes used in building the
8989// copy/move operators. These classes serve as factory functions and help us
8990// avoid using the same Expr* in the AST twice.
8991class ExprBuilder {
8992 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8993 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8994
8995protected:
8996 static Expr *assertNotNull(Expr *E) {
8997 assert(E && "Expression construction must not fail.");
8998 return E;
8999 }
9000
9001public:
9002 ExprBuilder() {}
9003 virtual ~ExprBuilder() {}
9004
9005 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9006};
9007
9008class RefBuilder: public ExprBuilder {
9009 VarDecl *Var;
9010 QualType VarType;
9011
9012public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009013 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009014 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009015 }
9016
9017 RefBuilder(VarDecl *Var, QualType VarType)
9018 : Var(Var), VarType(VarType) {}
9019};
9020
9021class ThisBuilder: public ExprBuilder {
9022public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009023 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009024 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009025 }
9026};
9027
9028class CastBuilder: public ExprBuilder {
9029 const ExprBuilder &Builder;
9030 QualType Type;
9031 ExprValueKind Kind;
9032 const CXXCastPath &Path;
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(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9037 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009038 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009039 }
9040
9041 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9042 const CXXCastPath &Path)
9043 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9044};
9045
9046class DerefBuilder: public ExprBuilder {
9047 const ExprBuilder &Builder;
9048
9049public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009050 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009051 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009052 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009053 }
9054
9055 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9056};
9057
9058class MemberBuilder: public ExprBuilder {
9059 const ExprBuilder &Builder;
9060 QualType Type;
9061 CXXScopeSpec SS;
9062 bool IsArrow;
9063 LookupResult &MemberLookup;
9064
9065public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009066 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009067 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009068 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009069 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009070 }
9071
9072 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9073 LookupResult &MemberLookup)
9074 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9075 MemberLookup(MemberLookup) {}
9076};
9077
9078class MoveCastBuilder: public ExprBuilder {
9079 const ExprBuilder &Builder;
9080
9081public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009082 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009083 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9084 }
9085
9086 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9087};
9088
9089class LvalueConvBuilder: public ExprBuilder {
9090 const ExprBuilder &Builder;
9091
9092public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009093 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009094 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009095 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009096 }
9097
9098 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9099};
9100
9101class SubscriptBuilder: public ExprBuilder {
9102 const ExprBuilder &Base;
9103 const ExprBuilder &Index;
9104
9105public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009106 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009107 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009108 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009109 }
9110
9111 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9112 : Base(Base), Index(Index) {}
9113};
9114
9115} // end anonymous namespace
9116
Richard Smith41ae3282012-11-14 00:50:40 +00009117/// When generating a defaulted copy or move assignment operator, if a field
9118/// should be copied with __builtin_memcpy rather than via explicit assignments,
9119/// do so. This optimization only applies for arrays of scalars, and for arrays
9120/// of class type where the selected copy/move-assignment operator is trivial.
9121static StmtResult
9122buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009123 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009124 // Compute the size of the memory buffer to be copied.
9125 QualType SizeType = S.Context.getSizeType();
9126 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9127 S.Context.getTypeSizeInChars(T).getQuantity());
9128
9129 // Take the address of the field references for "from" and "to". We
9130 // directly construct UnaryOperators here because semantic analysis
9131 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009132 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009133 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9134 S.Context.getPointerType(From->getType()),
9135 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009136 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009137 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9138 S.Context.getPointerType(To->getType()),
9139 VK_RValue, OK_Ordinary, Loc);
9140
9141 const Type *E = T->getBaseElementTypeUnsafe();
9142 bool NeedsCollectableMemCpy =
9143 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9144
9145 // Create a reference to the __builtin_objc_memmove_collectable function
9146 StringRef MemCpyName = NeedsCollectableMemCpy ?
9147 "__builtin_objc_memmove_collectable" :
9148 "__builtin_memcpy";
9149 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9150 Sema::LookupOrdinaryName);
9151 S.LookupName(R, S.TUScope, true);
9152
9153 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9154 if (!MemCpy)
9155 // Something went horribly wrong earlier, and we will have complained
9156 // about it.
9157 return StmtError();
9158
9159 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009160 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009161 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9162
9163 Expr *CallArgs[] = {
9164 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9165 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009166 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009167 Loc, CallArgs, Loc);
9168
9169 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009170 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009171}
9172
Sebastian Redl22653ba2011-08-30 19:58:05 +00009173/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009174/// \c To.
9175///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009176/// This routine is used to copy/move the members of a class with an
9177/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009178/// copied are arrays, this routine builds for loops to copy them.
9179///
9180/// \param S The Sema object used for type-checking.
9181///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009182/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009183///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009184/// \param T The type of the expressions being copied/moved. Both expressions
9185/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009186///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009187/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009188///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009189/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009190///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009191/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009192/// Otherwise, it's a non-static member subobject.
9193///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009194/// \param Copying Whether we're copying or moving.
9195///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009196/// \param Depth Internal parameter recording the depth of the recursion.
9197///
Richard Smith41ae3282012-11-14 00:50:40 +00009198/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9199/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009200static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009201buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009202 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009203 bool CopyingBaseSubobject, bool Copying,
9204 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009205 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009206 // Each subobject is assigned in the manner appropriate to its type:
9207 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009208 // - if the subobject is of class type, as if by a call to operator= with
9209 // the subobject as the object expression and the corresponding
9210 // subobject of x as a single function argument (as if by explicit
9211 // qualification; that is, ignoring any possible virtual overriding
9212 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009213 //
9214 // C++03 [class.copy]p13:
9215 // - if the subobject is of class type, the copy assignment operator for
9216 // the class is used (as if by explicit qualification; that is,
9217 // ignoring any possible virtual overriding functions in more derived
9218 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009219 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9220 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009221
Douglas Gregorb139cd52010-05-01 20:49:11 +00009222 // Look for operator=.
9223 DeclarationName Name
9224 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9225 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9226 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009227
Richard Smith52c0b582012-11-13 00:54:12 +00009228 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9229 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009230 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009231 LookupResult::Filter F = OpLookup.makeFilter();
9232 while (F.hasNext()) {
9233 NamedDecl *D = F.next();
9234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9235 if (Method->isCopyAssignmentOperator() ||
9236 (!Copying && Method->isMoveAssignmentOperator()))
9237 continue;
9238
9239 F.erase();
9240 }
9241 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009242 }
Richard Smith52c0b582012-11-13 00:54:12 +00009243
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009244 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009245 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009246 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009247 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009248 // ambiguities), we need to cast "this" to that subobject type; to
9249 // ensure that we don't go through the virtual call mechanism, we need
9250 // to qualify the operator= name with the base class (see below). However,
9251 // this means that if the base class has a protected copy assignment
9252 // operator, the protected member access check will fail. So, we
9253 // rewrite "protected" access to "public" access in this case, since we
9254 // know by construction that we're calling from a derived class.
9255 if (CopyingBaseSubobject) {
9256 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9257 L != LEnd; ++L) {
9258 if (L.getAccess() == AS_protected)
9259 L.setAccess(AS_public);
9260 }
9261 }
Richard Smith52c0b582012-11-13 00:54:12 +00009262
Douglas Gregorb139cd52010-05-01 20:49:11 +00009263 // Create the nested-name-specifier that will be used to qualify the
9264 // reference to operator=; this is required to suppress the virtual
9265 // call mechanism.
9266 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009267 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009268 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009269 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009270 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009271 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009272
Douglas Gregorb139cd52010-05-01 20:49:11 +00009273 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009274 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009275 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9276 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009277 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009278 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009279 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009280 /*SuppressQualifierCheck=*/true);
9281 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009282 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009283
Douglas Gregorb139cd52010-05-01 20:49:11 +00009284 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009285
Pavel Labath58934982013-08-30 08:52:28 +00009286 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009287 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009288 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009289 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009290 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009291 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009292
Richard Smith41ae3282012-11-14 00:50:40 +00009293 // If we built a call to a trivial 'operator=' while copying an array,
9294 // bail out. We'll replace the whole shebang with a memcpy.
9295 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9296 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009297 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009298
Richard Smith52c0b582012-11-13 00:54:12 +00009299 // Convert to an expression-statement, and clean up any produced
9300 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009301 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009302 }
John McCallab8c2732010-03-16 06:11:48 +00009303
Richard Smith52c0b582012-11-13 00:54:12 +00009304 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009305 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009306 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009307 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009308 ExprResult Assignment = S.CreateBuiltinBinOp(
9309 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009310 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009311 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009312 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009313 }
Richard Smith52c0b582012-11-13 00:54:12 +00009314
9315 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009316 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009317
Douglas Gregorb139cd52010-05-01 20:49:11 +00009318 // Construct a loop over the array bounds, e.g.,
9319 //
9320 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9321 //
9322 // that will copy each of the array elements.
9323 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009324
Douglas Gregorb139cd52010-05-01 20:49:11 +00009325 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009326 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009327 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009328 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009329 llvm::raw_svector_ostream OS(Str);
9330 OS << "__i" << Depth;
9331 IterationVarName = &S.Context.Idents.get(OS.str());
9332 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009333 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009334 IterationVarName, SizeType,
9335 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009336 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009337
Douglas Gregorb139cd52010-05-01 20:49:11 +00009338 // Initialize the iteration variable to zero.
9339 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009340 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009341
Pavel Labath58934982013-08-30 08:52:28 +00009342 // Creates a reference to the iteration variable.
9343 RefBuilder IterationVarRef(IterationVar, SizeType);
9344 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009345
Douglas Gregorb139cd52010-05-01 20:49:11 +00009346 // Create the DeclStmt that holds the iteration variable.
9347 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009348
Douglas Gregorb139cd52010-05-01 20:49:11 +00009349 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009350 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9351 MoveCastBuilder FromIndexMove(FromIndexCopy);
9352 const ExprBuilder *FromIndex;
9353 if (Copying)
9354 FromIndex = &FromIndexCopy;
9355 else
9356 FromIndex = &FromIndexMove;
9357
9358 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009359
9360 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009361 StmtResult Copy =
9362 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009363 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009364 Copying, Depth + 1);
9365 // Bail out if copying fails or if we determined that we should use memcpy.
9366 if (Copy.isInvalid() || !Copy.get())
9367 return Copy;
9368
9369 // Create the comparison against the array bound.
9370 llvm::APInt Upper
9371 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9372 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009373 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009374 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9375 BO_NE, S.Context.BoolTy,
9376 VK_RValue, OK_Ordinary, Loc, false);
9377
9378 // Create the pre-increment of the iteration variable.
9379 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009380 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9381 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009382
Douglas Gregorb139cd52010-05-01 20:49:11 +00009383 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009384 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009385 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009386 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009387 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009388}
9389
Richard Smith41ae3282012-11-14 00:50:40 +00009390static StmtResult
9391buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009392 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009393 bool CopyingBaseSubobject, bool Copying) {
9394 // Maybe we should use a memcpy?
9395 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9396 T.isTriviallyCopyableType(S.Context))
9397 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9398
9399 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9400 CopyingBaseSubobject,
9401 Copying, 0));
9402
9403 // If we ended up picking a trivial assignment operator for an array of a
9404 // non-trivially-copyable class type, just emit a memcpy.
9405 if (!Result.isInvalid() && !Result.get())
9406 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9407
9408 return Result;
9409}
9410
Richard Smithd3b5c9082012-07-27 04:22:15 +00009411Sema::ImplicitExceptionSpecification
9412Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9413 CXXRecordDecl *ClassDecl = MD->getParent();
9414
9415 ImplicitExceptionSpecification ExceptSpec(*this);
9416 if (ClassDecl->isInvalidDecl())
9417 return ExceptSpec;
9418
9419 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009420 assert(T->getNumParams() == 1 && "not a copy assignment op");
9421 unsigned ArgQuals =
9422 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009423
Douglas Gregor68e11362010-07-01 17:48:08 +00009424 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009425 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009426 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009427
9428 // It is unspecified whether or not an implicit copy assignment operator
9429 // attempts to deduplicate calls to assignment operators of virtual bases are
9430 // made. As such, this exception specification is effectively unspecified.
9431 // Based on a similar decision made for constness in C++0x, we're erring on
9432 // the side of assuming such calls to be made regardless of whether they
9433 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009434 for (const auto &Base : ClassDecl->bases()) {
9435 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009436 continue;
9437
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009438 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009439 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009440 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9441 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009442 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009443 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009444
Aaron Ballman445a9392014-03-13 16:15:17 +00009445 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009446 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009447 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009448 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9449 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009450 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009451 }
9452
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009453 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009454 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009455 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9456 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009457 LookupCopyingAssignment(FieldClassDecl,
9458 ArgQuals | FieldType.getCVRQualifiers(),
9459 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009460 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009461 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009462 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009463
Richard Smithd3b5c9082012-07-27 04:22:15 +00009464 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009465}
9466
9467CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9468 // Note: The following rules are largely analoguous to the copy
9469 // constructor rules. Note that virtual bases are not taken into account
9470 // for determining the argument type of the operator. Note also that
9471 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009472 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009473
Richard Smith8bf22e52012-11-29 01:34:07 +00009474 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9475 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009476 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009477
Alexis Hunt119f3652011-05-14 05:23:20 +00009478 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9479 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009480 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9481 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009482 ArgType = ArgType.withConst();
9483 ArgType = Context.getLValueReferenceType(ArgType);
9484
Richard Smith99005e62013-05-07 03:19:20 +00009485 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9486 CXXCopyAssignment,
9487 Const);
9488
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009489 // An implicitly-declared copy assignment operator is an inline public
9490 // member of its class.
9491 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009492 SourceLocation ClassLoc = ClassDecl->getLocation();
9493 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009494 CXXMethodDecl *CopyAssignment =
9495 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009496 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9497 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009498 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009499 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009500 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009501
9502 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009503 FunctionProtoType::ExtProtoInfo EPI =
9504 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009505 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009506
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009507 // Add the parameter to the operator.
9508 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009509 ClassLoc, ClassLoc,
9510 /*Id=*/nullptr, ArgType,
9511 /*TInfo=*/nullptr, SC_None,
9512 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009513 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009514
Richard Smith6b02d462012-12-08 08:32:28 +00009515 AddOverriddenMethods(ClassDecl, CopyAssignment);
9516
9517 CopyAssignment->setTrivial(
9518 ClassDecl->needsOverloadResolutionForCopyAssignment()
9519 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9520 : ClassDecl->hasTrivialCopyAssignment());
9521
Richard Smith852265f2012-03-30 20:53:28 +00009522 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009523 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009524
Richard Smith6b02d462012-12-08 08:32:28 +00009525 // Note that we have added this copy-assignment operator.
9526 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9527
9528 if (Scope *S = getScopeForContext(ClassDecl))
9529 PushOnScopeChains(CopyAssignment, S, false);
9530 ClassDecl->addDecl(CopyAssignment);
9531
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009532 return CopyAssignment;
9533}
9534
Richard Smithd577fbb2013-06-13 03:23:42 +00009535/// Diagnose an implicit copy operation for a class which is odr-used, but
9536/// which is deprecated because the class has a user-declared copy constructor,
9537/// copy assignment operator, or destructor.
9538static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9539 SourceLocation UseLoc) {
9540 assert(CopyOp->isImplicit());
9541
9542 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009543 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009544
9545 // In Microsoft mode, assignment operations don't affect constructors and
9546 // vice versa.
9547 if (RD->hasUserDeclaredDestructor()) {
9548 UserDeclaredOperation = RD->getDestructor();
9549 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9550 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009551 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009552 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009553 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009554 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009555 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009556 break;
9557 }
9558 }
9559 assert(UserDeclaredOperation);
9560 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9561 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009562 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009563 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009564 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009565 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009566 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009567 break;
9568 }
9569 }
9570 assert(UserDeclaredOperation);
9571 }
9572
9573 if (UserDeclaredOperation) {
9574 S.Diag(UserDeclaredOperation->getLocation(),
9575 diag::warn_deprecated_copy_operation)
9576 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9577 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9578 S.Diag(UseLoc, diag::note_member_synthesized_at)
9579 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9580 : Sema::CXXCopyAssignment)
9581 << RD;
9582 }
9583}
9584
Douglas Gregorb139cd52010-05-01 20:49:11 +00009585void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9586 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009587 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009588 CopyAssignOperator->isOverloadedOperator() &&
9589 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009590 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9591 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009592 "DefineImplicitCopyAssignment called for wrong function");
9593
9594 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9595
9596 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9597 CopyAssignOperator->setInvalidDecl();
9598 return;
9599 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009600
9601 // C++11 [class.copy]p18:
9602 // The [definition of an implicitly declared copy assignment operator] is
9603 // deprecated if the class has a user-declared copy constructor or a
9604 // user-declared destructor.
9605 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9606 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9607
Eli Friedman276dd182013-09-05 00:02:25 +00009608 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009609
Eli Friedmaneaf34142012-10-18 20:14:08 +00009610 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009611 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009612
9613 // C++0x [class.copy]p30:
9614 // The implicitly-defined or explicitly-defaulted copy assignment operator
9615 // for a non-union class X performs memberwise copy assignment of its
9616 // subobjects. The direct base classes of X are assigned first, in the
9617 // order of their declaration in the base-specifier-list, and then the
9618 // immediate non-static data members of X are assigned, in the order in
9619 // which they were declared in the class definition.
9620
9621 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009622 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009623
9624 // The parameter for the "other" object, which we are copying from.
9625 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9626 Qualifiers OtherQuals = Other->getType().getQualifiers();
9627 QualType OtherRefType = Other->getType();
9628 if (const LValueReferenceType *OtherRef
9629 = OtherRefType->getAs<LValueReferenceType>()) {
9630 OtherRefType = OtherRef->getPointeeType();
9631 OtherQuals = OtherRefType.getQualifiers();
9632 }
9633
9634 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009635 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9636 ? CopyAssignOperator->getLocEnd()
9637 : CopyAssignOperator->getLocation();
9638
Pavel Labath58934982013-08-30 08:52:28 +00009639 // Builds a DeclRefExpr for the "other" object.
9640 RefBuilder OtherRef(Other, OtherRefType);
9641
9642 // Builds the "this" pointer.
9643 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009644
9645 // Assign base classes.
9646 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009647 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009648 // Form the assignment:
9649 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009650 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009651 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009652 Invalid = true;
9653 continue;
9654 }
9655
John McCallcf142162010-08-07 06:22:56 +00009656 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009657 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009658
Douglas Gregorb139cd52010-05-01 20:49:11 +00009659 // Construct the "from" expression, which is an implicit cast to the
9660 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009661 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9662 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009663
9664 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009665 DerefBuilder DerefThis(This);
9666 CastBuilder To(DerefThis,
9667 Context.getCVRQualifiedType(
9668 BaseType, CopyAssignOperator->getTypeQualifiers()),
9669 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009670
9671 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009672 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009673 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009674 /*CopyingBaseSubobject=*/true,
9675 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009676 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009677 Diag(CurrentLocation, diag::note_member_synthesized_at)
9678 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9679 CopyAssignOperator->setInvalidDecl();
9680 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009681 }
9682
9683 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009684 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009685 }
9686
Douglas Gregorb139cd52010-05-01 20:49:11 +00009687 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009688 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009689 if (Field->isUnnamedBitfield())
9690 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009691
9692 if (Field->isInvalidDecl()) {
9693 Invalid = true;
9694 continue;
9695 }
9696
Douglas Gregorb139cd52010-05-01 20:49:11 +00009697 // Check for members of reference type; we can't copy those.
9698 if (Field->getType()->isReferenceType()) {
9699 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9700 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9701 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009702 Diag(CurrentLocation, diag::note_member_synthesized_at)
9703 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009704 Invalid = true;
9705 continue;
9706 }
9707
9708 // Check for members of const-qualified, non-class type.
9709 QualType BaseType = Context.getBaseElementType(Field->getType());
9710 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9711 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9712 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9713 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009714 Diag(CurrentLocation, diag::note_member_synthesized_at)
9715 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009716 Invalid = true;
9717 continue;
9718 }
John McCall1b1a1db2011-06-17 00:18:42 +00009719
9720 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009721 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9722 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009723
9724 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009725 if (FieldType->isIncompleteArrayType()) {
9726 assert(ClassDecl->hasFlexibleArrayMember() &&
9727 "Incomplete array type is not valid");
9728 continue;
9729 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009730
9731 // Build references to the field in the object we're copying from and to.
9732 CXXScopeSpec SS; // Intentionally empty
9733 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9734 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009735 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009736 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009737
9738 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9739
9740 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009741
Douglas Gregorb139cd52010-05-01 20:49:11 +00009742 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009743 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009744 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009745 /*CopyingBaseSubobject=*/false,
9746 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009747 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009748 Diag(CurrentLocation, diag::note_member_synthesized_at)
9749 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9750 CopyAssignOperator->setInvalidDecl();
9751 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009752 }
9753
9754 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009755 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009756 }
9757
9758 if (!Invalid) {
9759 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009760 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009761
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009762 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009763 if (Return.isInvalid())
9764 Invalid = true;
9765 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009766 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009767
9768 if (Trap.hasErrorOccurred()) {
9769 Diag(CurrentLocation, diag::note_member_synthesized_at)
9770 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9771 Invalid = true;
9772 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009773 }
9774 }
9775
9776 if (Invalid) {
9777 CopyAssignOperator->setInvalidDecl();
9778 return;
9779 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009780
9781 StmtResult Body;
9782 {
9783 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009784 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009785 /*isStmtExpr=*/false);
9786 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9787 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009788 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009789
9790 if (ASTMutationListener *L = getASTMutationListener()) {
9791 L->CompletedImplicitDefinition(CopyAssignOperator);
9792 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009793}
9794
Sebastian Redl22653ba2011-08-30 19:58:05 +00009795Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009796Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9797 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009798
Richard Smithd3b5c9082012-07-27 04:22:15 +00009799 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009800 if (ClassDecl->isInvalidDecl())
9801 return ExceptSpec;
9802
9803 // C++0x [except.spec]p14:
9804 // An implicitly declared special member function (Clause 12) shall have an
9805 // exception-specification. [...]
9806
9807 // It is unspecified whether or not an implicit move assignment operator
9808 // attempts to deduplicate calls to assignment operators of virtual bases are
9809 // made. As such, this exception specification is effectively unspecified.
9810 // Based on a similar decision made for constness in C++0x, we're erring on
9811 // the side of assuming such calls to be made regardless of whether they
9812 // actually happen.
9813 // Note that a move constructor is not implicitly declared when there are
9814 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009815 for (const auto &Base : ClassDecl->bases()) {
9816 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009817 continue;
9818
9819 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009820 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009821 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009822 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009823 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009824 }
9825
Aaron Ballman445a9392014-03-13 16:15:17 +00009826 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009827 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009828 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009829 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009830 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009831 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009832 }
9833
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009834 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009835 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009836 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009837 if (CXXMethodDecl *MoveAssign =
9838 LookupMovingAssignment(FieldClassDecl,
9839 FieldType.getCVRQualifiers(),
9840 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009841 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009842 }
9843 }
9844
9845 return ExceptSpec;
9846}
9847
9848CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009849 assert(ClassDecl->needsImplicitMoveAssignment());
9850
Richard Smith8bf22e52012-11-29 01:34:07 +00009851 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9852 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009853 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009854
Sebastian Redl22653ba2011-08-30 19:58:05 +00009855 // Note: The following rules are largely analoguous to the move
9856 // constructor rules.
9857
Sebastian Redl22653ba2011-08-30 19:58:05 +00009858 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9859 QualType RetType = Context.getLValueReferenceType(ArgType);
9860 ArgType = Context.getRValueReferenceType(ArgType);
9861
Richard Smith99005e62013-05-07 03:19:20 +00009862 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9863 CXXMoveAssignment,
9864 false);
9865
Sebastian Redl22653ba2011-08-30 19:58:05 +00009866 // An implicitly-declared move assignment operator is an inline public
9867 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009868 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9869 SourceLocation ClassLoc = ClassDecl->getLocation();
9870 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009871 CXXMethodDecl *MoveAssignment =
9872 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009873 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009874 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009875 MoveAssignment->setAccess(AS_public);
9876 MoveAssignment->setDefaulted();
9877 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009878
Richard Smithd3b5c9082012-07-27 04:22:15 +00009879 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009880 FunctionProtoType::ExtProtoInfo EPI =
9881 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009882 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009883
Sebastian Redl22653ba2011-08-30 19:58:05 +00009884 // Add the parameter to the operator.
9885 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009886 ClassLoc, ClassLoc,
9887 /*Id=*/nullptr, ArgType,
9888 /*TInfo=*/nullptr, SC_None,
9889 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009890 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009891
Richard Smith6b02d462012-12-08 08:32:28 +00009892 AddOverriddenMethods(ClassDecl, MoveAssignment);
9893
9894 MoveAssignment->setTrivial(
9895 ClassDecl->needsOverloadResolutionForMoveAssignment()
9896 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9897 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009898
Richard Smithd951a1d2012-02-18 02:02:13 +00009899 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009900 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9901 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009902 }
9903
Richard Smith6b02d462012-12-08 08:32:28 +00009904 // Note that we have added this copy-assignment operator.
9905 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9906
Sebastian Redl22653ba2011-08-30 19:58:05 +00009907 if (Scope *S = getScopeForContext(ClassDecl))
9908 PushOnScopeChains(MoveAssignment, S, false);
9909 ClassDecl->addDecl(MoveAssignment);
9910
Sebastian Redl22653ba2011-08-30 19:58:05 +00009911 return MoveAssignment;
9912}
9913
Richard Smithb2504bd2013-11-04 04:26:14 +00009914/// Check if we're implicitly defining a move assignment operator for a class
9915/// with virtual bases. Such a move assignment might move-assign the virtual
9916/// base multiple times.
9917static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9918 SourceLocation CurrentLocation) {
9919 assert(!Class->isDependentContext() && "should not define dependent move");
9920
9921 // Only a virtual base could get implicitly move-assigned multiple times.
9922 // Only a non-trivial move assignment can observe this. We only want to
9923 // diagnose if we implicitly define an assignment operator that assigns
9924 // two base classes, both of which move-assign the same virtual base.
9925 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9926 Class->getNumBases() < 2)
9927 return;
9928
9929 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9930 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9931 VBaseMap VBases;
9932
Aaron Ballman574705e2014-03-13 15:41:46 +00009933 for (auto &BI : Class->bases()) {
9934 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009935 while (!Worklist.empty()) {
9936 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9937 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9938
9939 // If the base has no non-trivial move assignment operators,
9940 // we don't care about moves from it.
9941 if (!Base->hasNonTrivialMoveAssignment())
9942 continue;
9943
9944 // If there's nothing virtual here, skip it.
9945 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9946 continue;
9947
9948 // If we're not actually going to call a move assignment for this base,
9949 // or the selected move assignment is trivial, skip it.
9950 Sema::SpecialMemberOverloadResult *SMOR =
9951 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9952 /*ConstArg*/false, /*VolatileArg*/false,
9953 /*RValueThis*/true, /*ConstThis*/false,
9954 /*VolatileThis*/false);
9955 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9956 !SMOR->getMethod()->isMoveAssignmentOperator())
9957 continue;
9958
9959 if (BaseSpec->isVirtual()) {
9960 // We're going to move-assign this virtual base, and its move
9961 // assignment operator is not trivial. If this can happen for
9962 // multiple distinct direct bases of Class, diagnose it. (If it
9963 // only happens in one base, we'll diagnose it when synthesizing
9964 // that base class's move assignment operator.)
9965 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009966 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009967 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009968 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009969 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9970 << Class << Base;
9971 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9972 << (Base->getCanonicalDecl() ==
9973 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9974 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009975 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009976 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009977 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9978 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009979
9980 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +00009981 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +00009982 }
9983 } else {
9984 // Only walk over bases that have defaulted move assignment operators.
9985 // We assume that any user-provided move assignment operator handles
9986 // the multiple-moves-of-vbase case itself somehow.
9987 if (!SMOR->getMethod()->isDefaulted())
9988 continue;
9989
9990 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009991 for (auto &BI : Base->bases())
9992 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009993 }
9994 }
9995 }
9996}
9997
Sebastian Redl22653ba2011-08-30 19:58:05 +00009998void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9999 CXXMethodDecl *MoveAssignOperator) {
10000 assert((MoveAssignOperator->isDefaulted() &&
10001 MoveAssignOperator->isOverloadedOperator() &&
10002 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010003 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10004 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010005 "DefineImplicitMoveAssignment called for wrong function");
10006
10007 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10008
10009 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10010 MoveAssignOperator->setInvalidDecl();
10011 return;
10012 }
10013
Eli Friedman276dd182013-09-05 00:02:25 +000010014 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010015
Eli Friedmaneaf34142012-10-18 20:14:08 +000010016 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010017 DiagnosticErrorTrap Trap(Diags);
10018
10019 // C++0x [class.copy]p28:
10020 // The implicitly-defined or move assignment operator for a non-union class
10021 // X performs memberwise move assignment of its subobjects. The direct base
10022 // classes of X are assigned first, in the order of their declaration in the
10023 // base-specifier-list, and then the immediate non-static data members of X
10024 // are assigned, in the order in which they were declared in the class
10025 // definition.
10026
Richard Smithb2504bd2013-11-04 04:26:14 +000010027 // Issue a warning if our implicit move assignment operator will move
10028 // from a virtual base more than once.
10029 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010030
Sebastian Redl22653ba2011-08-30 19:58:05 +000010031 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010032 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010033
10034 // The parameter for the "other" object, which we are move from.
10035 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10036 QualType OtherRefType = Other->getType()->
10037 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010038 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010039 "Bad argument type of defaulted move assignment");
10040
10041 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010042 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10043 ? MoveAssignOperator->getLocEnd()
10044 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010045
Pavel Labath58934982013-08-30 08:52:28 +000010046 // Builds a reference to the "other" object.
10047 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010048 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010049 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010050
Pavel Labath58934982013-08-30 08:52:28 +000010051 // Builds the "this" pointer.
10052 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010053
Sebastian Redl22653ba2011-08-30 19:58:05 +000010054 // Assign base classes.
10055 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010056 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010057 // C++11 [class.copy]p28:
10058 // It is unspecified whether subobjects representing virtual base classes
10059 // are assigned more than once by the implicitly-defined copy assignment
10060 // operator.
10061 // FIXME: Do not assign to a vbase that will be assigned by some other base
10062 // class. For a move-assignment, this can result in the vbase being moved
10063 // multiple times.
10064
Sebastian Redl22653ba2011-08-30 19:58:05 +000010065 // Form the assignment:
10066 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010067 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010068 if (!BaseType->isRecordType()) {
10069 Invalid = true;
10070 continue;
10071 }
10072
10073 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010074 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010075
10076 // Construct the "from" expression, which is an implicit cast to the
10077 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010078 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010079
10080 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010081 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010082
10083 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010084 CastBuilder To(DerefThis,
10085 Context.getCVRQualifiedType(
10086 BaseType, MoveAssignOperator->getTypeQualifiers()),
10087 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010088
10089 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010090 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010091 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010092 /*CopyingBaseSubobject=*/true,
10093 /*Copying=*/false);
10094 if (Move.isInvalid()) {
10095 Diag(CurrentLocation, diag::note_member_synthesized_at)
10096 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10097 MoveAssignOperator->setInvalidDecl();
10098 return;
10099 }
10100
10101 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010102 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010103 }
10104
Sebastian Redl22653ba2011-08-30 19:58:05 +000010105 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010106 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010107 if (Field->isUnnamedBitfield())
10108 continue;
10109
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010110 if (Field->isInvalidDecl()) {
10111 Invalid = true;
10112 continue;
10113 }
10114
Sebastian Redl22653ba2011-08-30 19:58:05 +000010115 // Check for members of reference type; we can't move those.
10116 if (Field->getType()->isReferenceType()) {
10117 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10118 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10119 Diag(Field->getLocation(), diag::note_declared_at);
10120 Diag(CurrentLocation, diag::note_member_synthesized_at)
10121 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10122 Invalid = true;
10123 continue;
10124 }
10125
10126 // Check for members of const-qualified, non-class type.
10127 QualType BaseType = Context.getBaseElementType(Field->getType());
10128 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10129 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10130 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10131 Diag(Field->getLocation(), diag::note_declared_at);
10132 Diag(CurrentLocation, diag::note_member_synthesized_at)
10133 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10134 Invalid = true;
10135 continue;
10136 }
10137
10138 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010139 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10140 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010141
10142 QualType FieldType = Field->getType().getNonReferenceType();
10143 if (FieldType->isIncompleteArrayType()) {
10144 assert(ClassDecl->hasFlexibleArrayMember() &&
10145 "Incomplete array type is not valid");
10146 continue;
10147 }
10148
10149 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010150 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10151 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010152 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010153 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010154 MemberBuilder From(MoveOther, OtherRefType,
10155 /*IsArrow=*/false, MemberLookup);
10156 MemberBuilder To(This, getCurrentThisType(),
10157 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010158
Pavel Labath58934982013-08-30 08:52:28 +000010159 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010160 "Member reference with rvalue base must be rvalue except for reference "
10161 "members, which aren't allowed for move assignment.");
10162
Sebastian Redl22653ba2011-08-30 19:58:05 +000010163 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010164 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010165 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010166 /*CopyingBaseSubobject=*/false,
10167 /*Copying=*/false);
10168 if (Move.isInvalid()) {
10169 Diag(CurrentLocation, diag::note_member_synthesized_at)
10170 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10171 MoveAssignOperator->setInvalidDecl();
10172 return;
10173 }
Richard Smith11d19592012-11-12 23:33:00 +000010174
Sebastian Redl22653ba2011-08-30 19:58:05 +000010175 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010176 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010177 }
10178
10179 if (!Invalid) {
10180 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010181 ExprResult ThisObj =
10182 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10183
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010184 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010185 if (Return.isInvalid())
10186 Invalid = true;
10187 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010188 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010189
10190 if (Trap.hasErrorOccurred()) {
10191 Diag(CurrentLocation, diag::note_member_synthesized_at)
10192 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10193 Invalid = true;
10194 }
10195 }
10196 }
10197
10198 if (Invalid) {
10199 MoveAssignOperator->setInvalidDecl();
10200 return;
10201 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010202
10203 StmtResult Body;
10204 {
10205 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010206 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010207 /*isStmtExpr=*/false);
10208 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10209 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010210 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010211
10212 if (ASTMutationListener *L = getASTMutationListener()) {
10213 L->CompletedImplicitDefinition(MoveAssignOperator);
10214 }
10215}
10216
Richard Smithd3b5c9082012-07-27 04:22:15 +000010217Sema::ImplicitExceptionSpecification
10218Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10219 CXXRecordDecl *ClassDecl = MD->getParent();
10220
10221 ImplicitExceptionSpecification ExceptSpec(*this);
10222 if (ClassDecl->isInvalidDecl())
10223 return ExceptSpec;
10224
10225 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010226 assert(T->getNumParams() >= 1 && "not a copy ctor");
10227 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010228
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010229 // C++ [except.spec]p14:
10230 // An implicitly declared special member function (Clause 12) shall have an
10231 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010232 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010233 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010234 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010235 continue;
10236
Douglas Gregora6d69502010-07-02 23:41:54 +000010237 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010238 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010239 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010240 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010241 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010242 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010243 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010244 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010245 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010246 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010247 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010248 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010249 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010250 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010251 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010252 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10253 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010254 LookupCopyingConstructor(FieldClassDecl,
10255 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010256 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010257 }
10258 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010259
Richard Smithd3b5c9082012-07-27 04:22:15 +000010260 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010261}
10262
10263CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10264 CXXRecordDecl *ClassDecl) {
10265 // C++ [class.copy]p4:
10266 // If the class definition does not explicitly declare a copy
10267 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010268 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010269
Richard Smith8bf22e52012-11-29 01:34:07 +000010270 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10271 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010272 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010273
Alexis Hunt913820d2011-05-13 06:10:58 +000010274 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10275 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010276 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010277 if (Const)
10278 ArgType = ArgType.withConst();
10279 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010280
Richard Smithb5800092012-06-10 05:43:50 +000010281 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10282 CXXCopyConstructor,
10283 Const);
10284
Douglas Gregor54be3392010-07-01 17:57:27 +000010285 DeclarationName Name
10286 = Context.DeclarationNames.getCXXConstructorName(
10287 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010288 SourceLocation ClassLoc = ClassDecl->getLocation();
10289 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010290
10291 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010292 // member of its class.
10293 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010294 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010295 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010296 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010297 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010298 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010299
Richard Smithd3b5c9082012-07-27 04:22:15 +000010300 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010301 FunctionProtoType::ExtProtoInfo EPI =
10302 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010303 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010304 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010305
Douglas Gregor54be3392010-07-01 17:57:27 +000010306 // Add the parameter to the constructor.
10307 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010308 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010309 /*IdentifierInfo=*/nullptr,
10310 ArgType, /*TInfo=*/nullptr,
10311 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010312 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010313
Richard Smith6b02d462012-12-08 08:32:28 +000010314 CopyConstructor->setTrivial(
10315 ClassDecl->needsOverloadResolutionForCopyConstructor()
10316 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10317 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010318
Richard Smith852265f2012-03-30 20:53:28 +000010319 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010320 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010321
Richard Smith6b02d462012-12-08 08:32:28 +000010322 // Note that we have declared this constructor.
10323 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10324
10325 if (Scope *S = getScopeForContext(ClassDecl))
10326 PushOnScopeChains(CopyConstructor, S, false);
10327 ClassDecl->addDecl(CopyConstructor);
10328
Douglas Gregor54be3392010-07-01 17:57:27 +000010329 return CopyConstructor;
10330}
10331
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010332void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010333 CXXConstructorDecl *CopyConstructor) {
10334 assert((CopyConstructor->isDefaulted() &&
10335 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010336 !CopyConstructor->doesThisDeclarationHaveABody() &&
10337 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010338 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010339
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010340 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010341 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010342
Richard Smithd577fbb2013-06-13 03:23:42 +000010343 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010344 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010345 // deprecated if the class has a user-declared copy assignment operator
10346 // or a user-declared destructor.
10347 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10348 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10349
Eli Friedmaneaf34142012-10-18 20:14:08 +000010350 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010351 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010352
David Blaikie3fc2f912013-01-17 05:26:25 +000010353 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010354 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010355 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010356 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010357 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010358 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010359 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10360 ? CopyConstructor->getLocEnd()
10361 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010362 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010363 CopyConstructor->setBody(
10364 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010365 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010366
Eli Friedman276dd182013-09-05 00:02:25 +000010367 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010368 if (ASTMutationListener *L = getASTMutationListener()) {
10369 L->CompletedImplicitDefinition(CopyConstructor);
10370 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010371}
10372
Sebastian Redl22653ba2011-08-30 19:58:05 +000010373Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010374Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10375 CXXRecordDecl *ClassDecl = MD->getParent();
10376
Sebastian Redl22653ba2011-08-30 19:58:05 +000010377 // C++ [except.spec]p14:
10378 // An implicitly declared special member function (Clause 12) shall have an
10379 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010380 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010381 if (ClassDecl->isInvalidDecl())
10382 return ExceptSpec;
10383
10384 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010385 for (const auto &B : ClassDecl->bases()) {
10386 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010387 continue;
10388
Aaron Ballman574705e2014-03-13 15:41:46 +000010389 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010390 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010391 CXXConstructorDecl *Constructor =
10392 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010393 // If this is a deleted function, add it anyway. This might be conformant
10394 // with the standard. This might not. I'm not sure. It might not matter.
10395 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010396 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010397 }
10398 }
10399
10400 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010401 for (const auto &B : ClassDecl->vbases()) {
10402 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010403 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010404 CXXConstructorDecl *Constructor =
10405 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010406 // If this is a deleted function, add it anyway. This might be conformant
10407 // with the standard. This might not. I'm not sure. It might not matter.
10408 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010409 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010410 }
10411 }
10412
10413 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010414 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010415 QualType FieldType = Context.getBaseElementType(F->getType());
10416 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10417 CXXConstructorDecl *Constructor =
10418 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010419 // If this is a deleted function, add it anyway. This might be conformant
10420 // with the standard. This might not. I'm not sure. It might not matter.
10421 // In particular, the problem is that this function never gets called. It
10422 // might just be ill-formed because this function attempts to refer to
10423 // a deleted function here.
10424 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010425 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010426 }
10427 }
10428
10429 return ExceptSpec;
10430}
10431
10432CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10433 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010434 assert(ClassDecl->needsImplicitMoveConstructor());
10435
Richard Smith8bf22e52012-11-29 01:34:07 +000010436 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10437 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010438 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010439
Sebastian Redl22653ba2011-08-30 19:58:05 +000010440 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10441 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010442
Richard Smithb5800092012-06-10 05:43:50 +000010443 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10444 CXXMoveConstructor,
10445 false);
10446
Sebastian Redl22653ba2011-08-30 19:58:05 +000010447 DeclarationName Name
10448 = Context.DeclarationNames.getCXXConstructorName(
10449 Context.getCanonicalType(ClassType));
10450 SourceLocation ClassLoc = ClassDecl->getLocation();
10451 DeclarationNameInfo NameInfo(Name, ClassLoc);
10452
Richard Smith99005e62013-05-07 03:19:20 +000010453 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010454 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010455 // member of its class.
10456 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010457 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010458 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010459 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010460 MoveConstructor->setAccess(AS_public);
10461 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010462
Richard Smithd3b5c9082012-07-27 04:22:15 +000010463 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010464 FunctionProtoType::ExtProtoInfo EPI =
10465 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010466 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010467 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010468
Sebastian Redl22653ba2011-08-30 19:58:05 +000010469 // Add the parameter to the constructor.
10470 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10471 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010472 /*IdentifierInfo=*/nullptr,
10473 ArgType, /*TInfo=*/nullptr,
10474 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010475 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010476
Richard Smith6b02d462012-12-08 08:32:28 +000010477 MoveConstructor->setTrivial(
10478 ClassDecl->needsOverloadResolutionForMoveConstructor()
10479 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10480 : ClassDecl->hasTrivialMoveConstructor());
10481
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010482 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010483 ClassDecl->setImplicitMoveConstructorIsDeleted();
10484 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010485 }
10486
10487 // Note that we have declared this constructor.
10488 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10489
10490 if (Scope *S = getScopeForContext(ClassDecl))
10491 PushOnScopeChains(MoveConstructor, S, false);
10492 ClassDecl->addDecl(MoveConstructor);
10493
10494 return MoveConstructor;
10495}
10496
10497void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10498 CXXConstructorDecl *MoveConstructor) {
10499 assert((MoveConstructor->isDefaulted() &&
10500 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010501 !MoveConstructor->doesThisDeclarationHaveABody() &&
10502 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010503 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10504
10505 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10506 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10507
Eli Friedmaneaf34142012-10-18 20:14:08 +000010508 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010509 DiagnosticErrorTrap Trap(Diags);
10510
David Blaikie3fc2f912013-01-17 05:26:25 +000010511 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010512 Trap.hasErrorOccurred()) {
10513 Diag(CurrentLocation, diag::note_member_synthesized_at)
10514 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10515 MoveConstructor->setInvalidDecl();
10516 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010517 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10518 ? MoveConstructor->getLocEnd()
10519 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010520 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010521 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010522 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010523 }
10524
Eli Friedman276dd182013-09-05 00:02:25 +000010525 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010526
10527 if (ASTMutationListener *L = getASTMutationListener()) {
10528 L->CompletedImplicitDefinition(MoveConstructor);
10529 }
10530}
10531
Douglas Gregor74f7d502012-02-15 19:33:52 +000010532bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010533 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010534}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010535
10536void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010537 SourceLocation CurrentLocation,
10538 CXXConversionDecl *Conv) {
10539 CXXRecordDecl *Lambda = Conv->getParent();
10540 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10541 // If we are defining a specialization of a conversion to function-ptr
10542 // cache the deduced template arguments for this specialization
10543 // so that we can use them to retrieve the corresponding call-operator
10544 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010545 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10546
Faisal Vali571df122013-09-29 08:45:24 +000010547 // Retrieve the corresponding call-operator specialization.
10548 if (Lambda->isGenericLambda()) {
10549 assert(Conv->isFunctionTemplateSpecialization());
10550 FunctionTemplateDecl *CallOpTemplate =
10551 CallOp->getDescribedFunctionTemplate();
10552 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010553 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010554 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010555 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010556 InsertPos);
10557 assert(CallOpSpec &&
10558 "Conversion operator must have a corresponding call operator");
10559 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10560 }
10561 // Mark the call operator referenced (and add to pending instantiations
10562 // if necessary).
10563 // For both the conversion and static-invoker template specializations
10564 // we construct their body's in this function, so no need to add them
10565 // to the PendingInstantiations.
10566 MarkFunctionReferenced(CurrentLocation, CallOp);
10567
Eli Friedmaneaf34142012-10-18 20:14:08 +000010568 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010569 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010570
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010571 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010572 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10573 // ... and get the corresponding specialization for a generic lambda.
10574 if (Lambda->isGenericLambda()) {
10575 assert(DeducedTemplateArgs &&
10576 "Must have deduced template arguments from Conversion Operator");
10577 FunctionTemplateDecl *InvokeTemplate =
10578 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010579 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010580 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010581 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010582 InsertPos);
10583 assert(InvokeSpec &&
10584 "Must have a corresponding static invoker specialization");
10585 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10586 }
10587 // Construct the body of the conversion function { return __invoke; }.
10588 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010589 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010590 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010591 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010592 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10593 Conv->getLocation(),
10594 Conv->getLocation()));
10595
10596 Conv->markUsed(Context);
10597 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010598
Faisal Vali571df122013-09-29 08:45:24 +000010599 // Fill in the __invoke function with a dummy implementation. IR generation
10600 // will fill in the actual details.
10601 Invoker->markUsed(Context);
10602 Invoker->setReferenced();
10603 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10604
Douglas Gregord3b672c2012-02-16 01:06:16 +000010605 if (ASTMutationListener *L = getASTMutationListener()) {
10606 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010607 L->CompletedImplicitDefinition(Invoker);
10608 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010609}
10610
Faisal Vali571df122013-09-29 08:45:24 +000010611
10612
Douglas Gregord3b672c2012-02-16 01:06:16 +000010613void Sema::DefineImplicitLambdaToBlockPointerConversion(
10614 SourceLocation CurrentLocation,
10615 CXXConversionDecl *Conv)
10616{
Faisal Vali850da1a2013-09-29 17:08:32 +000010617 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010618
Eli Friedman276dd182013-09-05 00:02:25 +000010619 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010620
Eli Friedmaneaf34142012-10-18 20:14:08 +000010621 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010622 DiagnosticErrorTrap Trap(Diags);
10623
Douglas Gregored90df32012-02-22 05:02:47 +000010624 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010625 Expr *This = ActOnCXXThis(CurrentLocation).get();
10626 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010627
Eli Friedman98b01ed2012-03-01 04:01:32 +000010628 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10629 Conv->getLocation(),
10630 Conv, DerefThis);
10631
10632 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10633 // behavior. Note that only the general conversion function does this
10634 // (since it's unusable otherwise); in the case where we inline the
10635 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010636 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010637 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10638 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010639 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010640
10641 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010642 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010643 Conv->setInvalidDecl();
10644 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010645 }
Douglas Gregored90df32012-02-22 05:02:47 +000010646
Douglas Gregored90df32012-02-22 05:02:47 +000010647 // Create the return statement that returns the block from the conversion
10648 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010649 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010650 if (Return.isInvalid()) {
10651 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10652 Conv->setInvalidDecl();
10653 return;
10654 }
10655
10656 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010657 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010658 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010659 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010660 Conv->getLocation()));
10661
Douglas Gregored90df32012-02-22 05:02:47 +000010662 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010663 if (ASTMutationListener *L = getASTMutationListener()) {
10664 L->CompletedImplicitDefinition(Conv);
10665 }
10666}
10667
Douglas Gregord2f70072012-03-10 06:53:13 +000010668/// \brief Determine whether the given list arguments contains exactly one
10669/// "real" (non-default) argument.
10670static bool hasOneRealArgument(MultiExprArg Args) {
10671 switch (Args.size()) {
10672 case 0:
10673 return false;
10674
10675 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010676 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010677 return false;
10678
10679 // fall through
10680 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010681 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010682 }
10683
10684 return false;
10685}
10686
John McCalldadc5752010-08-24 06:29:42 +000010687ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010688Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010689 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010690 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010691 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010692 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010693 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010694 unsigned ConstructKind,
10695 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010696 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010697
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010698 // C++0x [class.copy]p34:
10699 // When certain criteria are met, an implementation is allowed to
10700 // omit the copy/move construction of a class object, even if the
10701 // copy/move constructor and/or destructor for the object have
10702 // side effects. [...]
10703 // - when a temporary class object that has not been bound to a
10704 // reference (12.2) would be copied/moved to a class object
10705 // with the same cv-unqualified type, the copy/move operation
10706 // can be omitted by constructing the temporary object
10707 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010708 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010709 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010710 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010711 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010712 }
Mike Stump11289f42009-09-09 15:08:12 +000010713
10714 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010715 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010716 IsListInitialization, RequiresZeroInit,
10717 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010718}
10719
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010720/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10721/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010722ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010723Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10724 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010725 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010726 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010727 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010728 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010729 unsigned ConstructKind,
10730 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010731 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010732 return CXXConstructExpr::Create(
10733 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10734 HadMultipleCandidates, IsListInitialization, RequiresZeroInit,
10735 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10736 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010737}
10738
John McCall03c48482010-02-02 09:10:11 +000010739void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010740 if (VD->isInvalidDecl()) return;
10741
John McCall03c48482010-02-02 09:10:11 +000010742 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010743 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010744 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010745 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010746
Chandler Carruth86d17d32011-03-27 21:26:48 +000010747 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010748 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010749 CheckDestructorAccess(VD->getLocation(), Destructor,
10750 PDiag(diag::err_access_dtor_var)
10751 << VD->getDeclName()
10752 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010753 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010754
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010755 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010756 if (!VD->hasGlobalStorage()) return;
10757
10758 // Emit warning for non-trivial dtor in global scope (a real global,
10759 // class-static, function-static).
10760 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10761
10762 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010763 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010764 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010765}
10766
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010767/// \brief Given a constructor and the set of arguments provided for the
10768/// constructor, convert the arguments and add any required default arguments
10769/// to form a proper call to this constructor.
10770///
10771/// \returns true if an error occurred, false otherwise.
10772bool
10773Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10774 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010775 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010776 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010777 bool AllowExplicit,
10778 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010779 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10780 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010781 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010782
10783 const FunctionProtoType *Proto
10784 = Constructor->getType()->getAs<FunctionProtoType>();
10785 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010786 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010787
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010788 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010789 if (NumArgs < NumParams)
10790 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010791 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010792 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010793
10794 VariadicCallType CallType =
10795 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010796 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010797 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010798 Proto, 0,
10799 llvm::makeArrayRef(Args, NumArgs),
10800 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010801 CallType, AllowExplicit,
10802 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010803 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010804
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010805 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010806
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010807 CheckConstructorCall(Constructor,
10808 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10809 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010810 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010811
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010812 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010813}
10814
Anders Carlssone363c8e2009-12-12 00:32:00 +000010815static inline bool
10816CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10817 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010818 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010819 if (isa<NamespaceDecl>(DC)) {
10820 return SemaRef.Diag(FnDecl->getLocation(),
10821 diag::err_operator_new_delete_declared_in_namespace)
10822 << FnDecl->getDeclName();
10823 }
10824
10825 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010826 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010827 return SemaRef.Diag(FnDecl->getLocation(),
10828 diag::err_operator_new_delete_declared_static)
10829 << FnDecl->getDeclName();
10830 }
10831
Anders Carlsson60659a82009-12-12 02:43:16 +000010832 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010833}
10834
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010835static inline bool
10836CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10837 CanQualType ExpectedResultType,
10838 CanQualType ExpectedFirstParamType,
10839 unsigned DependentParamTypeDiag,
10840 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010841 QualType ResultType =
10842 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010843
10844 // Check that the result type is not dependent.
10845 if (ResultType->isDependentType())
10846 return SemaRef.Diag(FnDecl->getLocation(),
10847 diag::err_operator_new_delete_dependent_result_type)
10848 << FnDecl->getDeclName() << ExpectedResultType;
10849
10850 // Check that the result type is what we expect.
10851 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10852 return SemaRef.Diag(FnDecl->getLocation(),
10853 diag::err_operator_new_delete_invalid_result_type)
10854 << FnDecl->getDeclName() << ExpectedResultType;
10855
10856 // A function template must have at least 2 parameters.
10857 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10858 return SemaRef.Diag(FnDecl->getLocation(),
10859 diag::err_operator_new_delete_template_too_few_parameters)
10860 << FnDecl->getDeclName();
10861
10862 // The function decl must have at least 1 parameter.
10863 if (FnDecl->getNumParams() == 0)
10864 return SemaRef.Diag(FnDecl->getLocation(),
10865 diag::err_operator_new_delete_too_few_parameters)
10866 << FnDecl->getDeclName();
10867
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010868 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010869 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10870 if (FirstParamType->isDependentType())
10871 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10872 << FnDecl->getDeclName() << ExpectedFirstParamType;
10873
10874 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010875 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010876 ExpectedFirstParamType)
10877 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10878 << FnDecl->getDeclName() << ExpectedFirstParamType;
10879
10880 return false;
10881}
10882
Anders Carlsson12308f42009-12-11 23:23:22 +000010883static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010884CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010885 // C++ [basic.stc.dynamic.allocation]p1:
10886 // A program is ill-formed if an allocation function is declared in a
10887 // namespace scope other than global scope or declared static in global
10888 // scope.
10889 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10890 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010891
10892 CanQualType SizeTy =
10893 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10894
10895 // C++ [basic.stc.dynamic.allocation]p1:
10896 // The return type shall be void*. The first parameter shall have type
10897 // std::size_t.
10898 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10899 SizeTy,
10900 diag::err_operator_new_dependent_param_type,
10901 diag::err_operator_new_param_type))
10902 return true;
10903
10904 // C++ [basic.stc.dynamic.allocation]p1:
10905 // The first parameter shall not have an associated default argument.
10906 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010907 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010908 diag::err_operator_new_default_arg)
10909 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10910
10911 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010912}
10913
10914static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010915CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010916 // C++ [basic.stc.dynamic.deallocation]p1:
10917 // A program is ill-formed if deallocation functions are declared in a
10918 // namespace scope other than global scope or declared static in global
10919 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010920 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10921 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010922
10923 // C++ [basic.stc.dynamic.deallocation]p2:
10924 // Each deallocation function shall return void and its first parameter
10925 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010926 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10927 SemaRef.Context.VoidPtrTy,
10928 diag::err_operator_delete_dependent_param_type,
10929 diag::err_operator_delete_param_type))
10930 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010931
Anders Carlsson12308f42009-12-11 23:23:22 +000010932 return false;
10933}
10934
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010935/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10936/// of this overloaded operator is well-formed. If so, returns false;
10937/// otherwise, emits appropriate diagnostics and returns true.
10938bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010939 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010940 "Expected an overloaded operator declaration");
10941
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010942 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10943
Mike Stump11289f42009-09-09 15:08:12 +000010944 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010945 // The allocation and deallocation functions, operator new,
10946 // operator new[], operator delete and operator delete[], are
10947 // described completely in 3.7.3. The attributes and restrictions
10948 // found in the rest of this subclause do not apply to them unless
10949 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010950 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010951 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010952
Anders Carlsson22f443f2009-12-12 00:26:23 +000010953 if (Op == OO_New || Op == OO_Array_New)
10954 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010955
10956 // C++ [over.oper]p6:
10957 // An operator function shall either be a non-static member
10958 // function or be a non-member function and have at least one
10959 // parameter whose type is a class, a reference to a class, an
10960 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010961 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10962 if (MethodDecl->isStatic())
10963 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010964 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010965 } else {
10966 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010967 for (auto Param : FnDecl->params()) {
10968 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010969 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10970 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010971 ClassOrEnumParam = true;
10972 break;
10973 }
10974 }
10975
Douglas Gregord69246b2008-11-17 16:14:12 +000010976 if (!ClassOrEnumParam)
10977 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010978 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010979 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010980 }
10981
10982 // C++ [over.oper]p8:
10983 // An operator function cannot have default arguments (8.3.6),
10984 // except where explicitly stated below.
10985 //
Mike Stump11289f42009-09-09 15:08:12 +000010986 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010987 // (C++ [over.call]p1).
10988 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010989 for (auto Param : FnDecl->params()) {
10990 if (Param->hasDefaultArg())
10991 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010992 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010993 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010994 }
10995 }
10996
Douglas Gregor6cf08062008-11-10 13:38:07 +000010997 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10998 { false, false, false }
10999#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11000 , { Unary, Binary, MemberOnly }
11001#include "clang/Basic/OperatorKinds.def"
11002 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011003
Douglas Gregor6cf08062008-11-10 13:38:07 +000011004 bool CanBeUnaryOperator = OperatorUses[Op][0];
11005 bool CanBeBinaryOperator = OperatorUses[Op][1];
11006 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011007
11008 // C++ [over.oper]p8:
11009 // [...] Operator functions cannot have more or fewer parameters
11010 // than the number required for the corresponding operator, as
11011 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011012 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011013 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011014 if (Op != OO_Call &&
11015 ((NumParams == 1 && !CanBeUnaryOperator) ||
11016 (NumParams == 2 && !CanBeBinaryOperator) ||
11017 (NumParams < 1) || (NumParams > 2))) {
11018 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011019 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011020 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011021 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011022 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011023 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011024 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011025 assert(CanBeBinaryOperator &&
11026 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011027 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011028 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011029
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011030 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011031 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011032 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011033
Douglas Gregord69246b2008-11-17 16:14:12 +000011034 // Overloaded operators other than operator() cannot be variadic.
11035 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011036 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011037 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011038 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011039 }
11040
11041 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011042 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11043 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011044 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011045 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011046 }
11047
11048 // C++ [over.inc]p1:
11049 // The user-defined function called operator++ implements the
11050 // prefix and postfix ++ operator. If this function is a member
11051 // function with no parameters, or a non-member function with one
11052 // parameter of class or enumeration type, it defines the prefix
11053 // increment operator ++ for objects of that type. If the function
11054 // is a member function with one parameter (which shall be of type
11055 // int) or a non-member function with two parameters (the second
11056 // of which shall be of type int), it defines the postfix
11057 // increment operator ++ for objects of that type.
11058 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11059 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011060 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011061
Richard Smith538b52a2014-01-30 22:24:05 +000011062 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11063 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011064 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011065 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011066 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011067 }
11068
Douglas Gregord69246b2008-11-17 16:14:12 +000011069 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011070}
Chris Lattner3b024a32008-12-17 07:09:26 +000011071
Alexis Huntc88db062010-01-13 09:01:02 +000011072/// CheckLiteralOperatorDeclaration - Check whether the declaration
11073/// of this literal operator function is well-formed. If so, returns
11074/// false; otherwise, emits appropriate diagnostics and returns true.
11075bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011076 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011077 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11078 << FnDecl->getDeclName();
11079 return true;
11080 }
11081
Richard Smith72eebee2012-03-04 09:41:16 +000011082 if (FnDecl->isExternC()) {
11083 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11084 return true;
11085 }
11086
Alexis Huntc88db062010-01-13 09:01:02 +000011087 bool Valid = false;
11088
Richard Smithbcc22fc2012-03-09 08:00:36 +000011089 // This might be the definition of a literal operator template.
11090 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11091 // This might be a specialization of a literal operator template.
11092 if (!TpDecl)
11093 TpDecl = FnDecl->getPrimaryTemplate();
11094
Richard Smithb8b41d32013-10-07 19:57:58 +000011095 // template <char...> type operator "" name() and
11096 // template <class T, T...> type operator "" name() are the only valid
11097 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011098 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011099 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011100 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011101 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11102 if (Params->size() == 1) {
11103 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011104 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011105
Alexis Hunt7dd26172010-04-07 23:11:06 +000011106 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011107 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11108 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11109 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011110 } else if (Params->size() == 2) {
11111 TemplateTypeParmDecl *PmType =
11112 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11113 NonTypeTemplateParmDecl *PmArgs =
11114 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11115
11116 // The second template parameter must be a parameter pack with the
11117 // first template parameter as its type.
11118 if (PmType && PmArgs &&
11119 !PmType->isTemplateParameterPack() &&
11120 PmArgs->isTemplateParameterPack()) {
11121 const TemplateTypeParmType *TArgs =
11122 PmArgs->getType()->getAs<TemplateTypeParmType>();
11123 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11124 TArgs->getIndex() == PmType->getIndex()) {
11125 Valid = true;
11126 if (ActiveTemplateInstantiations.empty())
11127 Diag(FnDecl->getLocation(),
11128 diag::ext_string_literal_operator_template);
11129 }
11130 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011131 }
11132 }
Richard Smith72eebee2012-03-04 09:41:16 +000011133 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011134 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011135 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11136
Richard Smith72eebee2012-03-04 09:41:16 +000011137 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011138
Alexis Hunt079a6f72010-04-07 22:57:35 +000011139 // unsigned long long int, long double, and any character type are allowed
11140 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011141 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11142 Context.hasSameType(T, Context.LongDoubleTy) ||
11143 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011144 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011145 Context.hasSameType(T, Context.Char16Ty) ||
11146 Context.hasSameType(T, Context.Char32Ty)) {
11147 if (++Param == FnDecl->param_end())
11148 Valid = true;
11149 goto FinishedParams;
11150 }
11151
Alexis Hunt079a6f72010-04-07 22:57:35 +000011152 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011153 const PointerType *PT = T->getAs<PointerType>();
11154 if (!PT)
11155 goto FinishedParams;
11156 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011157 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011158 goto FinishedParams;
11159 T = T.getUnqualifiedType();
11160
11161 // Move on to the second parameter;
11162 ++Param;
11163
11164 // If there is no second parameter, the first must be a const char *
11165 if (Param == FnDecl->param_end()) {
11166 if (Context.hasSameType(T, Context.CharTy))
11167 Valid = true;
11168 goto FinishedParams;
11169 }
11170
11171 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11172 // are allowed as the first parameter to a two-parameter function
11173 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011174 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011175 Context.hasSameType(T, Context.Char16Ty) ||
11176 Context.hasSameType(T, Context.Char32Ty)))
11177 goto FinishedParams;
11178
11179 // The second and final parameter must be an std::size_t
11180 T = (*Param)->getType().getUnqualifiedType();
11181 if (Context.hasSameType(T, Context.getSizeType()) &&
11182 ++Param == FnDecl->param_end())
11183 Valid = true;
11184 }
11185
11186 // FIXME: This diagnostic is absolutely terrible.
11187FinishedParams:
11188 if (!Valid) {
11189 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11190 << FnDecl->getDeclName();
11191 return true;
11192 }
11193
Richard Smith768cecc2012-03-09 08:16:22 +000011194 // A parameter-declaration-clause containing a default argument is not
11195 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011196 for (auto Param : FnDecl->params()) {
11197 if (Param->hasDefaultArg()) {
11198 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011199 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011200 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011201 break;
11202 }
11203 }
11204
Richard Smith0df56f42012-03-08 02:39:21 +000011205 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011206 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11207 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011208 // C++11 [usrlit.suffix]p1:
11209 // Literal suffix identifiers that do not start with an underscore
11210 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011211 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11212 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011213 }
Richard Smith0df56f42012-03-08 02:39:21 +000011214
Alexis Huntc88db062010-01-13 09:01:02 +000011215 return false;
11216}
11217
Douglas Gregor07665a62009-01-05 19:45:36 +000011218/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11219/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011220/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11221/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011222/// the '{' brace. Otherwise, this linkage specification does not
11223/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011224Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011225 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011226 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011227 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11228 if (!Lit->isAscii()) {
11229 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11230 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011231 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011232 }
11233
11234 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011235 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011236 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011237 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011238 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011239 Language = LinkageSpecDecl::lang_cxx;
11240 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011241 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11242 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011243 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011244 }
Mike Stump11289f42009-09-09 15:08:12 +000011245
Chris Lattner438e5012008-12-17 07:13:27 +000011246 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011247
Richard Smith4ee696d2014-02-17 23:25:27 +000011248 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11249 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011250 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011251 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011252 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011253 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011254}
11255
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011256/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011257/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11258/// valid, it's the position of the closing '}' brace in a linkage
11259/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011260Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011261 Decl *LinkageSpec,
11262 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011263 if (RBraceLoc.isValid()) {
11264 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11265 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011266 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011267 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011268 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011269}
11270
Michael Han84324352013-02-22 17:15:32 +000011271Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11272 AttributeList *AttrList,
11273 SourceLocation SemiLoc) {
11274 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11275 // Attribute declarations appertain to empty declaration so we handle
11276 // them here.
11277 if (AttrList)
11278 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011279
Michael Han84324352013-02-22 17:15:32 +000011280 CurContext->addDecl(ED);
11281 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011282}
11283
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011284/// \brief Perform semantic analysis for the variable declaration that
11285/// occurs within a C++ catch clause, returning the newly-created
11286/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011287VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011288 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011289 SourceLocation StartLoc,
11290 SourceLocation Loc,
11291 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011292 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011293 QualType ExDeclType = TInfo->getType();
11294
Sebastian Redl54c04d42008-12-22 19:15:10 +000011295 // Arrays and functions decay.
11296 if (ExDeclType->isArrayType())
11297 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11298 else if (ExDeclType->isFunctionType())
11299 ExDeclType = Context.getPointerType(ExDeclType);
11300
11301 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11302 // The exception-declaration shall not denote a pointer or reference to an
11303 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011304 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011305 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011306 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011307 Invalid = true;
11308 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011309
Sebastian Redl54c04d42008-12-22 19:15:10 +000011310 QualType BaseType = ExDeclType;
11311 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011312 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011313 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011314 BaseType = Ptr->getPointeeType();
11315 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011316 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011317 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011318 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011319 BaseType = Ref->getPointeeType();
11320 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011321 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011322 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011323 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011324 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011325 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011326
Mike Stump11289f42009-09-09 15:08:12 +000011327 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011328 RequireNonAbstractType(Loc, ExDeclType,
11329 diag::err_abstract_type_in_decl,
11330 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011331 Invalid = true;
11332
John McCall2ca705e2010-07-24 00:37:23 +000011333 // Only the non-fragile NeXT runtime currently supports C++ catches
11334 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011335 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011336 QualType T = ExDeclType;
11337 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11338 T = RT->getPointeeType();
11339
11340 if (T->isObjCObjectType()) {
11341 Diag(Loc, diag::err_objc_object_catch);
11342 Invalid = true;
11343 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011344 // FIXME: should this be a test for macosx-fragile specifically?
11345 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011346 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011347 }
11348 }
11349
Abramo Bagnaradff19302011-03-08 08:55:46 +000011350 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011351 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011352 ExDecl->setExceptionVariable(true);
11353
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011354 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011355 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011356 Invalid = true;
11357
Douglas Gregor750734c2011-07-06 18:14:43 +000011358 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011359 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011360 // Insulate this from anything else we might currently be parsing.
11361 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11362
Douglas Gregor6de584c2010-03-05 23:38:39 +000011363 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011364 // The object declared in an exception-declaration or, if the
11365 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011366 // copy-initialized (8.5) from the exception object. [...]
11367 // The object is destroyed when the handler exits, after the destruction
11368 // of any automatic objects initialized within the handler.
11369 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011370 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011371 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011372 QualType initType = ExDeclType;
11373
11374 InitializedEntity entity =
11375 InitializedEntity::InitializeVariable(ExDecl);
11376 InitializationKind initKind =
11377 InitializationKind::CreateCopy(Loc, SourceLocation());
11378
11379 Expr *opaqueValue =
11380 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011381 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11382 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011383 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011384 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011385 else {
11386 // If the constructor used was non-trivial, set this as the
11387 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011388 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011389 if (!construct->getConstructor()->isTrivial()) {
11390 Expr *init = MaybeCreateExprWithCleanups(construct);
11391 ExDecl->setInit(init);
11392 }
11393
11394 // And make sure it's destructable.
11395 FinalizeVarWithDestructor(ExDecl, recordType);
11396 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011397 }
11398 }
11399
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011400 if (Invalid)
11401 ExDecl->setInvalidDecl();
11402
11403 return ExDecl;
11404}
11405
11406/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11407/// handler.
John McCall48871652010-08-21 09:40:31 +000011408Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011409 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011410 bool Invalid = D.isInvalidType();
11411
11412 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011413 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11414 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011415 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11416 D.getIdentifierLoc());
11417 Invalid = true;
11418 }
11419
Sebastian Redl54c04d42008-12-22 19:15:10 +000011420 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011421 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011422 LookupOrdinaryName,
11423 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011424 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011425 // it contains any previous declaration, except for function parameters in
11426 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011427 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011428 if (isDeclInScope(PrevDecl, CurContext, S)) {
11429 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11430 << D.getIdentifier();
11431 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11432 Invalid = true;
11433 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011434 // Maybe we will complain about the shadowed template parameter.
11435 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011436 }
11437
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011438 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011439 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11440 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011441 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011442 }
11443
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011444 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011445 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011446 D.getIdentifierLoc(),
11447 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011448 if (Invalid)
11449 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011450
Sebastian Redl54c04d42008-12-22 19:15:10 +000011451 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011452 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011453 PushOnScopeChains(ExDecl, S);
11454 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011455 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011456
Douglas Gregor758a8692009-06-17 21:51:59 +000011457 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011458 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011459}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011460
Abramo Bagnaraea947882011-03-08 16:41:52 +000011461Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011462 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011463 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011464 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011465 StringLiteral *AssertMessage =
11466 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011467
Richard Smithded9c2e2012-07-11 22:37:56 +000011468 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011469 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011470
11471 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11472 AssertMessage, RParenLoc, false);
11473}
11474
11475Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11476 Expr *AssertExpr,
11477 StringLiteral *AssertMessage,
11478 SourceLocation RParenLoc,
11479 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011480 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011481 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11482 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011483 // In a static_assert-declaration, the constant-expression shall be a
11484 // constant expression that can be contextually converted to bool.
11485 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11486 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011487 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011488
Richard Smith902ca212011-12-14 23:32:26 +000011489 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011490 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011491 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011492 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011493 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011494
Richard Smithded9c2e2012-07-11 22:37:56 +000011495 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011496 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011497 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011498 if (AssertMessage)
11499 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011500 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011501 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011502 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011503 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011504 }
Mike Stump11289f42009-09-09 15:08:12 +000011505
Abramo Bagnaraea947882011-03-08 16:41:52 +000011506 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011507 AssertExpr, AssertMessage, RParenLoc,
11508 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011509
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011510 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011511 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011512}
Sebastian Redlf769df52009-03-24 22:27:57 +000011513
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011514/// \brief Perform semantic analysis of the given friend type declaration.
11515///
11516/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011517FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011518 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011519 TypeSourceInfo *TSInfo) {
11520 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11521
11522 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011523 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011524
Richard Smithc8239732011-10-18 21:39:00 +000011525 // C++03 [class.friend]p2:
11526 // An elaborated-type-specifier shall be used in a friend declaration
11527 // for a class.*
11528 //
11529 // * The class-key of the elaborated-type-specifier is required.
11530 if (!ActiveTemplateInstantiations.empty()) {
11531 // Do not complain about the form of friend template types during
11532 // template instantiation; we will already have complained when the
11533 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011534 } else {
11535 if (!T->isElaboratedTypeSpecifier()) {
11536 // If we evaluated the type to a record type, suggest putting
11537 // a tag in front.
11538 if (const RecordType *RT = T->getAs<RecordType>()) {
11539 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011540
11541 SmallString<16> InsertionText(" ");
11542 InsertionText += RD->getKindName();
11543
Nick Lewycky36722d22013-02-06 05:59:33 +000011544 Diag(TypeRange.getBegin(),
11545 getLangOpts().CPlusPlus11 ?
11546 diag::warn_cxx98_compat_unelaborated_friend_type :
11547 diag::ext_unelaborated_friend_type)
11548 << (unsigned) RD->getTagKind()
11549 << T
11550 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11551 InsertionText);
11552 } else {
11553 Diag(FriendLoc,
11554 getLangOpts().CPlusPlus11 ?
11555 diag::warn_cxx98_compat_nonclass_type_friend :
11556 diag::ext_nonclass_type_friend)
11557 << T
11558 << TypeRange;
11559 }
11560 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011561 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011562 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011563 diag::warn_cxx98_compat_enum_friend :
11564 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011565 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011566 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011567 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011568
Nick Lewycky36722d22013-02-06 05:59:33 +000011569 // C++11 [class.friend]p3:
11570 // A friend declaration that does not declare a function shall have one
11571 // of the following forms:
11572 // friend elaborated-type-specifier ;
11573 // friend simple-type-specifier ;
11574 // friend typename-specifier ;
11575 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11576 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11577 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011578
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011579 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011580 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011581 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011582 return FriendDecl::Create(Context, CurContext,
11583 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11584 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011585}
11586
John McCallace48cd2010-10-19 01:40:49 +000011587/// Handle a friend tag declaration where the scope specifier was
11588/// templated.
11589Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11590 unsigned TagSpec, SourceLocation TagLoc,
11591 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011592 IdentifierInfo *Name,
11593 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011594 AttributeList *Attr,
11595 MultiTemplateParamsArg TempParamLists) {
11596 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11597
11598 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011599 bool Invalid = false;
11600
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011601 if (TemplateParameterList *TemplateParams =
11602 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011603 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011604 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011605 if (TemplateParams->size() > 0) {
11606 // This is a declaration of a class template.
11607 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011608 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011609
Eric Christopher6f228b52011-07-21 05:34:24 +000011610 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11611 SS, Name, NameLoc, Attr,
11612 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011613 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011614 TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011615 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011616 } else {
11617 // The "template<>" header is extraneous.
11618 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11619 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11620 isExplicitSpecialization = true;
11621 }
11622 }
11623
Craig Topperc3ec1492014-05-26 06:22:03 +000011624 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011625
John McCallace48cd2010-10-19 01:40:49 +000011626 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011627 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011628 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011629 isAllExplicitSpecializations = false;
11630 break;
11631 }
11632 }
11633
11634 // FIXME: don't ignore attributes.
11635
11636 // If it's explicit specializations all the way down, just forget
11637 // about the template header and build an appropriate non-templated
11638 // friend. TODO: for source fidelity, remember the headers.
11639 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011640 if (SS.isEmpty()) {
11641 bool Owned = false;
11642 bool IsDependent = false;
11643 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011644 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011645 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011646 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011647 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011648 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011649 /*UnderlyingType=*/TypeResult(),
11650 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011651 }
Richard Smith649c7b062014-01-08 00:56:48 +000011652
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011653 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011654 ElaboratedTypeKeyword Keyword
11655 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011656 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011657 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011658 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011659 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011660
11661 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11662 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011663 DependentNameTypeLoc TL =
11664 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011665 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011666 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011667 TL.setNameLoc(NameLoc);
11668 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011669 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011670 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011671 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011672 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011673 }
11674
11675 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011676 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011677 Friend->setAccess(AS_public);
11678 CurContext->addDecl(Friend);
11679 return Friend;
11680 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011681
11682 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11683
11684
John McCallace48cd2010-10-19 01:40:49 +000011685
11686 // Handle the case of a templated-scope friend class. e.g.
11687 // template <class T> class A<T>::B;
11688 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011689 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11690 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011691 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11692 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11693 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011694 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011695 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011696 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011697 TL.setNameLoc(NameLoc);
11698
11699 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011700 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011701 Friend->setAccess(AS_public);
11702 Friend->setUnsupportedFriend(true);
11703 CurContext->addDecl(Friend);
11704 return Friend;
11705}
11706
11707
John McCall11083da2009-09-16 22:47:08 +000011708/// Handle a friend type declaration. This works in tandem with
11709/// ActOnTag.
11710///
11711/// Notes on friend class templates:
11712///
11713/// We generally treat friend class declarations as if they were
11714/// declaring a class. So, for example, the elaborated type specifier
11715/// in a friend declaration is required to obey the restrictions of a
11716/// class-head (i.e. no typedefs in the scope chain), template
11717/// parameters are required to match up with simple template-ids, &c.
11718/// However, unlike when declaring a template specialization, it's
11719/// okay to refer to a template specialization without an empty
11720/// template parameter declaration, e.g.
11721/// friend class A<T>::B<unsigned>;
11722/// We permit this as a special case; if there are any template
11723/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011724/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011725Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011726 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011727 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011728
11729 assert(DS.isFriendSpecified());
11730 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11731
John McCall11083da2009-09-16 22:47:08 +000011732 // Try to convert the decl specifier to a type. This works for
11733 // friend templates because ActOnTag never produces a ClassTemplateDecl
11734 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011735 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011736 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11737 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011738 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011739 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011740
Douglas Gregor6c110f32010-12-16 01:14:37 +000011741 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011742 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011743
John McCall11083da2009-09-16 22:47:08 +000011744 // This is definitely an error in C++98. It's probably meant to
11745 // be forbidden in C++0x, too, but the specification is just
11746 // poorly written.
11747 //
11748 // The problem is with declarations like the following:
11749 // template <T> friend A<T>::foo;
11750 // where deciding whether a class C is a friend or not now hinges
11751 // on whether there exists an instantiation of A that causes
11752 // 'foo' to equal C. There are restrictions on class-heads
11753 // (which we declare (by fiat) elaborated friend declarations to
11754 // be) that makes this tractable.
11755 //
11756 // FIXME: handle "template <> friend class A<T>;", which
11757 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011758 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011759 Diag(Loc, diag::err_tagless_friend_type_template)
11760 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011761 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011762 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011763
John McCallaa74a0c2009-08-28 07:59:38 +000011764 // C++98 [class.friend]p1: A friend of a class is a function
11765 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011766 // This is fixed in DR77, which just barely didn't make the C++03
11767 // deadline. It's also a very silly restriction that seriously
11768 // affects inner classes and which nobody else seems to implement;
11769 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011770 //
11771 // But note that we could warn about it: it's always useless to
11772 // friend one of your own members (it's not, however, worthless to
11773 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011774
John McCall11083da2009-09-16 22:47:08 +000011775 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011776 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011777 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011778 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011779 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011780 TSI,
John McCall11083da2009-09-16 22:47:08 +000011781 DS.getFriendSpecLoc());
11782 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011783 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011784
11785 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011786 return nullptr;
11787
John McCall11083da2009-09-16 22:47:08 +000011788 D->setAccess(AS_public);
11789 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011790
John McCall48871652010-08-21 09:40:31 +000011791 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011792}
11793
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011794NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11795 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011796 const DeclSpec &DS = D.getDeclSpec();
11797
11798 assert(DS.isFriendSpecified());
11799 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11800
11801 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011802 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011803
11804 // C++ [class.friend]p1
11805 // A friend of a class is a function or class....
11806 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011807 // It *doesn't* see through dependent types, which is correct
11808 // according to [temp.arg.type]p3:
11809 // If a declaration acquires a function type through a
11810 // type dependent on a template-parameter and this causes
11811 // a declaration that does not use the syntactic form of a
11812 // function declarator to have a function type, the program
11813 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011814 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011815 Diag(Loc, diag::err_unexpected_friend);
11816
11817 // It might be worthwhile to try to recover by creating an
11818 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011819 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011820 }
11821
11822 // C++ [namespace.memdef]p3
11823 // - If a friend declaration in a non-local class first declares a
11824 // class or function, the friend class or function is a member
11825 // of the innermost enclosing namespace.
11826 // - The name of the friend is not found by simple name lookup
11827 // until a matching declaration is provided in that namespace
11828 // scope (either before or after the class declaration granting
11829 // friendship).
11830 // - If a friend function is called, its name may be found by the
11831 // name lookup that considers functions from namespaces and
11832 // classes associated with the types of the function arguments.
11833 // - When looking for a prior declaration of a class or a function
11834 // declared as a friend, scopes outside the innermost enclosing
11835 // namespace scope are not considered.
11836
John McCallde3fd222010-10-12 23:13:28 +000011837 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011838 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11839 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011840 assert(Name);
11841
Douglas Gregor6c110f32010-12-16 01:14:37 +000011842 // Check for unexpanded parameter packs.
11843 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11844 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11845 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011846 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011847
John McCall07e91c02009-08-06 02:15:43 +000011848 // The context we found the declaration in, or in which we should
11849 // create the declaration.
11850 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011851 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011852 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011853 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011854
Richard Smith114394f2013-08-09 04:35:01 +000011855 // There are five cases here.
11856 // - There's no scope specifier and we're in a local class. Only look
11857 // for functions declared in the immediately-enclosing block scope.
11858 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011859 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011860 if ((SS.isInvalid() || !SS.isSet()) &&
11861 (FunctionContainingLocalClass =
11862 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11863 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011864 // If a friend declaration appears in a local class and the name
11865 // specified is an unqualified name, a prior declaration is
11866 // looked up without considering scopes that are outside the
11867 // innermost enclosing non-class scope. For a friend function
11868 // declaration, if there is no prior declaration, the program is
11869 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011870
11871 // Find the innermost enclosing non-class scope. This is the block
11872 // scope containing the local class definition (or for a nested class,
11873 // the outer local class).
11874 DCScope = S->getFnParent();
11875
11876 // Look up the function name in the scope.
11877 Previous.clear(LookupLocalFriendName);
11878 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11879
11880 if (!Previous.empty()) {
11881 // All possible previous declarations must have the same context:
11882 // either they were declared at block scope or they are members of
11883 // one of the enclosing local classes.
11884 DC = Previous.getRepresentativeDecl()->getDeclContext();
11885 } else {
11886 // This is ill-formed, but provide the context that we would have
11887 // declared the function in, if we were permitted to, for error recovery.
11888 DC = FunctionContainingLocalClass;
11889 }
Richard Smith541b38b2013-09-20 01:15:31 +000011890 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011891
11892 // C++ [class.friend]p6:
11893 // A function can be defined in a friend declaration of a class if and
11894 // only if the class is a non-local class (9.8), the function name is
11895 // unqualified, and the function has namespace scope.
11896 if (D.isFunctionDefinition()) {
11897 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11898 }
11899
11900 // - There's no scope specifier, in which case we just go to the
11901 // appropriate scope and look for a function or function template
11902 // there as appropriate.
11903 } else if (SS.isInvalid() || !SS.isSet()) {
11904 // C++11 [namespace.memdef]p3:
11905 // If the name in a friend declaration is neither qualified nor
11906 // a template-id and the declaration is a function or an
11907 // elaborated-type-specifier, the lookup to determine whether
11908 // the entity has been previously declared shall not consider
11909 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011910 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011911
John McCallf7cfb222010-10-13 05:45:15 +000011912 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011913 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011914
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011915 // Skip class contexts. If someone can cite chapter and verse
11916 // for this behavior, that would be nice --- it's what GCC and
11917 // EDG do, and it seems like a reasonable intent, but the spec
11918 // really only says that checks for unqualified existing
11919 // declarations should stop at the nearest enclosing namespace,
11920 // not that they should only consider the nearest enclosing
11921 // namespace.
11922 while (DC->isRecord())
11923 DC = DC->getParent();
11924
11925 DeclContext *LookupDC = DC;
11926 while (LookupDC->isTransparentContext())
11927 LookupDC = LookupDC->getParent();
11928
11929 while (true) {
11930 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011931
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011932 if (!Previous.empty()) {
11933 DC = LookupDC;
11934 break;
John McCallf4776592010-10-14 22:22:28 +000011935 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011936
11937 if (isTemplateId) {
11938 if (isa<TranslationUnitDecl>(LookupDC)) break;
11939 } else {
11940 if (LookupDC->isFileContext()) break;
11941 }
11942 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011943 }
11944
John McCallccbc0322010-10-13 06:22:15 +000011945 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011946
John McCallde3fd222010-10-12 23:13:28 +000011947 // - There's a non-dependent scope specifier, in which case we
11948 // compute it and do a previous lookup there for a function
11949 // or function template.
11950 } else if (!SS.getScopeRep()->isDependent()) {
11951 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000011952 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011953
Craig Topperc3ec1492014-05-26 06:22:03 +000011954 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011955
11956 LookupQualifiedName(Previous, DC);
11957
11958 // Ignore things found implicitly in the wrong scope.
11959 // TODO: better diagnostics for this case. Suggesting the right
11960 // qualified scope would be nice...
11961 LookupResult::Filter F = Previous.makeFilter();
11962 while (F.hasNext()) {
11963 NamedDecl *D = F.next();
11964 if (!DC->InEnclosingNamespaceSetOf(
11965 D->getDeclContext()->getRedeclContext()))
11966 F.erase();
11967 }
11968 F.done();
11969
11970 if (Previous.empty()) {
11971 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011972 Diag(Loc, diag::err_qualified_friend_not_found)
11973 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000011974 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011975 }
11976
11977 // C++ [class.friend]p1: A friend of a class is a function or
11978 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011979 if (DC->Equals(CurContext))
11980 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011981 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011982 diag::warn_cxx98_compat_friend_is_member :
11983 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011984
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011985 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011986 // C++ [class.friend]p6:
11987 // A function can be defined in a friend declaration of a class if and
11988 // only if the class is a non-local class (9.8), the function name is
11989 // unqualified, and the function has namespace scope.
11990 SemaDiagnosticBuilder DB
11991 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11992
11993 DB << SS.getScopeRep();
11994 if (DC->isFileContext())
11995 DB << FixItHint::CreateRemoval(SS.getRange());
11996 SS.clear();
11997 }
John McCallde3fd222010-10-12 23:13:28 +000011998
11999 // - There's a scope specifier that does not match any template
12000 // parameter lists, in which case we use some arbitrary context,
12001 // create a method or method template, and wait for instantiation.
12002 // - There's a scope specifier that does match some template
12003 // parameter lists, which we don't handle right now.
12004 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012005 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012006 // C++ [class.friend]p6:
12007 // A function can be defined in a friend declaration of a class if and
12008 // only if the class is a non-local class (9.8), the function name is
12009 // unqualified, and the function has namespace scope.
12010 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12011 << SS.getScopeRep();
12012 }
12013
John McCallde3fd222010-10-12 23:13:28 +000012014 DC = CurContext;
12015 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012016 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012017
John McCallf7cfb222010-10-13 05:45:15 +000012018 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012019 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012020 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12021 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12022 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012023 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012024 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12025 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012026 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012027 }
John McCall07e91c02009-08-06 02:15:43 +000012028 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012029
Douglas Gregordd847ba2011-11-03 16:37:14 +000012030 // FIXME: This is an egregious hack to cope with cases where the scope stack
12031 // does not contain the declaration context, i.e., in an out-of-line
12032 // definition of a class.
12033 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12034 if (!DCScope) {
12035 FakeDCScope.setEntity(DC);
12036 DCScope = &FakeDCScope;
12037 }
Richard Smith114394f2013-08-09 04:35:01 +000012038
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012039 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012040 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012041 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012042 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012043
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012044 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012045
Richard Smith114394f2013-08-09 04:35:01 +000012046 // If we performed typo correction, we might have added a scope specifier
12047 // and changed the decl context.
12048 DC = ND->getDeclContext();
12049
John McCall759e32b2009-08-31 22:39:49 +000012050 // Add the function declaration to the appropriate lookup tables,
12051 // adjusting the redeclarations list as necessary. We don't
12052 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012053 //
John McCall759e32b2009-08-31 22:39:49 +000012054 // Also update the scope-based lookup if the target context's
12055 // lookup context is in lexical scope.
12056 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012057 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012058 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012059 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012060 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012061 }
John McCallaa74a0c2009-08-28 07:59:38 +000012062
12063 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012064 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012065 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012066 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012067 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012068
John McCalla0a96892012-08-10 03:15:35 +000012069 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012070 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012071 } else {
12072 if (DC->isRecord()) CheckFriendAccess(ND);
12073
John McCall2c2eb122010-10-16 06:59:13 +000012074 FunctionDecl *FD;
12075 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12076 FD = FTD->getTemplatedDecl();
12077 else
12078 FD = cast<FunctionDecl>(ND);
12079
David Majnemer502b0ed2013-06-25 23:09:30 +000012080 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12081 // default argument expression, that declaration shall be a definition
12082 // and shall be the only declaration of the function or function
12083 // template in the translation unit.
12084 if (functionDeclHasDefaultArgument(FD)) {
12085 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12086 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12087 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12088 } else if (!D.isFunctionDefinition())
12089 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12090 }
12091
John McCall2c2eb122010-10-16 06:59:13 +000012092 // Mark templated-scope function declarations as unsupported.
12093 if (FD->getNumTemplateParameterLists())
12094 FrD->setUnsupportedFriend(true);
12095 }
John McCallde3fd222010-10-12 23:13:28 +000012096
John McCall48871652010-08-21 09:40:31 +000012097 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012098}
12099
John McCall48871652010-08-21 09:40:31 +000012100void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12101 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012102
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012103 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012104 if (!Fn) {
12105 Diag(DelLoc, diag::err_deleted_non_function);
12106 return;
12107 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012108
Douglas Gregorec9fd132012-01-14 16:38:05 +000012109 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012110 // Don't consider the implicit declaration we generate for explicit
12111 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012112 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12113 Prev->getPreviousDecl()) &&
12114 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012115 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012116 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12117 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12118 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012119 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012120 // If the declaration wasn't the first, we delete the function anyway for
12121 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012122 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012123 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012124
Nico Rieck9de0a572014-05-29 16:51:19 +000012125 // dllimport/dllexport cannot be deleted.
12126 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12127 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12128 Fn->setInvalidDecl();
12129 }
12130
Richard Smithb4d2a152013-04-02 19:38:47 +000012131 if (Fn->isDeleted())
12132 return;
12133
12134 // See if we're deleting a function which is already known to override a
12135 // non-deleted virtual function.
12136 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12137 bool IssuedDiagnostic = false;
12138 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12139 E = MD->end_overridden_methods();
12140 I != E; ++I) {
12141 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12142 if (!IssuedDiagnostic) {
12143 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12144 IssuedDiagnostic = true;
12145 }
12146 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12147 }
12148 }
12149 }
12150
Richard Smithb63b6ee2014-01-22 01:43:19 +000012151 // C++11 [basic.start.main]p3:
12152 // A program that defines main as deleted [...] is ill-formed.
12153 if (Fn->isMain())
12154 Diag(DelLoc, diag::err_deleted_main);
12155
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012156 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012157}
Sebastian Redl4c018662009-04-27 21:33:24 +000012158
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012159void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012160 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012161
12162 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012163 if (MD->getParent()->isDependentType()) {
12164 MD->setDefaulted();
12165 MD->setExplicitlyDefaulted();
12166 return;
12167 }
12168
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012169 CXXSpecialMember Member = getSpecialMember(MD);
12170 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012171 if (!MD->isInvalidDecl())
12172 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012173 return;
12174 }
12175
12176 MD->setDefaulted();
12177 MD->setExplicitlyDefaulted();
12178
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012179 // If this definition appears within the record, do the checking when
12180 // the record is complete.
12181 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012182 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012183 // Find the uninstantiated declaration that actually had the '= default'
12184 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012185 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012186
Richard Smith3901dfe2013-03-27 00:22:47 +000012187 // If the method was defaulted on its first declaration, we will have
12188 // already performed the checking in CheckCompletedCXXClass. Such a
12189 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012190 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012191 return;
12192
Richard Smithd3b5c9082012-07-27 04:22:15 +000012193 CheckExplicitlyDefaultedSpecialMember(MD);
12194
Richard Smithbd305122012-12-11 01:14:52 +000012195 // The exception specification is needed because we are defining the
12196 // function.
12197 ResolveExceptionSpec(DefaultLoc,
12198 MD->getType()->castAs<FunctionProtoType>());
12199
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012200 if (MD->isInvalidDecl())
12201 return;
12202
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012203 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012204 case CXXDefaultConstructor:
12205 DefineImplicitDefaultConstructor(DefaultLoc,
12206 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012207 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012208 case CXXCopyConstructor:
12209 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012210 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012211 case CXXCopyAssignment:
12212 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012213 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012214 case CXXDestructor:
12215 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012216 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012217 case CXXMoveConstructor:
12218 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012219 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012220 case CXXMoveAssignment:
12221 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012222 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012223 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012224 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012225 }
12226 } else {
12227 Diag(DefaultLoc, diag::err_default_special_members);
12228 }
12229}
12230
Sebastian Redl4c018662009-04-27 21:33:24 +000012231static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012232 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012233 Stmt *SubStmt = *CI;
12234 if (!SubStmt)
12235 continue;
12236 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012237 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012238 diag::err_return_in_constructor_handler);
12239 if (!isa<Expr>(SubStmt))
12240 SearchForReturnInStmt(Self, SubStmt);
12241 }
12242}
12243
12244void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12245 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12246 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12247 SearchForReturnInStmt(*this, Handler);
12248 }
12249}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012250
David Blaikie68f71a32013-01-18 23:03:15 +000012251bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012252 const CXXMethodDecl *Old) {
12253 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12254 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12255
12256 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12257
12258 // If the calling conventions match, everything is fine
12259 if (NewCC == OldCC)
12260 return false;
12261
Hans Wennborg2545efe2013-12-11 17:42:11 +000012262 // If the calling conventions mismatch because the new function is static,
12263 // suppress the calling convention mismatch error; the error about static
12264 // function override (err_static_overrides_virtual from
12265 // Sema::CheckFunctionDeclaration) is more clear.
12266 if (New->getStorageClass() == SC_Static)
12267 return false;
12268
Reid Kleckner78af0702013-08-27 23:08:25 +000012269 Diag(New->getLocation(),
12270 diag::err_conflicting_overriding_cc_attributes)
12271 << New->getDeclName() << New->getType() << Old->getType();
12272 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12273 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012274}
12275
Mike Stump11289f42009-09-09 15:08:12 +000012276bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012277 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012278 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12279 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012280
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012281 if (Context.hasSameType(NewTy, OldTy) ||
12282 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012283 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012284
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012285 // Check if the return types are covariant
12286 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012287
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012288 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012289 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12290 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012291 NewClassTy = NewPT->getPointeeType();
12292 OldClassTy = OldPT->getPointeeType();
12293 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012294 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12295 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12296 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12297 NewClassTy = NewRT->getPointeeType();
12298 OldClassTy = OldRT->getPointeeType();
12299 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012300 }
12301 }
Mike Stump11289f42009-09-09 15:08:12 +000012302
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012303 // The return types aren't either both pointers or references to a class type.
12304 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012305 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012306 diag::err_different_return_type_for_overriding_virtual_function)
12307 << New->getDeclName() << NewTy << OldTy;
12308 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012309
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012310 return true;
12311 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012312
Anders Carlssone60365b2009-12-31 18:34:24 +000012313 // C++ [class.virtual]p6:
12314 // If the return type of D::f differs from the return type of B::f, the
12315 // class type in the return type of D::f shall be complete at the point of
12316 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012317 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12318 if (!RT->isBeingDefined() &&
12319 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012320 diag::err_covariant_return_incomplete,
12321 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012322 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012323 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012324
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012325 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012326 // Check if the new class derives from the old class.
12327 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12328 Diag(New->getLocation(),
12329 diag::err_covariant_return_not_derived)
12330 << New->getDeclName() << NewTy << OldTy;
12331 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12332 return true;
12333 }
Mike Stump11289f42009-09-09 15:08:12 +000012334
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012335 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012336 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012337 diag::err_covariant_return_inaccessible_base,
12338 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12339 // FIXME: Should this point to the return type?
Craig Topperc3ec1492014-05-26 06:22:03 +000012340 New->getLocation(), SourceRange(), New->getDeclName(),
12341 nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012342 // FIXME: this note won't trigger for delayed access control
12343 // diagnostics, and it's impossible to get an undelayed error
12344 // here from access control during the original parse because
12345 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012346 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12347 return true;
12348 }
12349 }
Mike Stump11289f42009-09-09 15:08:12 +000012350
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012351 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012352 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012353 Diag(New->getLocation(),
12354 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012355 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012356 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12357 return true;
12358 };
Mike Stump11289f42009-09-09 15:08:12 +000012359
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012360
12361 // The new class type must have the same or less qualifiers as the old type.
12362 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12363 Diag(New->getLocation(),
12364 diag::err_covariant_return_type_class_type_more_qualified)
12365 << New->getDeclName() << NewTy << OldTy;
12366 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12367 return true;
12368 };
Mike Stump11289f42009-09-09 15:08:12 +000012369
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012370 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012371}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012372
Douglas Gregor21920e372009-12-01 17:24:26 +000012373/// \brief Mark the given method pure.
12374///
12375/// \param Method the method to be marked pure.
12376///
12377/// \param InitRange the source range that covers the "0" initializer.
12378bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012379 SourceLocation EndLoc = InitRange.getEnd();
12380 if (EndLoc.isValid())
12381 Method->setRangeEnd(EndLoc);
12382
Douglas Gregor21920e372009-12-01 17:24:26 +000012383 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12384 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012385 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012386 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012387
12388 if (!Method->isInvalidDecl())
12389 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12390 << Method->getDeclName() << InitRange;
12391 return true;
12392}
12393
Douglas Gregor926410d2012-02-21 02:22:07 +000012394/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012395static bool isStaticDataMember(const Decl *D) {
12396 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12397 return Var->isStaticDataMember();
12398
12399 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012400}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012401
John McCall1f4ee7b2009-12-19 09:28:58 +000012402/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12403/// an initializer for the out-of-line declaration 'Dcl'. The scope
12404/// is a fresh scope pushed for just this purpose.
12405///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012406/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12407/// static data member of class X, names should be looked up in the scope of
12408/// class X.
John McCall48871652010-08-21 09:40:31 +000012409void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012410 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012411 if (!D || D->isInvalidDecl())
12412 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012413
Richard Smitha2302242013-12-05 07:51:02 +000012414 // We will always have a nested name specifier here, but this declaration
12415 // might not be out of line if the specifier names the current namespace:
12416 // extern int n;
12417 // int ::n = 0;
12418 if (D->isOutOfLine())
12419 EnterDeclaratorContext(S, D->getDeclContext());
12420
Douglas Gregor926410d2012-02-21 02:22:07 +000012421 // If we are parsing the initializer for a static data member, push a
12422 // new expression evaluation context that is associated with this static
12423 // data member.
12424 if (isStaticDataMember(D))
12425 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012426}
12427
12428/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012429/// initializer for the out-of-line declaration 'D'.
12430void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012431 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012432 if (!D || D->isInvalidDecl())
12433 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012434
Douglas Gregor926410d2012-02-21 02:22:07 +000012435 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012436 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012437
Richard Smitha2302242013-12-05 07:51:02 +000012438 if (D->isOutOfLine())
12439 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012440}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012441
12442/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12443/// C++ if/switch/while/for statement.
12444/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012445DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012446 // C++ 6.4p2:
12447 // The declarator shall not specify a function or an array.
12448 // The type-specifier-seq shall not contain typedef and shall not declare a
12449 // new class or enumeration.
12450 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12451 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012452
12453 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012454 if (!Dcl)
12455 return true;
12456
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012457 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12458 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012459 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012460 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012461 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012462
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012463 return Dcl;
12464}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012465
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012466void Sema::LoadExternalVTableUses() {
12467 if (!ExternalSource)
12468 return;
12469
12470 SmallVector<ExternalVTableUse, 4> VTables;
12471 ExternalSource->ReadUsedVTables(VTables);
12472 SmallVector<VTableUse, 4> NewUses;
12473 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12474 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12475 = VTablesUsed.find(VTables[I].Record);
12476 // Even if a definition wasn't required before, it may be required now.
12477 if (Pos != VTablesUsed.end()) {
12478 if (!Pos->second && VTables[I].DefinitionRequired)
12479 Pos->second = true;
12480 continue;
12481 }
12482
12483 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12484 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12485 }
12486
12487 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12488}
12489
Douglas Gregor88d292c2010-05-13 16:44:06 +000012490void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12491 bool DefinitionRequired) {
12492 // Ignore any vtable uses in unevaluated operands or for classes that do
12493 // not have a vtable.
12494 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012495 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012496 return;
12497
Douglas Gregor88d292c2010-05-13 16:44:06 +000012498 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012499 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012500 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12501 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12502 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12503 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012504 // If we already had an entry, check to see if we are promoting this vtable
12505 // to required a definition. If so, we need to reappend to the VTableUses
12506 // list, since we may have already processed the first entry.
12507 if (DefinitionRequired && !Pos.first->second) {
12508 Pos.first->second = true;
12509 } else {
12510 // Otherwise, we can early exit.
12511 return;
12512 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012513 } else {
12514 // The Microsoft ABI requires that we perform the destructor body
12515 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12516 // the deleting destructor is emitted with the vtable, not with the
12517 // destructor definition as in the Itanium ABI.
12518 // If it has a definition, we do the check at that point instead.
12519 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12520 Class->hasUserDeclaredDestructor() &&
12521 !Class->getDestructor()->isDefined() &&
12522 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012523 CXXDestructorDecl *DD = Class->getDestructor();
12524 ContextRAII SavedContext(*this, DD);
12525 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012526 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012527 }
12528
12529 // Local classes need to have their virtual members marked
12530 // immediately. For all other classes, we mark their virtual members
12531 // at the end of the translation unit.
12532 if (Class->isLocalClass())
12533 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012534 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012535 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012536}
12537
Douglas Gregor88d292c2010-05-13 16:44:06 +000012538bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012539 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012540 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012541 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012542
Douglas Gregor88d292c2010-05-13 16:44:06 +000012543 // Note: The VTableUses vector could grow as a result of marking
12544 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012545 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012546 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012547 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012548 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012549 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012550 if (!Class)
12551 continue;
12552
12553 SourceLocation Loc = VTableUses[I].second;
12554
Richard Smithd3b5c9082012-07-27 04:22:15 +000012555 bool DefineVTable = true;
12556
Douglas Gregor88d292c2010-05-13 16:44:06 +000012557 // If this class has a key function, but that key function is
12558 // defined in another translation unit, we don't need to emit the
12559 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012560 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012561 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012562 // The key function is in another translation unit.
12563 DefineVTable = false;
12564 TemplateSpecializationKind TSK =
12565 KeyFunction->getTemplateSpecializationKind();
12566 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12567 TSK != TSK_ImplicitInstantiation &&
12568 "Instantiations don't have key functions");
12569 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012570 } else if (!KeyFunction) {
12571 // If we have a class with no key function that is the subject
12572 // of an explicit instantiation declaration, suppress the
12573 // vtable; it will live with the explicit instantiation
12574 // definition.
12575 bool IsExplicitInstantiationDeclaration
12576 = Class->getTemplateSpecializationKind()
12577 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012578 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012579 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012580 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012581 if (TSK == TSK_ExplicitInstantiationDeclaration)
12582 IsExplicitInstantiationDeclaration = true;
12583 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12584 IsExplicitInstantiationDeclaration = false;
12585 break;
12586 }
12587 }
12588
12589 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012590 DefineVTable = false;
12591 }
12592
12593 // The exception specifications for all virtual members may be needed even
12594 // if we are not providing an authoritative form of the vtable in this TU.
12595 // We may choose to emit it available_externally anyway.
12596 if (!DefineVTable) {
12597 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12598 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012599 }
12600
12601 // Mark all of the virtual members of this class as referenced, so
12602 // that we can build a vtable. Then, tell the AST consumer that a
12603 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012604 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012605 MarkVirtualMembersReferenced(Loc, Class);
12606 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12607 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12608
12609 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012610 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012611 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012612 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012613 if (!KeyFunction ||
12614 (KeyFunction->hasBody(KeyFunctionDef) &&
12615 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012616 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12617 TSK_ExplicitInstantiationDefinition
12618 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12619 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012620 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012621 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012622 VTableUses.clear();
12623
Douglas Gregor97509692011-04-22 22:25:37 +000012624 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012625}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012626
Richard Smithd3b5c9082012-07-27 04:22:15 +000012627void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12628 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012629 for (const auto *I : RD->methods())
12630 if (I->isVirtual() && !I->isPure())
12631 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012632}
12633
Rafael Espindola5b334082010-03-26 00:36:59 +000012634void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12635 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012636 // Mark all functions which will appear in RD's vtable as used.
12637 CXXFinalOverriderMap FinalOverriders;
12638 RD->getFinalOverriders(FinalOverriders);
12639 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12640 E = FinalOverriders.end();
12641 I != E; ++I) {
12642 for (OverridingMethods::const_iterator OI = I->second.begin(),
12643 OE = I->second.end();
12644 OI != OE; ++OI) {
12645 assert(OI->second.size() > 0 && "no final overrider");
12646 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012647
Richard Smith4ff9ff92012-07-07 06:59:51 +000012648 // C++ [basic.def.odr]p2:
12649 // [...] A virtual member function is used if it is not pure. [...]
12650 if (!Overrider->isPure())
12651 MarkFunctionReferenced(Loc, Overrider);
12652 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012653 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012654
12655 // Only classes that have virtual bases need a VTT.
12656 if (RD->getNumVBases() == 0)
12657 return;
12658
Aaron Ballman574705e2014-03-13 15:41:46 +000012659 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012660 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012661 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012662 if (Base->getNumVBases() == 0)
12663 continue;
12664 MarkVirtualMembersReferenced(Loc, Base);
12665 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012666}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012667
12668/// SetIvarInitializers - This routine builds initialization ASTs for the
12669/// Objective-C implementation whose ivars need be initialized.
12670void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012671 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012672 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012673 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012674 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012675 CollectIvarsToConstructOrDestruct(OID, ivars);
12676 if (ivars.empty())
12677 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012678 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012679 for (unsigned i = 0; i < ivars.size(); i++) {
12680 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012681 if (Field->isInvalidDecl())
12682 continue;
12683
Alexis Hunt1d792652011-01-08 20:30:50 +000012684 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012685 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12686 InitializationKind InitKind =
12687 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012688
12689 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12690 ExprResult MemberInit =
12691 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012692 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012693 // Note, MemberInit could actually come back empty if no initialization
12694 // is required (e.g., because it would call a trivial default constructor)
12695 if (!MemberInit.get() || MemberInit.isInvalid())
12696 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012697
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012698 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012699 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12700 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012701 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012702 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012703 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012704
12705 // Be sure that the destructor is accessible and is marked as referenced.
12706 if (const RecordType *RecordTy
12707 = Context.getBaseElementType(Field->getType())
12708 ->getAs<RecordType>()) {
12709 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012710 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012711 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012712 CheckDestructorAccess(Field->getLocation(), Destructor,
12713 PDiag(diag::err_access_dtor_ivar)
12714 << Context.getBaseElementType(Field->getType()));
12715 }
12716 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012717 }
12718 ObjCImplementation->setIvarInitializers(Context,
12719 AllToInit.data(), AllToInit.size());
12720 }
12721}
Alexis Hunt6118d662011-05-04 05:57:24 +000012722
Alexis Hunt27a761d2011-05-04 23:29:54 +000012723static
12724void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12725 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12726 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12727 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12728 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012729 if (Ctor->isInvalidDecl())
12730 return;
12731
Richard Smith802c4b72012-08-23 06:16:52 +000012732 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12733
12734 // Target may not be determinable yet, for instance if this is a dependent
12735 // call in an uninstantiated template.
12736 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012737 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012738 (void)Target->hasBody(FNTarget);
12739 Target = const_cast<CXXConstructorDecl*>(
12740 cast_or_null<CXXConstructorDecl>(FNTarget));
12741 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012742
12743 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12744 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012745 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012746
12747 if (!Current.insert(Canonical))
12748 return;
12749
12750 // We know that beyond here, we aren't chaining into a cycle.
12751 if (!Target || !Target->isDelegatingConstructor() ||
12752 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012753 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012754 Current.clear();
12755 // We've hit a cycle.
12756 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12757 Current.count(TCanonical)) {
12758 // If we haven't diagnosed this cycle yet, do so now.
12759 if (!Invalid.count(TCanonical)) {
12760 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012761 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012762 << Ctor;
12763
Richard Smith802c4b72012-08-23 06:16:52 +000012764 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012765 if (TCanonical != Canonical)
12766 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12767
12768 CXXConstructorDecl *C = Target;
12769 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012770 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012771 (void)C->getTargetConstructor()->hasBody(FNTarget);
12772 assert(FNTarget && "Ctor cycle through bodiless function");
12773
Richard Smith802c4b72012-08-23 06:16:52 +000012774 C = const_cast<CXXConstructorDecl*>(
12775 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012776 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12777 }
12778 }
12779
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012780 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012781 Current.clear();
12782 } else {
12783 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12784 }
12785}
12786
12787
Alexis Hunt6118d662011-05-04 05:57:24 +000012788void Sema::CheckDelegatingCtorCycles() {
12789 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12790
Douglas Gregorbae31202011-07-27 21:57:17 +000012791 for (DelegatingCtorDeclsType::iterator
12792 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012793 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012794 I != E; ++I)
12795 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012796
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012797 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12798 CE = Invalid.end();
12799 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012800 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012801}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012802
Douglas Gregor3024f072012-04-16 07:05:22 +000012803namespace {
12804 /// \brief AST visitor that finds references to the 'this' expression.
12805 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12806 Sema &S;
12807
12808 public:
12809 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12810
12811 bool VisitCXXThisExpr(CXXThisExpr *E) {
12812 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12813 << E->isImplicit();
12814 return false;
12815 }
12816 };
12817}
12818
12819bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12820 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12821 if (!TSInfo)
12822 return false;
12823
12824 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012825 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012826 if (!ProtoTL)
12827 return false;
12828
12829 // C++11 [expr.prim.general]p3:
12830 // [The expression this] shall not appear before the optional
12831 // cv-qualifier-seq and it shall not appear within the declaration of a
12832 // static member function (although its type and value category are defined
12833 // within a static member function as they are within a non-static member
12834 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012835 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012836 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012837 FindCXXThisExpr Finder(*this);
12838
12839 // If the return type came after the cv-qualifier-seq, check it now.
12840 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012841 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012842 return true;
12843
12844 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012845 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12846 return true;
12847
12848 return checkThisInStaticMemberFunctionAttributes(Method);
12849}
12850
12851bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12852 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12853 if (!TSInfo)
12854 return false;
12855
12856 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012857 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012858 if (!ProtoTL)
12859 return false;
12860
David Blaikie6adc78e2013-02-18 22:06:02 +000012861 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012862 FindCXXThisExpr Finder(*this);
12863
Douglas Gregor3024f072012-04-16 07:05:22 +000012864 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012865 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012866 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012867 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012868 case EST_DynamicNone:
12869 case EST_MSAny:
12870 case EST_None:
12871 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012872
Douglas Gregor3024f072012-04-16 07:05:22 +000012873 case EST_ComputedNoexcept:
12874 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12875 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012876
Douglas Gregor3024f072012-04-16 07:05:22 +000012877 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012878 for (const auto &E : Proto->exceptions()) {
12879 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012880 return true;
12881 }
12882 break;
12883 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012884
12885 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012886}
12887
12888bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12889 FindCXXThisExpr Finder(*this);
12890
12891 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012892 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012893 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000012894 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000012895 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012896 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012897 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012898 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012899 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012900 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012901 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012902 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012903 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012904 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012905 Arg = ETLF->getSuccessValue();
12906 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012907 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012908 Arg = STLF->getSuccessValue();
12909 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012910 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012911 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012912 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012913 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012914 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012915 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012916 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012917 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012918 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12919 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12920 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012921 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012922
12923 if (Arg && !Finder.TraverseStmt(Arg))
12924 return true;
12925
12926 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12927 if (!Finder.TraverseStmt(Args[I]))
12928 return true;
12929 }
12930 }
12931
12932 return false;
12933}
12934
Douglas Gregor433e0532012-04-16 18:27:27 +000012935void
12936Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12937 ArrayRef<ParsedType> DynamicExceptions,
12938 ArrayRef<SourceRange> DynamicExceptionRanges,
12939 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012940 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012941 FunctionProtoType::ExtProtoInfo &EPI) {
12942 Exceptions.clear();
12943 EPI.ExceptionSpecType = EST;
12944 if (EST == EST_Dynamic) {
12945 Exceptions.reserve(DynamicExceptions.size());
12946 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12947 // FIXME: Preserve type source info.
12948 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12949
12950 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12951 collectUnexpandedParameterPacks(ET, Unexpanded);
12952 if (!Unexpanded.empty()) {
12953 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12954 UPPC_ExceptionType,
12955 Unexpanded);
12956 continue;
12957 }
12958
12959 // Check that the type is valid for an exception spec, and
12960 // drop it if not.
12961 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12962 Exceptions.push_back(ET);
12963 }
12964 EPI.NumExceptions = Exceptions.size();
12965 EPI.Exceptions = Exceptions.data();
12966 return;
12967 }
12968
12969 if (EST == EST_ComputedNoexcept) {
12970 // If an error occurred, there's no expression here.
12971 if (NoexceptExpr) {
12972 assert((NoexceptExpr->isTypeDependent() ||
12973 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12974 Context.BoolTy) &&
12975 "Parser should have made sure that the expression is boolean");
12976 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12977 EPI.ExceptionSpecType = EST_BasicNoexcept;
12978 return;
12979 }
12980
12981 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000012982 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000012983 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012984 /*AllowFold*/ false).get();
Douglas Gregor433e0532012-04-16 18:27:27 +000012985 EPI.NoexceptExpr = NoexceptExpr;
12986 }
12987 return;
12988 }
12989}
12990
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012991/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12992Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12993 // Implicitly declared functions (e.g. copy constructors) are
12994 // __host__ __device__
12995 if (D->isImplicit())
12996 return CFT_HostDevice;
12997
12998 if (D->hasAttr<CUDAGlobalAttr>())
12999 return CFT_Global;
13000
13001 if (D->hasAttr<CUDADeviceAttr>()) {
13002 if (D->hasAttr<CUDAHostAttr>())
13003 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013004 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013005 }
13006
13007 return CFT_Host;
13008}
13009
13010bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13011 CUDAFunctionTarget CalleeTarget) {
13012 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13013 // Callable from the device only."
13014 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13015 return true;
13016
13017 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13018 // Callable from the host only."
13019 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13020 // Callable from the host only."
13021 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13022 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13023 return true;
13024
13025 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13026 return true;
13027
13028 return false;
13029}
John McCall5e77d762013-04-16 07:28:30 +000013030
13031/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13032///
13033MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13034 SourceLocation DeclStart,
13035 Declarator &D, Expr *BitWidth,
13036 InClassInitStyle InitStyle,
13037 AccessSpecifier AS,
13038 AttributeList *MSPropertyAttr) {
13039 IdentifierInfo *II = D.getIdentifier();
13040 if (!II) {
13041 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013042 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013043 }
13044 SourceLocation Loc = D.getIdentifierLoc();
13045
13046 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13047 QualType T = TInfo->getType();
13048 if (getLangOpts().CPlusPlus) {
13049 CheckExtraCXXDefaultArguments(D);
13050
13051 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13052 UPPC_DataMemberType)) {
13053 D.setInvalidType();
13054 T = Context.IntTy;
13055 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13056 }
13057 }
13058
13059 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13060
13061 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13062 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13063 diag::err_invalid_thread)
13064 << DeclSpec::getSpecifierName(TSCS);
13065
13066 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013067 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013068 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13069 LookupName(Previous, S);
13070 switch (Previous.getResultKind()) {
13071 case LookupResult::Found:
13072 case LookupResult::FoundUnresolvedValue:
13073 PrevDecl = Previous.getAsSingle<NamedDecl>();
13074 break;
13075
13076 case LookupResult::FoundOverloaded:
13077 PrevDecl = Previous.getRepresentativeDecl();
13078 break;
13079
13080 case LookupResult::NotFound:
13081 case LookupResult::NotFoundInCurrentInstantiation:
13082 case LookupResult::Ambiguous:
13083 break;
13084 }
13085
13086 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13087 // Maybe we will complain about the shadowed template parameter.
13088 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13089 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013090 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013091 }
13092
13093 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013094 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013095
13096 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013097 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013098 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13099 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013100 ProcessDeclAttributes(TUScope, NewPD, D);
13101 NewPD->setAccess(AS);
13102
13103 if (NewPD->isInvalidDecl())
13104 Record->setInvalidDecl();
13105
13106 if (D.getDeclSpec().isModulePrivateSpecified())
13107 NewPD->setModulePrivate();
13108
13109 if (NewPD->isInvalidDecl() && PrevDecl) {
13110 // Don't introduce NewFD into scope; there's already something
13111 // with the same name in the same scope.
13112 } else if (II) {
13113 PushOnScopeChains(NewPD, S);
13114 } else
13115 Record->addDecl(NewPD);
13116
13117 return NewPD;
13118}