blob: a03e308f99b044b8abff455942febb13263e77dd [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.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param,
348 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000355 Param->setDefaultArg(new(Context)
356 OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Alp Tokerc5350722014-02-26 22:27:52 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384 ++argIdx) {
385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Toppere4794282012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
Richard Smith541b38b2013-09-20 01:15:31 +0000449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
Richard Smith5971e8c2014-08-27 22:31:34 +0000452 DeclContext *ScopeDC = New->isLocalExternDecl()
453 ? New->getLexicalDeclContext()
454 : New->getDeclContext();
455 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000456 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
Richard Smith5971e8c2014-08-27 22:31:34 +0000461 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
462 // If only one of these is a local function declaration, then they are
463 // declared in different scopes, even though isDeclInScope may think
464 // they're in the same scope. (If both are local, the scope check is
465 // sufficent, and if neither is local, then they are in the same scope.)
466 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000467
468 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000469
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000470 unsigned DiagDefaultParamID =
471 diag::err_param_default_argument_redefinition;
472
473 // MSVC accepts that default parameters be redefined for member functions
474 // of template class. The new default parameter's value is ignored.
475 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000476 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000477 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
478 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000479 // Merge the old default argument into the new parameter.
480 NewParam->setHasInheritedDefaultArg();
481 if (OldParam->hasUninstantiatedDefaultArg())
482 NewParam->setUninstantiatedDefaultArg(
483 OldParam->getUninstantiatedDefaultArg());
484 else
485 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000486 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000487 Invalid = false;
488 }
489 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000490
Francois Pichet8cb243a2011-04-10 04:58:30 +0000491 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
492 // hint here. Alternatively, we could walk the type-source information
493 // for NewParam to find the last source location in the type... but it
494 // isn't worth the effort right now. This is the kind of test case that
495 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 // int f(int);
497 // void g(int (*fp)(int) = f);
498 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000499 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000500 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000501
502 // Look for the function declaration where the default argument was
503 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000504 for (FunctionDecl *Older = Old->getPreviousDecl();
505 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000506 if (!Older->getParamDecl(p)->hasDefaultArg())
507 break;
508
509 OldParam = Older->getParamDecl(p);
510 }
511
512 Diag(OldParam->getLocation(), diag::note_previous_definition)
513 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000514 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000515 // Merge the old default argument into the new parameter.
516 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000517 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000518 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000519 if (OldParam->hasUninstantiatedDefaultArg())
520 NewParam->setUninstantiatedDefaultArg(
521 OldParam->getUninstantiatedDefaultArg());
522 else
John McCalle61b02b2010-05-04 01:53:42 +0000523 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000524 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000525 if (New->getDescribedFunctionTemplate()) {
526 // Paragraph 4, quoted above, only applies to non-template functions.
527 Diag(NewParam->getLocation(),
528 diag::err_param_default_argument_template_redecl)
529 << NewParam->getDefaultArgRange();
530 Diag(Old->getLocation(), diag::note_template_prev_declaration)
531 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000532 } else if (New->getTemplateSpecializationKind()
533 != TSK_ImplicitInstantiation &&
534 New->getTemplateSpecializationKind() != TSK_Undeclared) {
535 // C++ [temp.expr.spec]p21:
536 // Default function arguments shall not be specified in a declaration
537 // or a definition for one of the following explicit specializations:
538 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000539 // - the explicit specialization of a member function template;
540 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000541 // template where the class template specialization to which the
542 // member function specialization belongs is implicitly
543 // instantiated.
544 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
545 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
546 << New->getDeclName()
547 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000548 } else if (New->getDeclContext()->isDependentContext()) {
549 // C++ [dcl.fct.default]p6 (DR217):
550 // Default arguments for a member function of a class template shall
551 // be specified on the initial declaration of the member function
552 // within the class template.
553 //
554 // Reading the tea leaves a bit in DR217 and its reference to DR205
555 // leads me to the conclusion that one cannot add default function
556 // arguments for an out-of-line definition of a member function of a
557 // dependent type.
558 int WhichKind = 2;
559 if (CXXRecordDecl *Record
560 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
561 if (Record->getDescribedClassTemplate())
562 WhichKind = 0;
563 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
564 WhichKind = 1;
565 else
566 WhichKind = 2;
567 }
568
569 Diag(NewParam->getLocation(),
570 diag::err_param_default_argument_member_template_redecl)
571 << WhichKind
572 << NewParam->getDefaultArgRange();
573 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000574 }
575 }
576
Richard Smith58c3cc12012-11-28 03:45:24 +0000577 // DR1344: If a default argument is added outside a class definition and that
578 // default argument makes the function a special member function, the program
579 // is ill-formed. This can only happen for constructors.
580 if (isa<CXXConstructorDecl>(New) &&
581 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
582 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
583 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
584 if (NewSM != OldSM) {
585 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
586 assert(NewParam->hasDefaultArg());
587 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
588 << NewParam->getDefaultArgRange() << NewSM;
589 Diag(Old->getLocation(), diag::note_previous_declaration);
590 }
591 }
592
David Majnemeree4f4022014-03-30 06:44:54 +0000593 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000594 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000595 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000596 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000597 if (New->isConstexpr() != Old->isConstexpr()) {
598 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
599 << New << New->isConstexpr();
600 Diag(Old->getLocation(), diag::note_previous_declaration);
601 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000602 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
603 // C++11 [dcl.fcn.spec]p4:
604 // If the definition of a function appears in a translation unit before its
605 // first declaration as inline, the program is ill-formed.
606 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
607 Diag(Def->getLocation(), diag::note_previous_definition);
608 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000609 }
610
David Majnemer502b0ed2013-06-25 23:09:30 +0000611 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000612 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000613 // the only declaration of the function or function template in the
614 // translation unit.
615 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
616 functionDeclHasDefaultArgument(Old)) {
617 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
618 Diag(Old->getLocation(), diag::note_previous_declaration);
619 Invalid = true;
620 }
621
Douglas Gregorf40863c2010-02-12 07:32:17 +0000622 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000623 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000624
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000625 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000626}
627
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000628/// \brief Merge the exception specifications of two variable declarations.
629///
630/// This is called when there's a redeclaration of a VarDecl. The function
631/// checks if the redeclaration might have an exception specification and
632/// validates compatibility and merges the specs if necessary.
633void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
634 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000636 return;
637
638 assert(Context.hasSameType(New->getType(), Old->getType()) &&
639 "Should only be called if types are otherwise the same.");
640
641 QualType NewType = New->getType();
642 QualType OldType = Old->getType();
643
644 // We're only interested in pointers and references to functions, as well
645 // as pointers to member functions.
646 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
647 NewType = R->getPointeeType();
648 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
649 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
650 NewType = P->getPointeeType();
651 OldType = OldType->getAs<PointerType>()->getPointeeType();
652 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
653 NewType = M->getPointeeType();
654 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
655 }
656
657 if (!NewType->isFunctionProtoType())
658 return;
659
660 // There's lots of special cases for functions. For function pointers, system
661 // libraries are hopefully not as broken so that we don't need these
662 // workarounds.
663 if (CheckEquivalentExceptionSpec(
664 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
665 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
666 New->setInvalidDecl();
667 }
668}
669
Chris Lattner199abbc2008-04-08 05:04:30 +0000670/// CheckCXXDefaultArguments - Verify that the default arguments for a
671/// function declaration are well-formed according to C++
672/// [dcl.fct.default].
673void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
674 unsigned NumParams = FD->getNumParams();
675 unsigned p;
676
677 // Find first parameter with a default argument
678 for (p = 0; p < NumParams; ++p) {
679 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000680 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000681 break;
682 }
683
684 // C++ [dcl.fct.default]p4:
685 // In a given function declaration, all parameters
686 // subsequent to a parameter with a default argument shall
687 // have default arguments supplied in this or previous
688 // declarations. A default argument shall not be redefined
689 // by a later declaration (not even to the same value).
690 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000691 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000692 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000693 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000694 if (Param->isInvalidDecl())
695 /* We already complained about this parameter. */;
696 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000697 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000698 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000699 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000700 else
Mike Stump11289f42009-09-09 15:08:12 +0000701 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000702 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattner199abbc2008-04-08 05:04:30 +0000704 LastMissingDefaultArg = p;
705 }
706 }
707
708 if (LastMissingDefaultArg > 0) {
709 // Some default arguments were missing. Clear out all of the
710 // default arguments up to (and including) the last missing
711 // default argument, so that we leave the function parameters
712 // in a semantically valid state.
713 for (p = 0; p <= LastMissingDefaultArg; ++p) {
714 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000715 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000716 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000717 }
718 }
719 }
720}
Douglas Gregor556877c2008-04-13 21:30:24 +0000721
Richard Smitheb3c10c2011-10-01 02:31:28 +0000722// CheckConstexprParameterTypes - Check whether a function's parameter types
723// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000724// diagnostic and return false.
725static bool CheckConstexprParameterTypes(Sema &SemaRef,
726 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000727 unsigned ArgIndex = 0;
728 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000729 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
730 e = FT->param_type_end();
731 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000732 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
733 SourceLocation ParamLoc = PD->getLocation();
734 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000735 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000736 diag::err_constexpr_non_literal_param,
737 ArgIndex+1, PD->getSourceRange(),
738 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000739 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000740 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000741 return true;
742}
743
744/// \brief Get diagnostic %select index for tag kind for
745/// record diagnostic message.
746/// WARNING: Indexes apply to particular diagnostics only!
747///
748/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000749static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000750 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000751 case TTK_Struct: return 0;
752 case TTK_Interface: return 1;
753 case TTK_Class: return 2;
754 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000755 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000756}
757
758// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
759// the requirements of a constexpr function definition or a constexpr
760// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000761// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000762//
Richard Smith3607ffe2012-02-13 03:54:03 +0000763// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
764bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000765 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
766 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000767 // C++11 [dcl.constexpr]p4:
768 // The definition of a constexpr constructor shall satisfy the following
769 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000770 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000771 const CXXRecordDecl *RD = MD->getParent();
772 if (RD->getNumVBases()) {
773 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
774 << isa<CXXConstructorDecl>(NewFD)
775 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000776 for (const auto &I : RD->vbases())
777 Diag(I.getLocStart(),
778 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 return false;
780 }
Richard Smith7971b692012-01-13 04:54:00 +0000781 }
782
783 if (!isa<CXXConstructorDecl>(NewFD)) {
784 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000785 // The definition of a constexpr function shall satisfy the following
786 // constraints:
787 // - it shall not be virtual;
788 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
789 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000790 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000791
Richard Smith3607ffe2012-02-13 03:54:03 +0000792 // If it's not obvious why this function is virtual, find an overridden
793 // function which uses the 'virtual' keyword.
794 const CXXMethodDecl *WrittenVirtual = Method;
795 while (!WrittenVirtual->isVirtualAsWritten())
796 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
797 if (WrittenVirtual != Method)
798 Diag(WrittenVirtual->getLocation(),
799 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000800 return false;
801 }
802
803 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000804 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000805 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000807 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 }
810
Richard Smith7971b692012-01-13 04:54:00 +0000811 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000812 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000813 return false;
814
Richard Smitheb3c10c2011-10-01 02:31:28 +0000815 return true;
816}
817
818/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000819/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820///
Richard Smithd9f663b2013-04-22 15:31:51 +0000821/// \return true if the body is OK (maybe only as an extension), false if we
822/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000824 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
825 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
827 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000828 for (const auto *DclIt : DS->decls()) {
829 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000830 case Decl::StaticAssert:
831 case Decl::Using:
832 case Decl::UsingShadow:
833 case Decl::UsingDirective:
834 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000835 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000836 // - static_assert-declarations
837 // - using-declarations,
838 // - using-directives,
839 continue;
840
841 case Decl::Typedef:
842 case Decl::TypeAlias: {
843 // - typedef declarations and alias-declarations that do not define
844 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000845 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000846 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
847 // Don't allow variably-modified types in constexpr functions.
848 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
849 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
850 << TL.getSourceRange() << TL.getType()
851 << isa<CXXConstructorDecl>(Dcl);
852 return false;
853 }
854 continue;
855 }
856
857 case Decl::Enum:
858 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000859 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000860 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000861 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000862 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000863 ? diag::warn_cxx11_compat_constexpr_type_definition
864 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000865 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000866 continue;
867
Richard Smithd9f663b2013-04-22 15:31:51 +0000868 case Decl::EnumConstant:
869 case Decl::IndirectField:
870 case Decl::ParmVar:
871 // These can only appear with other declarations which are banned in
872 // C++11 and permitted in C++1y, so ignore them.
873 continue;
874
875 case Decl::Var: {
876 // C++1y [dcl.constexpr]p3 allows anything except:
877 // a definition of a variable of non-literal type or of static or
878 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000879 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000880 if (VD->isThisDeclarationADefinition()) {
881 if (VD->isStaticLocal()) {
882 SemaRef.Diag(VD->getLocation(),
883 diag::err_constexpr_local_var_static)
884 << isa<CXXConstructorDecl>(Dcl)
885 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
886 return false;
887 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000888 if (!VD->getType()->isDependentType() &&
889 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000890 VD->getLocation(), VD->getType(),
891 diag::err_constexpr_local_var_non_literal_type,
892 isa<CXXConstructorDecl>(Dcl)))
893 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000894 if (!VD->getType()->isDependentType() &&
895 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000896 SemaRef.Diag(VD->getLocation(),
897 diag::err_constexpr_local_var_no_init)
898 << isa<CXXConstructorDecl>(Dcl);
899 return false;
900 }
901 }
902 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000903 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000904 ? diag::warn_cxx11_compat_constexpr_local_var
905 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000907 continue;
908 }
909
910 case Decl::NamespaceAlias:
911 case Decl::Function:
912 // These are disallowed in C++11 and permitted in C++1y. Allow them
913 // everywhere as an extension.
914 if (!Cxx1yLoc.isValid())
915 Cxx1yLoc = DS->getLocStart();
916 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000917
918 default:
919 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
920 << isa<CXXConstructorDecl>(Dcl);
921 return false;
922 }
923 }
924
925 return true;
926}
927
928/// Check that the given field is initialized within a constexpr constructor.
929///
930/// \param Dcl The constexpr constructor being checked.
931/// \param Field The field being checked. This may be a member of an anonymous
932/// struct or union nested within the class being checked.
933/// \param Inits All declarations, including anonymous struct/union members and
934/// indirect members, for which any initialization was provided.
935/// \param Diagnosed Set to true if an error is produced.
936static void CheckConstexprCtorInitializer(Sema &SemaRef,
937 const FunctionDecl *Dcl,
938 FieldDecl *Field,
939 llvm::SmallSet<Decl*, 16> &Inits,
940 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000941 if (Field->isInvalidDecl())
942 return;
943
Douglas Gregor556e5862011-10-10 17:22:13 +0000944 if (Field->isUnnamedBitfield())
945 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000946
Richard Smithab44d5b2013-12-10 08:25:00 +0000947 // Anonymous unions with no variant members and empty anonymous structs do not
948 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
949 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000950 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000951 (Field->getType()->isUnionType()
952 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
953 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000954 return;
955
Richard Smitheb3c10c2011-10-01 02:31:28 +0000956 if (!Inits.count(Field)) {
957 if (!Diagnosed) {
958 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
959 Diagnosed = true;
960 }
961 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
962 } else if (Field->isAnonymousStructOrUnion()) {
963 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000964 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000965 // If an anonymous union contains an anonymous struct of which any member
966 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000967 if (!RD->isUnion() || Inits.count(I))
968 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000969 }
970}
971
Richard Smithd9f663b2013-04-22 15:31:51 +0000972/// Check the provided statement is allowed in a constexpr function
973/// definition.
974static bool
975CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000976 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000977 SourceLocation &Cxx1yLoc) {
978 // - its function-body shall be [...] a compound-statement that contains only
979 switch (S->getStmtClass()) {
980 case Stmt::NullStmtClass:
981 // - null statements,
982 return true;
983
984 case Stmt::DeclStmtClass:
985 // - static_assert-declarations
986 // - using-declarations,
987 // - using-directives,
988 // - typedef declarations and alias-declarations that do not define
989 // classes or enumerations,
990 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
991 return false;
992 return true;
993
994 case Stmt::ReturnStmtClass:
995 // - and exactly one return statement;
996 if (isa<CXXConstructorDecl>(Dcl)) {
997 // C++1y allows return statements in constexpr constructors.
998 if (!Cxx1yLoc.isValid())
999 Cxx1yLoc = S->getLocStart();
1000 return true;
1001 }
1002
1003 ReturnStmts.push_back(S->getLocStart());
1004 return true;
1005
1006 case Stmt::CompoundStmtClass: {
1007 // C++1y allows compound-statements.
1008 if (!Cxx1yLoc.isValid())
1009 Cxx1yLoc = S->getLocStart();
1010
1011 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001012 for (auto *BodyIt : CompStmt->body()) {
1013 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001014 Cxx1yLoc))
1015 return false;
1016 }
1017 return true;
1018 }
1019
1020 case Stmt::AttributedStmtClass:
1021 if (!Cxx1yLoc.isValid())
1022 Cxx1yLoc = S->getLocStart();
1023 return true;
1024
1025 case Stmt::IfStmtClass: {
1026 // C++1y allows if-statements.
1027 if (!Cxx1yLoc.isValid())
1028 Cxx1yLoc = S->getLocStart();
1029
1030 IfStmt *If = cast<IfStmt>(S);
1031 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1032 Cxx1yLoc))
1033 return false;
1034 if (If->getElse() &&
1035 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1036 Cxx1yLoc))
1037 return false;
1038 return true;
1039 }
1040
1041 case Stmt::WhileStmtClass:
1042 case Stmt::DoStmtClass:
1043 case Stmt::ForStmtClass:
1044 case Stmt::CXXForRangeStmtClass:
1045 case Stmt::ContinueStmtClass:
1046 // C++1y allows all of these. We don't allow them as extensions in C++11,
1047 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001048 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001049 break;
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1052 for (Stmt::child_range Children = S->children(); Children; ++Children)
1053 if (*Children &&
1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055 Cxx1yLoc))
1056 return false;
1057 return true;
1058
1059 case Stmt::SwitchStmtClass:
1060 case Stmt::CaseStmtClass:
1061 case Stmt::DefaultStmtClass:
1062 case Stmt::BreakStmtClass:
1063 // C++1y allows switch-statements, and since they don't need variable
1064 // mutation, we can reasonably allow them in C++11 as an extension.
1065 if (!Cxx1yLoc.isValid())
1066 Cxx1yLoc = S->getLocStart();
1067 for (Stmt::child_range Children = S->children(); Children; ++Children)
1068 if (*Children &&
1069 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1070 Cxx1yLoc))
1071 return false;
1072 return true;
1073
1074 default:
1075 if (!isa<Expr>(S))
1076 break;
1077
1078 // C++1y allows expression-statements.
1079 if (!Cxx1yLoc.isValid())
1080 Cxx1yLoc = S->getLocStart();
1081 return true;
1082 }
1083
1084 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1085 << isa<CXXConstructorDecl>(Dcl);
1086 return false;
1087}
1088
Richard Smitheb3c10c2011-10-01 02:31:28 +00001089/// Check the body for the given constexpr function declaration only contains
1090/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1091///
1092/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001093bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001094 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001095 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 // The definition of a constexpr function shall satisfy the following
1097 // constraints: [...]
1098 // - its function-body shall be = delete, = default, or a
1099 // compound-statement
1100 //
Richard Smith74388b42012-02-04 00:33:54 +00001101 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001102 // In the definition of a constexpr constructor, [...]
1103 // - its function-body shall not be a function-try-block;
1104 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1105 << isa<CXXConstructorDecl>(Dcl);
1106 return false;
1107 }
1108
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001109 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001110
1111 // - its function-body shall be [...] a compound-statement that contains only
1112 // [... list of cases ...]
1113 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1114 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001115 for (auto *BodyIt : CompBody->body()) {
1116 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001117 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001118 }
1119
Richard Smithd9f663b2013-04-22 15:31:51 +00001120 if (Cxx1yLoc.isValid())
1121 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001122 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001123 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1124 : diag::ext_constexpr_body_invalid_stmt)
1125 << isa<CXXConstructorDecl>(Dcl);
1126
Richard Smitheb3c10c2011-10-01 02:31:28 +00001127 if (const CXXConstructorDecl *Constructor
1128 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1129 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001130 // DR1359:
1131 // - every non-variant non-static data member and base class sub-object
1132 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001133 // DR1460:
1134 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001135 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001136 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001137 if (Constructor->getNumCtorInitializers() == 0 &&
1138 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001139 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1140 return false;
1141 }
Richard Smithf368fb42011-10-10 16:38:04 +00001142 } else if (!Constructor->isDependentContext() &&
1143 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001144 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1145
1146 // Skip detailed checking if we have enough initializers, and we would
1147 // allow at most one initializer per member.
1148 bool AnyAnonStructUnionMembers = false;
1149 unsigned Fields = 0;
1150 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1151 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001152 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001153 AnyAnonStructUnionMembers = true;
1154 break;
1155 }
1156 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001157 // DR1460:
1158 // - if the class is a union-like class, but is not a union, for each of
1159 // its anonymous union members having variant members, exactly one of
1160 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001161 if (AnyAnonStructUnionMembers ||
1162 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1163 // Check initialization of non-static data members. Base classes are
1164 // always initialized so do not need to be checked. Dependent bases
1165 // might not have initializers in the member initializer list.
1166 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001167 for (const auto *I: Constructor->inits()) {
1168 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001169 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001170 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 Inits.insert(ID->chain_begin(), ID->chain_end());
1172 }
1173
1174 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001175 for (auto *I : RD->fields())
1176 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 if (Diagnosed)
1178 return false;
1179 }
1180 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001181 } else {
1182 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001183 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001184 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001185 // otherwise if there's no return statement, the function cannot
1186 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001187 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001188 (Dcl->getReturnType()->isVoidType() ||
1189 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001190 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001191 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1192 : diag::err_constexpr_body_no_return);
1193 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 }
1195 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001196 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001197 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001198 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1199 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001200 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1201 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001202 }
1203 }
1204
Richard Smith74388b42012-02-04 00:33:54 +00001205 // C++11 [dcl.constexpr]p5:
1206 // if no function argument values exist such that the function invocation
1207 // substitution would produce a constant expression, the program is
1208 // ill-formed; no diagnostic required.
1209 // C++11 [dcl.constexpr]p3:
1210 // - every constructor call and implicit conversion used in initializing the
1211 // return value shall be one of those allowed in a constant expression.
1212 // C++11 [dcl.constexpr]p4:
1213 // - every constructor involved in initializing non-static data members and
1214 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001215 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001216 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001217 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001218 << isa<CXXConstructorDecl>(Dcl);
1219 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1220 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001221 // Don't return false here: we allow this for compatibility in
1222 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001223 }
1224
Richard Smitheb3c10c2011-10-01 02:31:28 +00001225 return true;
1226}
1227
Douglas Gregor61956c42008-10-31 09:07:45 +00001228/// isCurrentClassName - Determine whether the identifier II is the
1229/// name of the class type currently being defined. In the case of
1230/// nested classes, this will only return true if II is the name of
1231/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001232bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1233 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001234 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001235
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001236 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001237 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001238 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001239 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1240 } else
1241 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1242
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001243 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001244 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001245 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001246}
1247
Richard Smithfb8b7b92013-10-15 00:00:26 +00001248/// \brief Determine whether the identifier II is a typo for the name of
1249/// the class type currently being defined. If so, update it to the identifier
1250/// that should have been used.
1251bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1252 assert(getLangOpts().CPlusPlus && "No class names in C!");
1253
1254 if (!getLangOpts().SpellChecking)
1255 return false;
1256
1257 CXXRecordDecl *CurDecl;
1258 if (SS && SS->isSet() && !SS->isInvalid()) {
1259 DeclContext *DC = computeDeclContext(*SS, true);
1260 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1261 } else
1262 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1263
1264 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1265 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1266 < II->getLength()) {
1267 II = CurDecl->getIdentifier();
1268 return true;
1269 }
1270
1271 return false;
1272}
1273
Douglas Gregordc974572012-11-10 07:24:09 +00001274/// \brief Determine whether the given class is a base class of the given
1275/// class, including looking at dependent bases.
1276static bool findCircularInheritance(const CXXRecordDecl *Class,
1277 const CXXRecordDecl *Current) {
1278 SmallVector<const CXXRecordDecl*, 8> Queue;
1279
1280 Class = Class->getCanonicalDecl();
1281 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001282 for (const auto &I : Current->bases()) {
1283 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001284 if (!Base)
1285 continue;
1286
1287 Base = Base->getDefinition();
1288 if (!Base)
1289 continue;
1290
1291 if (Base->getCanonicalDecl() == Class)
1292 return true;
1293
1294 Queue.push_back(Base);
1295 }
1296
1297 if (Queue.empty())
1298 return false;
1299
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001300 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001301 }
1302
1303 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001304}
1305
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001306/// \brief Perform propagation of DLL attributes from a derived class to a
1307/// templated base class for MS compatibility.
1308static void propagateDLLAttrToBaseClassTemplate(
1309 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1310 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1311 if (getDLLAttr(
1312 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1313 // If the base class template has a DLL attribute, don't try to change it.
1314 return;
1315 }
1316
1317 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1318 // If the base class is not already specialized, we can do the propagation.
1319 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1320 NewAttr->setInherited(true);
1321 BaseTemplateSpec->addAttr(NewAttr);
1322 return;
1323 }
1324
1325 bool DifferentAttribute = false;
1326 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1327 if (!SpecializationAttr->isInherited()) {
1328 // The template has previously been specialized or instantiated with an
1329 // explicit attribute. We should not try to change it.
1330 return;
1331 }
1332 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1333 // The specialization already has the right attribute.
1334 return;
1335 }
1336 DifferentAttribute = true;
1337 }
1338
1339 // The template was previously instantiated or explicitly specialized without
1340 // a dll attribute, or the template was previously instantiated with a
1341 // different inherited attribute. It's too late for us to change the
1342 // attribute, so warn that this is unsupported.
1343 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1344 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1345 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1346 if (BaseTemplateSpec->isExplicitSpecialization()) {
1347 S.Diag(BaseTemplateSpec->getLocation(),
1348 diag::note_template_class_explicit_specialization_was_here)
1349 << BaseTemplateSpec;
1350 } else {
1351 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1352 diag::note_template_class_instantiation_was_here)
1353 << BaseTemplateSpec;
1354 }
1355}
1356
Mike Stump11289f42009-09-09 15:08:12 +00001357/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001358///
1359/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1360/// and returns NULL otherwise.
1361CXXBaseSpecifier *
1362Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1363 SourceRange SpecifierRange,
1364 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001365 TypeSourceInfo *TInfo,
1366 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001367 QualType BaseType = TInfo->getType();
1368
Douglas Gregor463421d2009-03-03 04:44:36 +00001369 // C++ [class.union]p1:
1370 // A union shall not have base classes.
1371 if (Class->isUnion()) {
1372 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1373 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001374 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001375 }
1376
Douglas Gregor752a5952011-01-03 22:36:02 +00001377 if (EllipsisLoc.isValid() &&
1378 !TInfo->getType()->containsUnexpandedParameterPack()) {
1379 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1380 << TInfo->getTypeLoc().getSourceRange();
1381 EllipsisLoc = SourceLocation();
1382 }
Douglas Gregor62004702012-11-10 01:18:17 +00001383
1384 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1385
1386 if (BaseType->isDependentType()) {
1387 // Make sure that we don't have circular inheritance among our dependent
1388 // bases. For non-dependent bases, the check for completeness below handles
1389 // this.
1390 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1391 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1392 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001393 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001394 Diag(BaseLoc, diag::err_circular_inheritance)
1395 << BaseType << Context.getTypeDeclType(Class);
1396
1397 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1398 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1399 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001400
1401 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001402 }
1403 }
1404
Mike Stump11289f42009-09-09 15:08:12 +00001405 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001406 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001407 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001408 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001409
1410 // Base specifiers must be record types.
1411 if (!BaseType->isRecordType()) {
1412 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001414 }
1415
1416 // C++ [class.union]p1:
1417 // A union shall not be used as a base class.
1418 if (BaseType->isUnionType()) {
1419 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001420 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001421 }
1422
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001423 // For the MS ABI, propagate DLL attributes to base class templates.
1424 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1425 if (Attr *ClassAttr = getDLLAttr(Class)) {
1426 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1427 BaseType->getAsCXXRecordDecl())) {
1428 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1429 BaseTemplate, BaseLoc);
1430 }
1431 }
1432 }
1433
Douglas Gregor463421d2009-03-03 04:44:36 +00001434 // C++ [class.derived]p2:
1435 // The class-name in a base-specifier shall not be an incompletely
1436 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001437 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001438 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001439 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001440 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001441 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001442
Eli Friedmanc96d4962009-08-15 21:55:26 +00001443 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001444 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001445 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001446 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001447 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001448 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001449 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001450
David Majnemer9b1754d2013-11-02 12:00:36 +00001451 // A class which contains a flexible array member is not suitable for use as a
1452 // base class:
1453 // - If the layout determines that a base comes before another base,
1454 // the flexible array member would index into the subsequent base.
1455 // - If the layout determines that base comes before the derived class,
1456 // the flexible array member would index into the derived class.
1457 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1458 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1459 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001460 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001461 }
1462
Anders Carlsson65c76d32011-03-25 14:55:14 +00001463 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001464 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001465 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001466 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001467 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001468 << CXXBaseDecl->getDeclName()
1469 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001470 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1471 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001472 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001473 }
1474
John McCall3696dcb2010-08-17 07:23:57 +00001475 if (BaseDecl->isInvalidDecl())
1476 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001477
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001478 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001479 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001480 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001481 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001482}
1483
Douglas Gregor556877c2008-04-13 21:30:24 +00001484/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1485/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001486/// example:
1487/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001488/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001489BaseResult
John McCall48871652010-08-21 09:40:31 +00001490Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001491 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001492 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001493 ParsedType basetype, SourceLocation BaseLoc,
1494 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001495 if (!classdecl)
1496 return true;
1497
Douglas Gregorc40290e2009-03-09 23:48:35 +00001498 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001499 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001500 if (!Class)
1501 return true;
1502
David Majnemer5ef4fe72014-06-13 06:43:46 +00001503 // We haven't yet attached the base specifiers.
1504 Class->setIsParsingBaseSpecifiers();
1505
Richard Smith4c96e992013-02-19 23:47:15 +00001506 // We do not support any C++11 attributes on base-specifiers yet.
1507 // Diagnose any attributes we see.
1508 if (!Attributes.empty()) {
1509 for (AttributeList *Attr = Attributes.getList(); Attr;
1510 Attr = Attr->getNext()) {
1511 if (Attr->isInvalid() ||
1512 Attr->getKind() == AttributeList::IgnoredAttribute)
1513 continue;
1514 Diag(Attr->getLoc(),
1515 Attr->getKind() == AttributeList::UnknownAttribute
1516 ? diag::warn_unknown_attribute_ignored
1517 : diag::err_base_specifier_attribute)
1518 << Attr->getName();
1519 }
1520 }
1521
Craig Topperc3ec1492014-05-26 06:22:03 +00001522 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001523 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001524
Douglas Gregor752a5952011-01-03 22:36:02 +00001525 if (EllipsisLoc.isInvalid() &&
1526 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001527 UPPC_BaseType))
1528 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001529
Douglas Gregor463421d2009-03-03 04:44:36 +00001530 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001531 Virtual, Access, TInfo,
1532 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001533 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001534 else
1535 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001536
Douglas Gregor463421d2009-03-03 04:44:36 +00001537 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001538}
Douglas Gregor556877c2008-04-13 21:30:24 +00001539
Douglas Gregor463421d2009-03-03 04:44:36 +00001540/// \brief Performs the actual work of attaching the given base class
1541/// specifiers to a C++ class.
1542bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1543 unsigned NumBases) {
1544 if (NumBases == 0)
1545 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001546
1547 // Used to keep track of which base types we have already seen, so
1548 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001549 // that the key is always the unqualified canonical type of the base
1550 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001551 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1552
1553 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001554 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001555 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001556 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001557 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001558 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001559 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001560
1561 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1562 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001563 // C++ [class.mi]p3:
1564 // A class shall not be specified as a direct base class of a
1565 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001566 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001567 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001568 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001569 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001570
1571 // Delete the duplicate base class specifier; we're going to
1572 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001573 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001574
1575 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001576 } else {
1577 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001578 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001579 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001580 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1581 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1582 if (Class->isInterface() &&
1583 (!RD->isInterface() ||
1584 KnownBase->getAccessSpecifier() != AS_public)) {
1585 // The Microsoft extension __interface does not permit bases that
1586 // are not themselves public interfaces.
1587 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1588 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1589 << RD->getSourceRange();
1590 Invalid = true;
1591 }
1592 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001593 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001594 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001595 }
1596 }
1597
1598 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001599 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001600
1601 // Delete the remaining (good) base class specifiers, since their
1602 // data has been copied into the CXXRecordDecl.
1603 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001604 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001605
1606 return Invalid;
1607}
1608
1609/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1610/// class, after checking whether there are any duplicate base
1611/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001612void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001613 unsigned NumBases) {
1614 if (!ClassDecl || !Bases || !NumBases)
1615 return;
1616
1617 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001618 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001619}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001620
Douglas Gregor36d1b142009-10-06 17:59:45 +00001621/// \brief Determine whether the type \p Derived is a C++ class that is
1622/// derived from the type \p Base.
1623bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001624 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001625 return false;
John McCalle78aac42010-03-10 03:28:59 +00001626
Douglas Gregor45bb4832013-03-26 23:36:30 +00001627 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001628 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001629 return false;
1630
Douglas Gregor45bb4832013-03-26 23:36:30 +00001631 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001632 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001633 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001634
1635 // If either the base or the derived type is invalid, don't try to
1636 // check whether one is derived from the other.
1637 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1638 return false;
1639
John McCall67da35c2010-02-04 22:26:26 +00001640 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1641 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001642}
1643
1644/// \brief Determine whether the type \p Derived is a C++ class that is
1645/// derived from the type \p Base.
1646bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001647 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001648 return false;
1649
Douglas Gregor45bb4832013-03-26 23:36:30 +00001650 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001651 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001652 return false;
1653
Douglas Gregor45bb4832013-03-26 23:36:30 +00001654 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001655 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001656 return false;
1657
Douglas Gregor36d1b142009-10-06 17:59:45 +00001658 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1659}
1660
Anders Carlssona70cff62010-04-24 19:06:50 +00001661void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001662 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001663 assert(BasePathArray.empty() && "Base path array must be empty!");
1664 assert(Paths.isRecordingPaths() && "Must record paths!");
1665
1666 const CXXBasePath &Path = Paths.front();
1667
1668 // We first go backward and check if we have a virtual base.
1669 // FIXME: It would be better if CXXBasePath had the base specifier for
1670 // the nearest virtual base.
1671 unsigned Start = 0;
1672 for (unsigned I = Path.size(); I != 0; --I) {
1673 if (Path[I - 1].Base->isVirtual()) {
1674 Start = I - 1;
1675 break;
1676 }
1677 }
1678
1679 // Now add all bases.
1680 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001681 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001682}
1683
Douglas Gregor88d292c2010-05-13 16:44:06 +00001684/// \brief Determine whether the given base path includes a virtual
1685/// base class.
John McCallcf142162010-08-07 06:22:56 +00001686bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1687 for (CXXCastPath::const_iterator B = BasePath.begin(),
1688 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001689 B != BEnd; ++B)
1690 if ((*B)->isVirtual())
1691 return true;
1692
1693 return false;
1694}
1695
Douglas Gregor36d1b142009-10-06 17:59:45 +00001696/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1697/// conversion (where Derived and Base are class types) is
1698/// well-formed, meaning that the conversion is unambiguous (and
1699/// that all of the base classes are accessible). Returns true
1700/// and emits a diagnostic if the code is ill-formed, returns false
1701/// otherwise. Loc is the location where this routine should point to
1702/// if there is an error, and Range is the source range to highlight
1703/// if there is an error.
1704bool
1705Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001706 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707 unsigned AmbigiousBaseConvID,
1708 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001709 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001710 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001711 // First, determine whether the path from Derived to Base is
1712 // ambiguous. This is slightly more expensive than checking whether
1713 // the Derived to Base conversion exists, because here we need to
1714 // explore multiple paths to determine if there is an ambiguity.
1715 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1716 /*DetectVirtual=*/false);
1717 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1718 assert(DerivationOkay &&
1719 "Can only be used with a derived-to-base conversion");
1720 (void)DerivationOkay;
1721
1722 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001723 if (InaccessibleBaseID) {
1724 // Check that the base class can be accessed.
1725 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1726 InaccessibleBaseID)) {
1727 case AR_inaccessible:
1728 return true;
1729 case AR_accessible:
1730 case AR_dependent:
1731 case AR_delayed:
1732 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001733 }
John McCall5b0829a2010-02-10 09:31:12 +00001734 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001735
1736 // Build a base path if necessary.
1737 if (BasePath)
1738 BuildBasePathArray(Paths, *BasePath);
1739 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001740 }
1741
David Majnemer626032f2013-06-22 06:43:58 +00001742 if (AmbigiousBaseConvID) {
1743 // We know that the derived-to-base conversion is ambiguous, and
1744 // we're going to produce a diagnostic. Perform the derived-to-base
1745 // search just one more time to compute all of the possible paths so
1746 // that we can print them out. This is more expensive than any of
1747 // the previous derived-to-base checks we've done, but at this point
1748 // performance isn't as much of an issue.
1749 Paths.clear();
1750 Paths.setRecordingPaths(true);
1751 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1752 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1753 (void)StillOkay;
1754
1755 // Build up a textual representation of the ambiguous paths, e.g.,
1756 // D -> B -> A, that will be used to illustrate the ambiguous
1757 // conversions in the diagnostic. We only print one of the paths
1758 // to each base class subobject.
1759 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1760
1761 Diag(Loc, AmbigiousBaseConvID)
1762 << Derived << Base << PathDisplayStr << Range << Name;
1763 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001764 return true;
1765}
1766
1767bool
1768Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001769 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001770 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001771 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001772 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001773 IgnoreAccess ? 0
1774 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001775 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001776 Loc, Range, DeclarationName(),
1777 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001778}
1779
1780
1781/// @brief Builds a string representing ambiguous paths from a
1782/// specific derived class to different subobjects of the same base
1783/// class.
1784///
1785/// This function builds a string that can be used in error messages
1786/// to show the different paths that one can take through the
1787/// inheritance hierarchy to go from the derived class to different
1788/// subobjects of a base class. The result looks something like this:
1789/// @code
1790/// struct D -> struct B -> struct A
1791/// struct D -> struct C -> struct A
1792/// @endcode
1793std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1794 std::string PathDisplayStr;
1795 std::set<unsigned> DisplayedPaths;
1796 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1797 Path != Paths.end(); ++Path) {
1798 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1799 // We haven't displayed a path to this particular base
1800 // class subobject yet.
1801 PathDisplayStr += "\n ";
1802 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1803 for (CXXBasePath::const_iterator Element = Path->begin();
1804 Element != Path->end(); ++Element)
1805 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1806 }
1807 }
1808
1809 return PathDisplayStr;
1810}
1811
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001812//===----------------------------------------------------------------------===//
1813// C++ class member Handling
1814//===----------------------------------------------------------------------===//
1815
Abramo Bagnarad7340582010-06-05 05:09:32 +00001816/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001817bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1818 SourceLocation ASLoc,
1819 SourceLocation ColonLoc,
1820 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001821 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001822 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001823 ASLoc, ColonLoc);
1824 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001825 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001826}
1827
Richard Smith18f07db2012-08-06 03:25:17 +00001828/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001829void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001830 if (D->isInvalidDecl())
1831 return;
1832
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001833 // We only care about "override" and "final" declarations.
1834 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1835 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001836
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001837 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001838
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001839 // We can't check dependent instance methods.
1840 if (MD && MD->isInstance() &&
1841 (MD->getParent()->hasAnyDependentBases() ||
1842 MD->getType()->isDependentType()))
1843 return;
1844
1845 if (MD && !MD->isVirtual()) {
1846 // If we have a non-virtual method, check if if hides a virtual method.
1847 // (In that case, it's most likely the method has the wrong type.)
1848 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1849 FindHiddenVirtualMethods(MD, OverloadedMethods);
1850
1851 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001852 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1853 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001854 diag::override_keyword_hides_virtual_member_function)
1855 << "override" << (OverloadedMethods.size() > 1);
1856 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001857 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001858 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001859 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1860 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001861 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001862 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1863 MD->setInvalidDecl();
1864 return;
1865 }
1866 // Fall through into the general case diagnostic.
1867 // FIXME: We might want to attempt typo correction here.
1868 }
1869
1870 if (!MD || !MD->isVirtual()) {
1871 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1872 Diag(OA->getLocation(),
1873 diag::override_keyword_only_allowed_on_virtual_member_functions)
1874 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1875 D->dropAttr<OverrideAttr>();
1876 }
1877 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1878 Diag(FA->getLocation(),
1879 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001880 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1881 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001882 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001883 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001884 return;
1885 }
Richard Smith18f07db2012-08-06 03:25:17 +00001886
Richard Smith18f07db2012-08-06 03:25:17 +00001887 // C++11 [class.virtual]p5:
1888 // If a virtual function is marked with the virt-specifier override and
1889 // does not override a member function of a base class, the program is
1890 // ill-formed.
1891 bool HasOverriddenMethods =
1892 MD->begin_overridden_methods() != MD->end_overridden_methods();
1893 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1894 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1895 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001896}
1897
Richard Smith18f07db2012-08-06 03:25:17 +00001898/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001899/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001900/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001901bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1902 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001903 FinalAttr *FA = Old->getAttr<FinalAttr>();
1904 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001905 return false;
1906
1907 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001908 << New->getDeclName()
1909 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001910 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1911 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001912}
1913
Daniel Jasper0baec5492012-06-06 08:32:04 +00001914static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001915 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1916 // FIXME: Destruction of ObjC lifetime types has side-effects.
1917 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1918 return !RD->isCompleteDefinition() ||
1919 !RD->hasTrivialDefaultConstructor() ||
1920 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001921 return false;
1922}
1923
John McCall5e77d762013-04-16 07:28:30 +00001924static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001925 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001926 if (it->isDeclspecPropertyAttribute())
1927 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001928 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001929}
1930
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001931/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1932/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001933/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001934/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1935/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001936NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001938 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001939 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001940 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001941 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001942 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1943 DeclarationName Name = NameInfo.getName();
1944 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001945
1946 // For anonymous bitfields, the location should point to the type.
1947 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001948 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001949
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001950 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001951
John McCallb1cd7da2010-06-04 08:34:12 +00001952 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001953 assert(!DS.isFriendSpecified());
1954
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001955 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001956
John McCalldb632ac2012-09-25 07:32:39 +00001957 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1958 // The Microsoft extension __interface only permits public member functions
1959 // and prohibits constructors, destructors, operators, non-public member
1960 // functions, static methods and data members.
1961 unsigned InvalidDecl;
1962 bool ShowDeclName = true;
1963 if (!isFunc)
1964 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1965 else if (AS != AS_public)
1966 InvalidDecl = 2;
1967 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1968 InvalidDecl = 3;
1969 else switch (Name.getNameKind()) {
1970 case DeclarationName::CXXConstructorName:
1971 InvalidDecl = 4;
1972 ShowDeclName = false;
1973 break;
1974
1975 case DeclarationName::CXXDestructorName:
1976 InvalidDecl = 5;
1977 ShowDeclName = false;
1978 break;
1979
1980 case DeclarationName::CXXOperatorName:
1981 case DeclarationName::CXXConversionFunctionName:
1982 InvalidDecl = 6;
1983 break;
1984
1985 default:
1986 InvalidDecl = 0;
1987 break;
1988 }
1989
1990 if (InvalidDecl) {
1991 if (ShowDeclName)
1992 Diag(Loc, diag::err_invalid_member_in_interface)
1993 << (InvalidDecl-1) << Name;
1994 else
1995 Diag(Loc, diag::err_invalid_member_in_interface)
1996 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001997 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001998 }
1999 }
2000
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002001 // C++ 9.2p6: A member shall not be declared to have automatic storage
2002 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002003 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2004 // data members and cannot be applied to names declared const or static,
2005 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002006 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002007 case DeclSpec::SCS_unspecified:
2008 case DeclSpec::SCS_typedef:
2009 case DeclSpec::SCS_static:
2010 break;
2011 case DeclSpec::SCS_mutable:
2012 if (isFunc) {
2013 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002014
Richard Smithb4a9e862013-04-12 22:46:28 +00002015 // FIXME: It would be nicer if the keyword was ignored only for this
2016 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002017 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002018 }
2019 break;
2020 default:
2021 Diag(DS.getStorageClassSpecLoc(),
2022 diag::err_storageclass_invalid_for_member);
2023 D.getMutableDeclSpec().ClearStorageClassSpecs();
2024 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002025 }
2026
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002027 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2028 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002029 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002030
David Blaikie35506f82013-01-30 01:22:18 +00002031 if (DS.isConstexprSpecified() && isInstField) {
2032 SemaDiagnosticBuilder B =
2033 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2034 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2035 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002036 B << 0 << 0;
2037 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2038 B << FixItHint::CreateRemoval(ConstexprLoc);
2039 else {
2040 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2041 D.getMutableDeclSpec().ClearConstexprSpec();
2042 const char *PrevSpec;
2043 unsigned DiagID;
2044 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2045 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2046 (void)Failed;
2047 assert(!Failed && "Making a constexpr member const shouldn't fail");
2048 }
David Blaikie35506f82013-01-30 01:22:18 +00002049 } else {
2050 B << 1;
2051 const char *PrevSpec;
2052 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002053 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002054 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2055 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002056 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002057 "This is the only DeclSpec that should fail to be applied");
2058 B << 1;
2059 } else {
2060 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2061 isInstField = false;
2062 }
2063 }
2064 }
2065
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002066 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002067 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002068 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002069
2070 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002071 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002072 Diag(Loc, diag::err_bad_variable_name)
2073 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002074 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002075 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002076
Benjamin Kramer365082d2012-05-19 16:34:46 +00002077 IdentifierInfo *II = Name.getAsIdentifierInfo();
2078
Douglas Gregor7c26c042011-09-21 14:40:46 +00002079 // Member field could not be with "template" keyword.
2080 // So TemplateParameterLists should be empty in this case.
2081 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002082 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002083 if (TemplateParams->size()) {
2084 // There is no such thing as a member field template.
2085 Diag(D.getIdentifierLoc(), diag::err_template_member)
2086 << II
2087 << SourceRange(TemplateParams->getTemplateLoc(),
2088 TemplateParams->getRAngleLoc());
2089 } else {
2090 // There is an extraneous 'template<>' for this member.
2091 Diag(TemplateParams->getTemplateLoc(),
2092 diag::err_template_member_noparams)
2093 << II
2094 << SourceRange(TemplateParams->getTemplateLoc(),
2095 TemplateParams->getRAngleLoc());
2096 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002097 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002098 }
2099
Douglas Gregora007d362010-10-13 22:19:53 +00002100 if (SS.isSet() && !SS.isInvalid()) {
2101 // The user provided a superfluous scope specifier inside a class
2102 // definition:
2103 //
2104 // class X {
2105 // int X::member;
2106 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002107 if (DeclContext *DC = computeDeclContext(SS, false))
2108 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002109 else
2110 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2111 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002112
Douglas Gregora007d362010-10-13 22:19:53 +00002113 SS.clear();
2114 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002115
John McCall5e77d762013-04-16 07:28:30 +00002116 AttributeList *MSPropertyAttr =
2117 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002118 if (MSPropertyAttr) {
2119 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2120 BitWidth, InitStyle, AS, MSPropertyAttr);
2121 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002122 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002123 isInstField = false;
2124 } else {
2125 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2126 BitWidth, InitStyle, AS);
2127 assert(Member && "HandleField never returns null");
2128 }
2129 } else {
2130 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2131
2132 Member = HandleDeclarator(S, D, TemplateParameterLists);
2133 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002134 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002135
2136 // Non-instance-fields can't have a bitfield.
2137 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002138 if (Member->isInvalidDecl()) {
2139 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002140 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002141 // C++ 9.6p3: A bit-field shall not be a static member.
2142 // "static member 'A' cannot be a bit-field"
2143 Diag(Loc, diag::err_static_not_bitfield)
2144 << Name << BitWidth->getSourceRange();
2145 } else if (isa<TypedefDecl>(Member)) {
2146 // "typedef member 'x' cannot be a bit-field"
2147 Diag(Loc, diag::err_typedef_not_bitfield)
2148 << Name << BitWidth->getSourceRange();
2149 } else {
2150 // A function typedef ("typedef int f(); f a;").
2151 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2152 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002153 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002154 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002155 }
Mike Stump11289f42009-09-09 15:08:12 +00002156
Craig Topperc3ec1492014-05-26 06:22:03 +00002157 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002158 Member->setInvalidDecl();
2159 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002160
2161 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002162
Larisse Voufo39a1e502013-08-06 01:03:05 +00002163 // If we have declared a member function template or static data member
2164 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002165 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2166 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002167 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2168 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002169 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002170
Richard Smith18f07db2012-08-06 03:25:17 +00002171 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002172 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002173 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002174 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2175 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002176
Douglas Gregorf2f08062011-03-08 17:10:18 +00002177 if (VS.getLastLocation().isValid()) {
2178 // Update the end location of a method that has a virt-specifiers.
2179 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2180 MD->setRangeEnd(VS.getLastLocation());
2181 }
Richard Smith18f07db2012-08-06 03:25:17 +00002182
Anders Carlssonc87f8612011-01-20 06:29:02 +00002183 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002184
Douglas Gregor92751d42008-11-17 22:58:34 +00002185 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002186
Daniel Jasper0baec5492012-06-06 08:32:04 +00002187 if (isInstField) {
2188 FieldDecl *FD = cast<FieldDecl>(Member);
2189 FieldCollector->Add(FD);
2190
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002191 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002192 // Remember all explicit private FieldDecls that have a name, no side
2193 // effects and are not part of a dependent type declaration.
2194 if (!FD->isImplicit() && FD->getDeclName() &&
2195 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002196 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002197 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002198 !InitializationHasSideEffects(*FD))
2199 UnusedPrivateFields.insert(FD);
2200 }
2201 }
2202
John McCall48871652010-08-21 09:40:31 +00002203 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002204}
2205
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002206namespace {
2207 class UninitializedFieldVisitor
2208 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2209 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002210 // List of Decls to generate a warning on. Also remove Decls that become
2211 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002212 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu8d08a272014-08-28 03:23:47 +00002213 // Vector of decls to be removed from the Decl set prior to visiting the
2214 // nodes. These Decls may have been initialized in the prior initializer.
2215 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002216 // If non-null, add a note to the warning pointing back to the constructor.
2217 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002218 public:
2219 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002220 UninitializedFieldVisitor(Sema &S,
Richard Trieu8d08a272014-08-28 03:23:47 +00002221 llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
2222 : Inherited(S.Context), S(S), Decls(Decls) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002223
Richard Trieufd687772013-09-16 20:46:50 +00002224 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002225 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2226 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002227
Richard Trieu1bc22c12013-09-13 03:20:53 +00002228 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2229 // or union.
2230 MemberExpr *FieldME = ME;
2231
2232 Expr *Base = ME;
2233 while (isa<MemberExpr>(Base)) {
2234 ME = cast<MemberExpr>(Base);
2235
2236 if (isa<VarDecl>(ME->getMemberDecl()))
2237 return;
2238
2239 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2240 if (!FD->isAnonymousStructOrUnion())
2241 FieldME = ME;
2242
2243 Base = ME->getBase();
2244 }
2245
Richard Trieufd687772013-09-16 20:46:50 +00002246 if (!isa<CXXThisExpr>(Base))
2247 return;
2248
Richard Trieu406e65c2013-09-20 03:03:06 +00002249 ValueDecl* FoundVD = FieldME->getMemberDecl();
2250
Richard Trieuef64e942013-10-25 00:56:00 +00002251 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002252 return;
2253
Richard Trieuef64e942013-10-25 00:56:00 +00002254 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002255
Richard Trieuef64e942013-10-25 00:56:00 +00002256 // Prevent double warnings on use of unbounded references.
2257 if (IsReference != CheckReferenceOnly)
2258 return;
2259
2260 unsigned diag = IsReference
2261 ? diag::warn_reference_field_is_uninit
2262 : diag::warn_field_is_uninit;
2263 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2264 if (Constructor)
2265 S.Diag(Constructor->getLocation(),
2266 diag::note_uninit_in_this_constructor)
2267 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2268
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002269 }
2270
2271 void HandleValue(Expr *E) {
2272 E = E->IgnoreParens();
2273
2274 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002275 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002276 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002277 }
2278
2279 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2280 HandleValue(CO->getTrueExpr());
2281 HandleValue(CO->getFalseExpr());
2282 return;
2283 }
2284
2285 if (BinaryConditionalOperator *BCO =
2286 dyn_cast<BinaryConditionalOperator>(E)) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002287 HandleValue(BCO->getFalseExpr());
2288 return;
2289 }
2290
Richard Trieuabf6ec42014-08-27 22:15:10 +00002291 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2292 HandleValue(OVE->getSourceExpr());
2293 return;
2294 }
2295
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2297 switch (BO->getOpcode()) {
2298 default:
2299 return;
2300 case(BO_PtrMemD):
2301 case(BO_PtrMemI):
2302 HandleValue(BO->getLHS());
2303 return;
2304 case(BO_Comma):
2305 HandleValue(BO->getRHS());
2306 return;
2307 }
2308 }
2309 }
2310
Richard Trieu8d08a272014-08-28 03:23:47 +00002311 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2312 FieldDecl *Field) {
2313 // Remove Decls that may have been initialized in the previous
2314 // initializer.
2315 for (ValueDecl* VD : DeclsToRemove)
2316 Decls.erase(VD);
2317
2318 DeclsToRemove.clear();
2319 Constructor = FieldConstructor;
2320 Visit(E);
2321 if (Field)
2322 Decls.erase(Field);
2323 }
2324
Richard Trieu1bc22c12013-09-13 03:20:53 +00002325 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002326 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002327 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002328
2329 Inherited::VisitMemberExpr(ME);
2330 }
2331
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002332 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2333 if (E->getCastKind() == CK_LValueToRValue)
2334 HandleValue(E->getSubExpr());
2335
2336 Inherited::VisitImplicitCastExpr(E);
2337 }
2338
Richard Trieu1bc22c12013-09-13 03:20:53 +00002339 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002340 if (E->getConstructor()->isCopyConstructor()) {
2341 Expr *ArgExpr = E->getArg(0);
2342 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2343 if (ICE->getCastKind() == CK_NoOp) {
2344 ArgExpr = ICE->getSubExpr();
2345 }
2346 }
2347
2348 if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2349 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2350 }
2351 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002352 Inherited::VisitCXXConstructExpr(E);
2353 }
2354
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002355 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2356 Expr *Callee = E->getCallee();
2357 if (isa<MemberExpr>(Callee))
2358 HandleValue(Callee);
2359
2360 Inherited::VisitCXXMemberCallExpr(E);
2361 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002362
Richard Trieu11fd0792014-08-26 04:30:55 +00002363 void VisitCallExpr(CallExpr *E) {
2364 // Treat std::move as a use.
2365 if (E->getNumArgs() == 1) {
2366 if (FunctionDecl *FD = E->getDirectCallee()) {
2367 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
Richard Trieuabf6ec42014-08-27 22:15:10 +00002368 HandleValue(E->getArg(0));
Richard Trieu11fd0792014-08-26 04:30:55 +00002369 }
2370 }
2371 }
2372
2373 Inherited::VisitCallExpr(E);
2374 }
2375
Richard Trieu406e65c2013-09-20 03:03:06 +00002376 void VisitBinaryOperator(BinaryOperator *E) {
2377 // If a field assignment is detected, remove the field from the
2378 // uninitiailized field set.
2379 if (E->getOpcode() == BO_Assign)
2380 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2381 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002382 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002383 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002384
2385 Inherited::VisitBinaryOperator(E);
2386 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002387 };
Richard Trieuef64e942013-10-25 00:56:00 +00002388
2389 // Diagnose value-uses of fields to initialize themselves, e.g.
2390 // foo(foo)
2391 // where foo is not also a parameter to the constructor.
2392 // Also diagnose across field uninitialized use such as
2393 // x(y), y(x)
2394 // TODO: implement -Wuninitialized and fold this into that framework.
2395 static void DiagnoseUninitializedFields(
2396 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2397
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002398 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2399 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002400 return;
2401 }
2402
2403 if (Constructor->isInvalidDecl())
2404 return;
2405
2406 const CXXRecordDecl *RD = Constructor->getParent();
2407
2408 // Holds fields that are uninitialized.
2409 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2410
2411 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002412 for (auto *I : RD->decls()) {
2413 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002414 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002415 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002416 UninitializedFields.insert(IFD->getAnonField());
2417 }
2418 }
2419
Richard Trieu8d08a272014-08-28 03:23:47 +00002420 if (UninitializedFields.empty())
2421 return;
2422
2423 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2424 UninitializedFields);
2425
Aaron Ballman0ad78302014-03-13 17:34:31 +00002426 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002427 if (UninitializedFields.empty())
2428 break;
2429
Aaron Ballman0ad78302014-03-13 17:34:31 +00002430 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002431 if (!InitExpr)
2432 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002433
Richard Trieu8d08a272014-08-28 03:23:47 +00002434 if (CXXDefaultInitExpr *Default =
2435 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2436 InitExpr = Default->getExpr();
2437 if (!InitExpr)
2438 continue;
2439 // In class initializers will point to the constructor.
2440 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2441 FieldInit->getAnyMember());
2442 } else {
2443 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2444 FieldInit->getAnyMember());
2445 }
Richard Trieuef64e942013-10-25 00:56:00 +00002446 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002447 }
2448} // namespace
2449
Richard Smith74108172014-01-17 03:11:34 +00002450/// \brief Enter a new C++ default initializer scope. After calling this, the
2451/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2452/// parsing or instantiating the initializer failed.
2453void Sema::ActOnStartCXXInClassMemberInitializer() {
2454 // Create a synthetic function scope to represent the call to the constructor
2455 // that notionally surrounds a use of this initializer.
2456 PushFunctionScope();
2457}
2458
2459/// \brief This is invoked after parsing an in-class initializer for a
2460/// non-static C++ class member, and after instantiating an in-class initializer
2461/// in a class template. Such actions are deferred until the class is complete.
2462void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2463 SourceLocation InitLoc,
2464 Expr *InitExpr) {
2465 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002466 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002467
Richard Smith938f40b2011-06-11 17:19:42 +00002468 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002469 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2470 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002471
2472 if (!InitExpr) {
2473 FD->setInvalidDecl();
2474 FD->removeInClassInitializer();
2475 return;
2476 }
2477
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002478 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2479 FD->setInvalidDecl();
2480 FD->removeInClassInitializer();
2481 return;
2482 }
2483
Richard Smith938f40b2011-06-11 17:19:42 +00002484 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002485 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002486 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002487 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002488 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002489 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002490 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2491 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002492 if (Init.isInvalid()) {
2493 FD->setInvalidDecl();
2494 return;
2495 }
Richard Smith938f40b2011-06-11 17:19:42 +00002496 }
2497
Richard Smith945f8d32013-01-14 22:39:08 +00002498 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002499 // The initialization of each base and member constitutes a
2500 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002501 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002502 if (Init.isInvalid()) {
2503 FD->setInvalidDecl();
2504 return;
2505 }
2506
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002507 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002508
2509 FD->setInClassInitializer(InitExpr);
2510}
2511
Douglas Gregor15e77a22009-12-31 09:10:24 +00002512/// \brief Find the direct and/or virtual base specifiers that
2513/// correspond to the given base type, for use in base initialization
2514/// within a constructor.
2515static bool FindBaseInitializer(Sema &SemaRef,
2516 CXXRecordDecl *ClassDecl,
2517 QualType BaseType,
2518 const CXXBaseSpecifier *&DirectBaseSpec,
2519 const CXXBaseSpecifier *&VirtualBaseSpec) {
2520 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002521 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002522 for (const auto &Base : ClassDecl->bases()) {
2523 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002524 // We found a direct base of this type. That's what we're
2525 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002526 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002527 break;
2528 }
2529 }
2530
2531 // Check for a virtual base class.
2532 // FIXME: We might be able to short-circuit this if we know in advance that
2533 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002534 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002535 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2536 // We haven't found a base yet; search the class hierarchy for a
2537 // virtual base class.
2538 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2539 /*DetectVirtual=*/false);
2540 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2541 BaseType, Paths)) {
2542 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2543 Path != Paths.end(); ++Path) {
2544 if (Path->back().Base->isVirtual()) {
2545 VirtualBaseSpec = Path->back().Base;
2546 break;
2547 }
2548 }
2549 }
2550 }
2551
2552 return DirectBaseSpec || VirtualBaseSpec;
2553}
2554
Sebastian Redla74948d2011-09-24 17:48:25 +00002555/// \brief Handle a C++ member initializer using braced-init-list syntax.
2556MemInitResult
2557Sema::ActOnMemInitializer(Decl *ConstructorD,
2558 Scope *S,
2559 CXXScopeSpec &SS,
2560 IdentifierInfo *MemberOrBase,
2561 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002562 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002563 SourceLocation IdLoc,
2564 Expr *InitList,
2565 SourceLocation EllipsisLoc) {
2566 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002567 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002568 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002569}
2570
2571/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002572MemInitResult
John McCall48871652010-08-21 09:40:31 +00002573Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002574 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002575 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002576 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002577 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002578 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002579 SourceLocation IdLoc,
2580 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002581 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002582 SourceLocation RParenLoc,
2583 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002584 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002585 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002586 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002587 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002588}
2589
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002590namespace {
2591
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002592// Callback to only accept typo corrections that can be a valid C++ member
2593// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002594class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002595public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002596 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2597 : ClassDecl(ClassDecl) {}
2598
Craig Toppera798a9d2014-03-02 09:32:10 +00002599 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002600 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2601 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2602 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002603 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002604 }
2605 return false;
2606 }
2607
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002608private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002609 CXXRecordDecl *ClassDecl;
2610};
2611
2612}
2613
Sebastian Redla74948d2011-09-24 17:48:25 +00002614/// \brief Handle a C++ member initializer.
2615MemInitResult
2616Sema::BuildMemInitializer(Decl *ConstructorD,
2617 Scope *S,
2618 CXXScopeSpec &SS,
2619 IdentifierInfo *MemberOrBase,
2620 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002621 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002622 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002623 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002624 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002625 if (!ConstructorD)
2626 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002627
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002628 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002629
2630 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002631 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002632 if (!Constructor) {
2633 // The user wrote a constructor initializer on a function that is
2634 // not a C++ constructor. Ignore the error for now, because we may
2635 // have more member initializers coming; we'll diagnose it just
2636 // once in ActOnMemInitializers.
2637 return true;
2638 }
2639
2640 CXXRecordDecl *ClassDecl = Constructor->getParent();
2641
2642 // C++ [class.base.init]p2:
2643 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002644 // constructor's class and, if not found in that scope, are looked
2645 // up in the scope containing the constructor's definition.
2646 // [Note: if the constructor's class contains a member with the
2647 // same name as a direct or virtual base class of the class, a
2648 // mem-initializer-id naming the member or base class and composed
2649 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002650 // mem-initializer-id for the hidden base class may be specified
2651 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002652 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002653 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002654 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002655 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002656 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002657 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002658 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2659 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002660 if (EllipsisLoc.isValid())
2661 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002662 << MemberOrBase
2663 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002664
Sebastian Redla9351792012-02-11 23:51:47 +00002665 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002666 }
Francois Pichetd583da02010-12-04 09:14:42 +00002667 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002668 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002669 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002670 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002671 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002672
2673 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002674 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002675 } else if (DS.getTypeSpecType() == TST_decltype) {
2676 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002677 } else {
2678 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2679 LookupParsedName(R, S, &SS);
2680
2681 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2682 if (!TyD) {
2683 if (R.isAmbiguous()) return true;
2684
John McCallda6841b2010-04-09 19:01:14 +00002685 // We don't want access-control diagnostics here.
2686 R.suppressDiagnostics();
2687
Douglas Gregora3b624a2010-01-19 06:46:48 +00002688 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2689 bool NotUnknownSpecialization = false;
2690 DeclContext *DC = computeDeclContext(SS, false);
2691 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2692 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2693
2694 if (!NotUnknownSpecialization) {
2695 // When the scope specifier can refer to a member of an unknown
2696 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002697 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2698 SS.getWithLocInContext(Context),
2699 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002700 if (BaseType.isNull())
2701 return true;
2702
Douglas Gregora3b624a2010-01-19 06:46:48 +00002703 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002704 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002705 }
2706 }
2707
Douglas Gregor15e77a22009-12-31 09:10:24 +00002708 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002709 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002710 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002711 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002712 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002713 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002714 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002715 // We have found a non-static data member with a similar
2716 // name to what was typed; complain and initialize that
2717 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002718 diagnoseTypo(Corr,
2719 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2720 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002721 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002722 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002723 const CXXBaseSpecifier *DirectBaseSpec;
2724 const CXXBaseSpecifier *VirtualBaseSpec;
2725 if (FindBaseInitializer(*this, ClassDecl,
2726 Context.getTypeDeclType(Type),
2727 DirectBaseSpec, VirtualBaseSpec)) {
2728 // We have found a direct or virtual base class with a
2729 // similar name to what was typed; complain and initialize
2730 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002731 diagnoseTypo(Corr,
2732 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2733 << MemberOrBase << false,
2734 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002735
Richard Smithf9b15102013-08-17 00:46:16 +00002736 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2737 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002738 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002739 diag::note_base_class_specified_here)
2740 << BaseSpec->getType()
2741 << BaseSpec->getSourceRange();
2742
Douglas Gregor15e77a22009-12-31 09:10:24 +00002743 TyD = Type;
2744 }
2745 }
2746 }
2747
Douglas Gregora3b624a2010-01-19 06:46:48 +00002748 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002749 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002750 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002751 return true;
2752 }
John McCallb5a0d312009-12-21 10:41:20 +00002753 }
2754
Douglas Gregora3b624a2010-01-19 06:46:48 +00002755 if (BaseType.isNull()) {
2756 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002757 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002758 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002759 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2760 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002761 }
2762 }
Mike Stump11289f42009-09-09 15:08:12 +00002763
John McCallbcd03502009-12-07 02:54:59 +00002764 if (!TInfo)
2765 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002766
Sebastian Redla9351792012-02-11 23:51:47 +00002767 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002768}
2769
Chandler Carruth599deef2011-09-03 01:14:15 +00002770/// Checks a member initializer expression for cases where reference (or
2771/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002772static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2773 Expr *Init,
2774 SourceLocation IdLoc) {
2775 QualType MemberTy = Member->getType();
2776
2777 // We only handle pointers and references currently.
2778 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2779 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2780 return;
2781
2782 const bool IsPointer = MemberTy->isPointerType();
2783 if (IsPointer) {
2784 if (const UnaryOperator *Op
2785 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2786 // The only case we're worried about with pointers requires taking the
2787 // address.
2788 if (Op->getOpcode() != UO_AddrOf)
2789 return;
2790
2791 Init = Op->getSubExpr();
2792 } else {
2793 // We only handle address-of expression initializers for pointers.
2794 return;
2795 }
2796 }
2797
Richard Smithe3b28bc2013-06-12 21:51:50 +00002798 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002799 // We only warn when referring to a non-reference parameter declaration.
2800 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2801 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002802 return;
2803
2804 S.Diag(Init->getExprLoc(),
2805 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2806 : diag::warn_bind_ref_member_to_parameter)
2807 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002808 } else {
2809 // Other initializers are fine.
2810 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002811 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002812
2813 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2814 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002815}
2816
John McCallfaf5fb42010-08-26 23:41:50 +00002817MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002818Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002819 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002820 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2821 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2822 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002823 "Member must be a FieldDecl or IndirectFieldDecl");
2824
Sebastian Redla9351792012-02-11 23:51:47 +00002825 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002826 return true;
2827
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002828 if (Member->isInvalidDecl())
2829 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002830
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002831 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002832 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002833 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002834 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002835 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002836 } else {
2837 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002838 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002839 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002840
Sebastian Redla9351792012-02-11 23:51:47 +00002841 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002842
Sebastian Redla9351792012-02-11 23:51:47 +00002843 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002844 // Can't check initialization for a member of dependent type or when
2845 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002846 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002847 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002848 bool InitList = false;
2849 if (isa<InitListExpr>(Init)) {
2850 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002851 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002852 }
2853
Chandler Carruthd44c3102010-12-06 09:23:57 +00002854 // Initialize the member.
2855 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002856 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2857 : InitializedEntity::InitializeMember(IndirectMember,
2858 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002859 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002860 InitList ? InitializationKind::CreateDirectList(IdLoc)
2861 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2862 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002863
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002864 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002865 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2866 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002867 if (MemberInit.isInvalid())
2868 return true;
2869
Richard Smith736a9472013-06-12 20:42:33 +00002870 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2871
Richard Smith945f8d32013-01-14 22:39:08 +00002872 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002873 // The initialization of each base and member constitutes a
2874 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002875 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002876 if (MemberInit.isInvalid())
2877 return true;
2878
Richard Smithd59b8322012-12-19 01:39:02 +00002879 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002880 }
2881
Chandler Carruthd44c3102010-12-06 09:23:57 +00002882 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002883 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2884 InitRange.getBegin(), Init,
2885 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002886 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002887 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2888 InitRange.getBegin(), Init,
2889 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002890 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002891}
2892
John McCallfaf5fb42010-08-26 23:41:50 +00002893MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002894Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002895 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002896 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002897 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002898 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002899 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002900 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002901
Sebastian Redl0501c632012-02-12 16:37:36 +00002902 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002903 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002904 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2905 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002906 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002907 }
2908
Sebastian Redla9351792012-02-11 23:51:47 +00002909 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002910 // Initialize the object.
2911 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2912 QualType(ClassDecl->getTypeForDecl(), 0));
2913 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002914 InitList ? InitializationKind::CreateDirectList(NameLoc)
2915 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2916 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002917 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002918 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002919 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002920 if (DelegationInit.isInvalid())
2921 return true;
2922
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002923 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2924 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002925
Richard Smith945f8d32013-01-14 22:39:08 +00002926 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002927 // The initialization of each base and member constitutes a
2928 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002929 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2930 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002931 if (DelegationInit.isInvalid())
2932 return true;
2933
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002934 // If we are in a dependent context, template instantiation will
2935 // perform this type-checking again. Just save the arguments that we
2936 // received in a ParenListExpr.
2937 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2938 // of the information that we have about the base
2939 // initializer. However, deconstructing the ASTs is a dicey process,
2940 // and this approach is far more likely to get the corner cases right.
2941 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002942 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002943
Sebastian Redla9351792012-02-11 23:51:47 +00002944 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002945 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002946 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002947}
2948
2949MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002950Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002951 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002952 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002953 SourceLocation BaseLoc
2954 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002955
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002956 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2957 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2958 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2959
2960 // C++ [class.base.init]p2:
2961 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002962 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002963 // of that class, the mem-initializer is ill-formed. A
2964 // mem-initializer-list can initialize a base class using any
2965 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002966 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002967
Sebastian Redla9351792012-02-11 23:51:47 +00002968 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002969 if (EllipsisLoc.isValid()) {
2970 // This is a pack expansion.
2971 if (!BaseType->containsUnexpandedParameterPack()) {
2972 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002973 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002974
Douglas Gregor44e7df62011-01-04 00:32:56 +00002975 EllipsisLoc = SourceLocation();
2976 }
2977 } else {
2978 // Check for any unexpanded parameter packs.
2979 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2980 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002981
Sebastian Redla9351792012-02-11 23:51:47 +00002982 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002983 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002984 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002985
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002986 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002987 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2988 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002989 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002990 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2991 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002992 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002993
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002994 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2995 VirtualBaseSpec);
2996
2997 // C++ [base.class.init]p2:
2998 // Unless the mem-initializer-id names a nonstatic data member of the
2999 // constructor's class or a direct or virtual base of that class, the
3000 // mem-initializer is ill-formed.
3001 if (!DirectBaseSpec && !VirtualBaseSpec) {
3002 // If the class has any dependent bases, then it's possible that
3003 // one of those types will resolve to the same type as
3004 // BaseType. Therefore, just treat this as a dependent base
3005 // class initialization. FIXME: Should we try to check the
3006 // initialization anyway? It seems odd.
3007 if (ClassDecl->hasAnyDependentBases())
3008 Dependent = true;
3009 else
3010 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3011 << BaseType << Context.getTypeDeclType(ClassDecl)
3012 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3013 }
3014 }
3015
3016 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003017 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003018
Sebastian Redla74948d2011-09-24 17:48:25 +00003019 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3020 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003021 InitRange.getBegin(), Init,
3022 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003023 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003024
3025 // C++ [base.class.init]p2:
3026 // If a mem-initializer-id is ambiguous because it designates both
3027 // a direct non-virtual base class and an inherited virtual base
3028 // class, the mem-initializer is ill-formed.
3029 if (DirectBaseSpec && VirtualBaseSpec)
3030 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003031 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003032
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003033 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003034 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003035 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003036
3037 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003038 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003039 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003040 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003041 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003042 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003043 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003044
3045 InitializedEntity BaseEntity =
3046 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3047 InitializationKind Kind =
3048 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3049 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3050 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003051 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003052 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003053 if (BaseInit.isInvalid())
3054 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003055
Richard Smith945f8d32013-01-14 22:39:08 +00003056 // C++11 [class.base.init]p7:
3057 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003058 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003059 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003060 if (BaseInit.isInvalid())
3061 return true;
3062
3063 // If we are in a dependent context, template instantiation will
3064 // perform this type-checking again. Just save the arguments that we
3065 // received in a ParenListExpr.
3066 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3067 // of the information that we have about the base
3068 // initializer. However, deconstructing the ASTs is a dicey process,
3069 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003070 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003071 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003072
Alexis Hunt1d792652011-01-08 20:30:50 +00003073 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003074 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003075 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003076 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003077 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003078}
3079
Sebastian Redl22653ba2011-08-30 19:58:05 +00003080// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003081static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3082 if (T.isNull()) T = E->getType();
3083 QualType TargetType = SemaRef.BuildReferenceType(
3084 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003085 SourceLocation ExprLoc = E->getLocStart();
3086 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3087 TargetType, ExprLoc);
3088
3089 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3090 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003091 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003092}
3093
Anders Carlsson1b00e242010-04-23 03:10:23 +00003094/// ImplicitInitializerKind - How an implicit base or member initializer should
3095/// initialize its base or member.
3096enum ImplicitInitializerKind {
3097 IIK_Default,
3098 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003099 IIK_Move,
3100 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003101};
3102
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003103static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003104BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003105 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003106 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003107 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003108 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003109 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003110 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3111 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003112
John McCalldadc5752010-08-24 06:29:42 +00003113 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003114
3115 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003116 case IIK_Inherit: {
3117 const CXXRecordDecl *Inherited =
3118 Constructor->getInheritedConstructor()->getParent();
3119 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3120 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3121 // C++11 [class.inhctor]p8:
3122 // Each expression in the expression-list is of the form
3123 // static_cast<T&&>(p), where p is the name of the corresponding
3124 // constructor parameter and T is the declared type of p.
3125 SmallVector<Expr*, 16> Args;
3126 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3127 ParmVarDecl *PD = Constructor->getParamDecl(I);
3128 ExprResult ArgExpr =
3129 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3130 VK_LValue, SourceLocation());
3131 if (ArgExpr.isInvalid())
3132 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003133 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003134 }
3135
3136 InitializationKind InitKind = InitializationKind::CreateDirect(
3137 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003138 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003139 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3140 break;
3141 }
3142 }
3143 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003144 case IIK_Default: {
3145 InitializationKind InitKind
3146 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003147 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3148 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003149 break;
3150 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003151
Sebastian Redl22653ba2011-08-30 19:58:05 +00003152 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003153 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003154 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003155 ParmVarDecl *Param = Constructor->getParamDecl(0);
3156 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003157
Anders Carlsson1b00e242010-04-23 03:10:23 +00003158 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003159 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003160 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003161 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003162 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003163
Eli Friedmanfa0df832012-02-02 03:46:19 +00003164 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3165
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003166 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003167 QualType ArgTy =
3168 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3169 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003170
Sebastian Redl22653ba2011-08-30 19:58:05 +00003171 if (Moving) {
3172 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3173 }
3174
John McCallcf142162010-08-07 06:22:56 +00003175 CXXCastPath BasePath;
3176 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003177 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3178 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003179 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003180 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003181
Anders Carlsson1b00e242010-04-23 03:10:23 +00003182 InitializationKind InitKind
3183 = InitializationKind::CreateDirect(Constructor->getLocation(),
3184 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003185 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3186 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003187 break;
3188 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003189 }
John McCallb268a282010-08-23 23:25:46 +00003190
Douglas Gregora40433a2010-12-07 00:41:46 +00003191 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003192 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003193 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003194
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003195 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003196 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003197 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3198 SourceLocation()),
3199 BaseSpec->isVirtual(),
3200 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003201 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003202 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003203 SourceLocation());
3204
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003205 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003206}
3207
Sebastian Redl22653ba2011-08-30 19:58:05 +00003208static bool RefersToRValueRef(Expr *MemRef) {
3209 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3210 return Referenced->getType()->isRValueReferenceType();
3211}
3212
Anders Carlsson3c1db572010-04-23 02:15:47 +00003213static bool
3214BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003215 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003216 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003217 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003218 if (Field->isInvalidDecl())
3219 return true;
3220
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003221 SourceLocation Loc = Constructor->getLocation();
3222
Sebastian Redl22653ba2011-08-30 19:58:05 +00003223 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3224 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003225 ParmVarDecl *Param = Constructor->getParamDecl(0);
3226 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003227
3228 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003229 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3230 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003231
Anders Carlsson423f5d82010-04-23 16:04:08 +00003232 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003233 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003234 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003235 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003236
Eli Friedmanfa0df832012-02-02 03:46:19 +00003237 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3238
Sebastian Redl22653ba2011-08-30 19:58:05 +00003239 if (Moving) {
3240 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3241 }
3242
Douglas Gregor94f9a482010-05-05 05:51:00 +00003243 // Build a reference to this field within the parameter.
3244 CXXScopeSpec SS;
3245 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3246 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003247 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3248 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003249 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003250 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003251 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003252 ParamType, Loc,
3253 /*IsArrow=*/false,
3254 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003255 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003256 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003257 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003258 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003259 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003260 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003261
3262 // C++11 [class.copy]p15:
3263 // - if a member m has rvalue reference type T&&, it is direct-initialized
3264 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003265 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003266 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003267 }
3268
Douglas Gregor94f9a482010-05-05 05:51:00 +00003269 // When the field we are copying is an array, create index variables for
3270 // each dimension of the array. We use these index variables to subscript
3271 // the source array, and other clients (e.g., CodeGen) will perform the
3272 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003273 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003274 QualType BaseType = Field->getType();
3275 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003276 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003277 while (const ConstantArrayType *Array
3278 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003279 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003280 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003281 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003282 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003283 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003284 llvm::raw_svector_ostream OS(Str);
3285 OS << "__i" << IndexVariables.size();
3286 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3287 }
3288 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003289 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003290 IterationVarName, SizeType,
3291 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003292 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003293 IndexVariables.push_back(IterationVar);
3294
3295 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003296 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003297 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003298 assert(!IterationVarRef.isInvalid() &&
3299 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003300 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003301 assert(!IterationVarRef.isInvalid() &&
3302 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003303
Douglas Gregor94f9a482010-05-05 05:51:00 +00003304 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003305 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3306 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003307 Loc);
3308 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003309 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003310
Douglas Gregor94f9a482010-05-05 05:51:00 +00003311 BaseType = Array->getElementType();
3312 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003313
3314 // The array subscript expression is an lvalue, which is wrong for moving.
3315 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003316 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003317
Douglas Gregor94f9a482010-05-05 05:51:00 +00003318 // Construct the entity that we will be initializing. For an array, this
3319 // will be first element in the array, which may require several levels
3320 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003321 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003322 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003323 if (Indirect)
3324 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3325 else
3326 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003327 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3328 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3329 0,
3330 Entities.back()));
3331
3332 // Direct-initialize to use the copy constructor.
3333 InitializationKind InitKind =
3334 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3335
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003336 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003337 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003338
John McCalldadc5752010-08-24 06:29:42 +00003339 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003340 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003341 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003342 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003343 if (MemberInit.isInvalid())
3344 return true;
3345
Douglas Gregor493627b2011-08-10 15:22:55 +00003346 if (Indirect) {
3347 assert(IndexVariables.size() == 0 &&
3348 "Indirect field improperly initialized");
3349 CXXMemberInit
3350 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3351 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003352 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003353 Loc);
3354 } else
3355 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003356 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003357 Loc,
3358 IndexVariables.data(),
3359 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003360 return false;
3361 }
3362
Richard Smithc2bc61b2013-03-18 21:12:30 +00003363 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3364 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003365
Anders Carlsson3c1db572010-04-23 02:15:47 +00003366 QualType FieldBaseElementType =
3367 SemaRef.Context.getBaseElementType(Field->getType());
3368
Anders Carlsson3c1db572010-04-23 02:15:47 +00003369 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003370 InitializedEntity InitEntity
3371 = Indirect? InitializedEntity::InitializeMember(Indirect)
3372 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003373 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003374 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003375
3376 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3377 ExprResult MemberInit =
3378 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003379
Douglas Gregora40433a2010-12-07 00:41:46 +00003380 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003381 if (MemberInit.isInvalid())
3382 return true;
3383
Douglas Gregor493627b2011-08-10 15:22:55 +00003384 if (Indirect)
3385 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3386 Indirect, Loc,
3387 Loc,
3388 MemberInit.get(),
3389 Loc);
3390 else
3391 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3392 Field, Loc, Loc,
3393 MemberInit.get(),
3394 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003395 return false;
3396 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003397
Alexis Hunt8b455182011-05-17 00:19:05 +00003398 if (!Field->getParent()->isUnion()) {
3399 if (FieldBaseElementType->isReferenceType()) {
3400 SemaRef.Diag(Constructor->getLocation(),
3401 diag::err_uninitialized_member_in_ctor)
3402 << (int)Constructor->isImplicit()
3403 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3404 << 0 << Field->getDeclName();
3405 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3406 return true;
3407 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003408
Alexis Hunt8b455182011-05-17 00:19:05 +00003409 if (FieldBaseElementType.isConstQualified()) {
3410 SemaRef.Diag(Constructor->getLocation(),
3411 diag::err_uninitialized_member_in_ctor)
3412 << (int)Constructor->isImplicit()
3413 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3414 << 1 << Field->getDeclName();
3415 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3416 return true;
3417 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003418 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003419
David Blaikiebbafb8a2012-03-11 07:00:24 +00003420 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003421 FieldBaseElementType->isObjCRetainableType() &&
3422 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3423 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003424 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003425 // Default-initialize Objective-C pointers to NULL.
3426 CXXMemberInit
3427 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3428 Loc, Loc,
3429 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3430 Loc);
3431 return false;
3432 }
3433
Anders Carlsson3c1db572010-04-23 02:15:47 +00003434 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003435 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003436 return false;
3437}
John McCallbc83b3f2010-05-20 23:23:51 +00003438
3439namespace {
3440struct BaseAndFieldInfo {
3441 Sema &S;
3442 CXXConstructorDecl *Ctor;
3443 bool AnyErrorsInInits;
3444 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003445 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003446 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003447 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003448
3449 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3450 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003451 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3452 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003453 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003454 else if (Generated && Ctor->isMoveConstructor())
3455 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003456 else if (Ctor->getInheritedConstructor())
3457 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003458 else
3459 IIK = IIK_Default;
3460 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003461
3462 bool isImplicitCopyOrMove() const {
3463 switch (IIK) {
3464 case IIK_Copy:
3465 case IIK_Move:
3466 return true;
3467
3468 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003469 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003470 return false;
3471 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003472
3473 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003474 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003475
3476 bool addFieldInitializer(CXXCtorInitializer *Init) {
3477 AllToInit.push_back(Init);
3478
3479 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003480 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003481 S.UnusedPrivateFields.remove(Init->getAnyMember());
3482
3483 return false;
3484 }
John McCallbc83b3f2010-05-20 23:23:51 +00003485
Richard Smithab44d5b2013-12-10 08:25:00 +00003486 bool isInactiveUnionMember(FieldDecl *Field) {
3487 RecordDecl *Record = Field->getParent();
3488 if (!Record->isUnion())
3489 return false;
3490
Richard Smith8d183852013-12-10 20:56:03 +00003491 if (FieldDecl *Active =
3492 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003493 return Active != Field->getCanonicalDecl();
3494
3495 // In an implicit copy or move constructor, ignore any in-class initializer.
3496 if (isImplicitCopyOrMove())
3497 return true;
3498
3499 // If there's no explicit initialization, the field is active only if it
3500 // has an in-class initializer...
3501 if (Field->hasInClassInitializer())
3502 return false;
3503 // ... or it's an anonymous struct or union whose class has an in-class
3504 // initializer.
3505 if (!Field->isAnonymousStructOrUnion())
3506 return true;
3507 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3508 return !FieldRD->hasInClassInitializer();
3509 }
3510
3511 /// \brief Determine whether the given field is, or is within, a union member
3512 /// that is inactive (because there was an initializer given for a different
3513 /// member of the union, or because the union was not initialized at all).
3514 bool isWithinInactiveUnionMember(FieldDecl *Field,
3515 IndirectFieldDecl *Indirect) {
3516 if (!Indirect)
3517 return isInactiveUnionMember(Field);
3518
Aaron Ballman29c94602014-03-07 18:36:15 +00003519 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003520 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003521 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003522 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003523 }
3524 return false;
3525 }
3526};
Richard Smithc94ec842011-09-19 13:34:43 +00003527}
3528
Douglas Gregor10f939c2011-11-02 23:04:16 +00003529/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3530/// array type.
3531static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3532 if (T->isIncompleteArrayType())
3533 return true;
3534
3535 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3536 if (!ArrayT->getSize())
3537 return true;
3538
3539 T = ArrayT->getElementType();
3540 }
3541
3542 return false;
3543}
3544
Richard Smith938f40b2011-06-11 17:19:42 +00003545static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003546 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003547 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003548 if (Field->isInvalidDecl())
3549 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003550
Chandler Carruth139e9622010-06-30 02:59:29 +00003551 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003552 if (CXXCtorInitializer *Init =
3553 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003554 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003555
Richard Smithab44d5b2013-12-10 08:25:00 +00003556 // C++11 [class.base.init]p8:
3557 // if the entity is a non-static data member that has a
3558 // brace-or-equal-initializer and either
3559 // -- the constructor's class is a union and no other variant member of that
3560 // union is designated by a mem-initializer-id or
3561 // -- the constructor's class is not a union, and, if the entity is a member
3562 // of an anonymous union, no other member of that union is designated by
3563 // a mem-initializer-id,
3564 // the entity is initialized as specified in [dcl.init].
3565 //
3566 // We also apply the same rules to handle anonymous structs within anonymous
3567 // unions.
3568 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3569 return false;
3570
Douglas Gregor7db3e952011-11-28 20:03:15 +00003571 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003572 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3573 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003574 CXXCtorInitializer *Init;
3575 if (Indirect)
3576 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3577 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003578 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003579 SourceLocation());
3580 else
3581 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3582 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003583 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003584 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003585 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003586 }
3587
Douglas Gregor10f939c2011-11-02 23:04:16 +00003588 // Don't initialize incomplete or zero-length arrays.
3589 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3590 return false;
3591
John McCallbc83b3f2010-05-20 23:23:51 +00003592 // Don't try to build an implicit initializer if there were semantic
3593 // errors in any of the initializers (and therefore we might be
3594 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003595 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003596 return false;
3597
Craig Topperc3ec1492014-05-26 06:22:03 +00003598 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003599 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3600 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003601 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003602
Richard Smith0a8cfc72012-08-07 21:30:42 +00003603 if (!Init)
3604 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003605
Richard Smith0a8cfc72012-08-07 21:30:42 +00003606 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003607}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003608
3609bool
3610Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3611 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003612 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003613 Constructor->setNumCtorInitializers(1);
3614 CXXCtorInitializer **initializer =
3615 new (Context) CXXCtorInitializer*[1];
3616 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3617 Constructor->setCtorInitializers(initializer);
3618
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003619 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003620 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003621 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3622 }
3623
Alexis Hunte2622992011-05-05 00:05:47 +00003624 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003625
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003626 DiagnoseUninitializedFields(*this, Constructor);
3627
Alexis Hunt61bc1732011-05-01 07:04:31 +00003628 return false;
3629}
Douglas Gregor493627b2011-08-10 15:22:55 +00003630
David Blaikie3fc2f912013-01-17 05:26:25 +00003631bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3632 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003633 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003634 // Just store the initializers as written, they will be checked during
3635 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003636 if (!Initializers.empty()) {
3637 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003638 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003639 new (Context) CXXCtorInitializer*[Initializers.size()];
3640 memcpy(baseOrMemberInitializers, Initializers.data(),
3641 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003642 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003643 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003644
3645 // Let template instantiation know whether we had errors.
3646 if (AnyErrors)
3647 Constructor->setInvalidDecl();
3648
Anders Carlssondb0a9652010-04-02 06:26:44 +00003649 return false;
3650 }
3651
John McCallbc83b3f2010-05-20 23:23:51 +00003652 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003653
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003654 // We need to build the initializer AST according to order of construction
3655 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003656 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003657 if (!ClassDecl)
3658 return true;
3659
Eli Friedman9cf6b592009-11-09 19:20:36 +00003660 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003661
David Blaikie3fc2f912013-01-17 05:26:25 +00003662 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003663 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003664
Anders Carlssondb0a9652010-04-02 06:26:44 +00003665 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003666 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003667 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003668 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003669
3670 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003671 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003672 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003673 if (FD && FD->getParent()->isUnion())
3674 Info.ActiveUnionMember.insert(std::make_pair(
3675 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3676 }
3677 } else if (FieldDecl *FD = Member->getMember()) {
3678 if (FD->getParent()->isUnion())
3679 Info.ActiveUnionMember.insert(std::make_pair(
3680 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3681 }
3682 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003683 }
3684
Anders Carlsson43c64af2010-04-21 19:52:01 +00003685 // Keep track of the direct virtual bases.
3686 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003687 for (auto &I : ClassDecl->bases()) {
3688 if (I.isVirtual())
3689 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003690 }
3691
Anders Carlssondb0a9652010-04-02 06:26:44 +00003692 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003693 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003694 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003695 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003696 // [class.base.init]p7, per DR257:
3697 // A mem-initializer where the mem-initializer-id names a virtual base
3698 // class is ignored during execution of a constructor of any class that
3699 // is not the most derived class.
3700 if (ClassDecl->isAbstract()) {
3701 // FIXME: Provide a fixit to remove the base specifier. This requires
3702 // tracking the location of the associated comma for a base specifier.
3703 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003704 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003705 DiagnoseAbstractType(ClassDecl);
3706 }
3707
John McCallbc83b3f2010-05-20 23:23:51 +00003708 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003709 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3710 // [class.base.init]p8, per DR257:
3711 // If a given [...] base class is not named by a mem-initializer-id
3712 // [...] and the entity is not a virtual base class of an abstract
3713 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003714 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003715 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003716 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003717 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003718 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003719 HadError = true;
3720 continue;
3721 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003722
John McCallbc83b3f2010-05-20 23:23:51 +00003723 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003724 }
3725 }
Mike Stump11289f42009-09-09 15:08:12 +00003726
John McCallbc83b3f2010-05-20 23:23:51 +00003727 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003728 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003729 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003730 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003731 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003732
Alexis Hunt1d792652011-01-08 20:30:50 +00003733 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003734 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003735 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003736 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003737 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003738 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003739 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003740 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003741 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003742 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003743 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003744
John McCallbc83b3f2010-05-20 23:23:51 +00003745 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003746 }
3747 }
Mike Stump11289f42009-09-09 15:08:12 +00003748
John McCallbc83b3f2010-05-20 23:23:51 +00003749 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003750 for (auto *Mem : ClassDecl->decls()) {
3751 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003752 // C++ [class.bit]p2:
3753 // A declaration for a bit-field that omits the identifier declares an
3754 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3755 // initialized.
3756 if (F->isUnnamedBitfield())
3757 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003758
Sebastian Redl22653ba2011-08-30 19:58:05 +00003759 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003760 // handle anonymous struct/union fields based on their individual
3761 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003762 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003763 continue;
3764
3765 if (CollectFieldInitializer(*this, Info, F))
3766 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003767 continue;
3768 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003769
3770 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003771 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003772 continue;
3773
Aaron Ballman629afae2014-03-07 19:56:05 +00003774 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003775 if (F->getType()->isIncompleteArrayType()) {
3776 assert(ClassDecl->hasFlexibleArrayMember() &&
3777 "Incomplete array type is not valid");
3778 continue;
3779 }
3780
Douglas Gregor493627b2011-08-10 15:22:55 +00003781 // Initialize each field of an anonymous struct individually.
3782 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3783 HadError = true;
3784
3785 continue;
3786 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003787 }
Mike Stump11289f42009-09-09 15:08:12 +00003788
David Blaikie3fc2f912013-01-17 05:26:25 +00003789 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003790 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003791 Constructor->setNumCtorInitializers(NumInitializers);
3792 CXXCtorInitializer **baseOrMemberInitializers =
3793 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003794 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003795 NumInitializers * sizeof(CXXCtorInitializer*));
3796 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003797
John McCalla6309952010-03-16 21:39:52 +00003798 // Constructors implicitly reference the base and member
3799 // destructors.
3800 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3801 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003802 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003803
3804 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003805}
3806
David Blaikieb61b8152013-01-17 08:49:22 +00003807static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003808 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003809 const RecordDecl *RD = RT->getDecl();
3810 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003811 for (auto *Field : RD->fields())
3812 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003813 return;
3814 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003815 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003816 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003817}
3818
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003819static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3820 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003821}
3822
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003823static const void *GetKeyForMember(ASTContext &Context,
3824 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003825 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003826 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003827
Richard Smithcd45dbc2014-04-19 03:48:30 +00003828 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003829}
3830
David Blaikie3fc2f912013-01-17 05:26:25 +00003831static void DiagnoseBaseOrMemInitializerOrder(
3832 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3833 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003834 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003835 return;
Mike Stump11289f42009-09-09 15:08:12 +00003836
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003837 // Don't check initializers order unless the warning is enabled at the
3838 // location of at least one initializer.
3839 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003840 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003841 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003842 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3843 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003844 ShouldCheckOrder = true;
3845 break;
3846 }
3847 }
3848 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003849 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003850
John McCallbb7b6582010-04-10 07:37:23 +00003851 // Build the list of bases and members in the order that they'll
3852 // actually be initialized. The explicit initializers should be in
3853 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003854 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003855
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003856 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3857
John McCallbb7b6582010-04-10 07:37:23 +00003858 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003859 for (const auto &VBase : ClassDecl->vbases())
3860 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003861
John McCallbb7b6582010-04-10 07:37:23 +00003862 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003863 for (const auto &Base : ClassDecl->bases()) {
3864 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003865 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003866 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003867 }
Mike Stump11289f42009-09-09 15:08:12 +00003868
John McCallbb7b6582010-04-10 07:37:23 +00003869 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003870 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003871 if (Field->isUnnamedBitfield())
3872 continue;
3873
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003874 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003875 }
3876
John McCallbb7b6582010-04-10 07:37:23 +00003877 unsigned NumIdealInits = IdealInitKeys.size();
3878 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003879
Craig Topperc3ec1492014-05-26 06:22:03 +00003880 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003881 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003882 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003883 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003884
3885 // Scan forward to try to find this initializer in the idealized
3886 // initializers list.
3887 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3888 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003889 break;
John McCallbb7b6582010-04-10 07:37:23 +00003890
3891 // If we didn't find this initializer, it must be because we
3892 // scanned past it on a previous iteration. That can only
3893 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003894 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003895 Sema::SemaDiagnosticBuilder D =
3896 SemaRef.Diag(PrevInit->getSourceLocation(),
3897 diag::warn_initializer_out_of_order);
3898
Francois Pichetd583da02010-12-04 09:14:42 +00003899 if (PrevInit->isAnyMemberInitializer())
3900 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003901 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003902 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003903
Francois Pichetd583da02010-12-04 09:14:42 +00003904 if (Init->isAnyMemberInitializer())
3905 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003906 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003907 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003908
3909 // Move back to the initializer's location in the ideal list.
3910 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3911 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003912 break;
John McCallbb7b6582010-04-10 07:37:23 +00003913
3914 assert(IdealIndex != NumIdealInits &&
3915 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003916 }
John McCallbb7b6582010-04-10 07:37:23 +00003917
3918 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003919 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003920}
3921
John McCall23eebd92010-04-10 09:28:51 +00003922namespace {
3923bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003924 CXXCtorInitializer *Init,
3925 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003926 if (!PrevInit) {
3927 PrevInit = Init;
3928 return false;
3929 }
3930
Douglas Gregorea306a12013-03-25 23:28:23 +00003931 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003932 S.Diag(Init->getSourceLocation(),
3933 diag::err_multiple_mem_initialization)
3934 << Field->getDeclName()
3935 << Init->getSourceRange();
3936 else {
John McCall424cec92011-01-19 06:33:43 +00003937 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003938 assert(BaseClass && "neither field nor base");
3939 S.Diag(Init->getSourceLocation(),
3940 diag::err_multiple_base_initialization)
3941 << QualType(BaseClass, 0)
3942 << Init->getSourceRange();
3943 }
3944 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3945 << 0 << PrevInit->getSourceRange();
3946
3947 return true;
3948}
3949
Alexis Hunt1d792652011-01-08 20:30:50 +00003950typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003951typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3952
3953bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003954 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003955 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003956 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003957 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003958 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003959
3960 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003961 if (Parent->isUnion()) {
3962 UnionEntry &En = Unions[Parent];
3963 if (En.first && En.first != Child) {
3964 S.Diag(Init->getSourceLocation(),
3965 diag::err_multiple_mem_union_initialization)
3966 << Field->getDeclName()
3967 << Init->getSourceRange();
3968 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3969 << 0 << En.second->getSourceRange();
3970 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003971 }
3972 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003973 En.first = Child;
3974 En.second = Init;
3975 }
David Blaikie0f65d592011-11-17 06:01:57 +00003976 if (!Parent->isAnonymousStructOrUnion())
3977 return false;
John McCall23eebd92010-04-10 09:28:51 +00003978 }
3979
3980 Child = Parent;
3981 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003982 }
John McCall23eebd92010-04-10 09:28:51 +00003983
3984 return false;
3985}
3986}
3987
Anders Carlssone857b292010-04-02 03:37:03 +00003988/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003989void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003990 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003991 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003992 bool AnyErrors) {
3993 if (!ConstructorDecl)
3994 return;
3995
3996 AdjustDeclIfTemplate(ConstructorDecl);
3997
3998 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003999 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004000
4001 if (!Constructor) {
4002 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4003 return;
4004 }
4005
John McCall23eebd92010-04-10 09:28:51 +00004006 // Mapping for the duplicate initializers check.
4007 // For member initializers, this is keyed with a FieldDecl*.
4008 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004009 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004010
4011 // Mapping for the inconsistent anonymous-union initializers check.
4012 RedundantUnionMap MemberUnions;
4013
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004014 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004015 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004016 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004017
Abramo Bagnara341d7832010-05-26 18:09:23 +00004018 // Set the source order index.
4019 Init->setSourceOrder(i);
4020
Francois Pichetd583da02010-12-04 09:14:42 +00004021 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004022 const void *Key = GetKeyForMember(Context, Init);
4023 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004024 CheckRedundantUnionInit(*this, Init, MemberUnions))
4025 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004026 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004027 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004028 if (CheckRedundantInit(*this, Init, Members[Key]))
4029 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004030 } else {
4031 assert(Init->isDelegatingInitializer());
4032 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004033 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004034 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004035 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004036 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004037 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004038 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004039 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004040 // Return immediately as the initializer is set.
4041 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004042 }
Anders Carlssone857b292010-04-02 03:37:03 +00004043 }
4044
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004045 if (HadError)
4046 return;
4047
David Blaikie3fc2f912013-01-17 05:26:25 +00004048 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004049
David Blaikie3fc2f912013-01-17 05:26:25 +00004050 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004051
Richard Trieuef64e942013-10-25 00:56:00 +00004052 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004053}
4054
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004055void
John McCalla6309952010-03-16 21:39:52 +00004056Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4057 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004058 // Ignore dependent contexts. Also ignore unions, since their members never
4059 // have destructors implicitly called.
4060 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004061 return;
John McCall1064d7e2010-03-16 05:22:47 +00004062
4063 // FIXME: all the access-control diagnostics are positioned on the
4064 // field/base declaration. That's probably good; that said, the
4065 // user might reasonably want to know why the destructor is being
4066 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004067
Anders Carlssondee9a302009-11-17 04:44:12 +00004068 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004069 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004070 if (Field->isInvalidDecl())
4071 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004072
4073 // Don't destroy incomplete or zero-length arrays.
4074 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4075 continue;
4076
Anders Carlssondee9a302009-11-17 04:44:12 +00004077 QualType FieldType = Context.getBaseElementType(Field->getType());
4078
4079 const RecordType* RT = FieldType->getAs<RecordType>();
4080 if (!RT)
4081 continue;
4082
4083 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004084 if (FieldClassDecl->isInvalidDecl())
4085 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004086 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004087 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004088 // The destructor for an implicit anonymous union member is never invoked.
4089 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4090 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004091
Douglas Gregore71edda2010-07-01 22:47:18 +00004092 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004093 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004094 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004095 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004096 << Field->getDeclName()
4097 << FieldType);
4098
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004099 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004100 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004101 }
4102
John McCall1064d7e2010-03-16 05:22:47 +00004103 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4104
Anders Carlssondee9a302009-11-17 04:44:12 +00004105 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004106 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004107 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004108 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004109
4110 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004111 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004112 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004113
John McCall1064d7e2010-03-16 05:22:47 +00004114 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004115 // If our base class is invalid, we probably can't get its dtor anyway.
4116 if (BaseClassDecl->isInvalidDecl())
4117 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004118 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004119 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004120
Douglas Gregore71edda2010-07-01 22:47:18 +00004121 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004122 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004123
4124 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004125 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004126 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004127 << Base.getType()
4128 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004129 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004130
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004131 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004132 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004133 }
4134
4135 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004136 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004137 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004138 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004139
4140 // Ignore direct virtual bases.
4141 if (DirectVirtualBases.count(RT))
4142 continue;
4143
John McCall1064d7e2010-03-16 05:22:47 +00004144 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004145 // If our base class is invalid, we probably can't get its dtor anyway.
4146 if (BaseClassDecl->isInvalidDecl())
4147 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004148 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004149 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004150
Douglas Gregore71edda2010-07-01 22:47:18 +00004151 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004152 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004153 if (CheckDestructorAccess(
4154 ClassDecl->getLocation(), Dtor,
4155 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004156 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004157 Context.getTypeDeclType(ClassDecl)) ==
4158 AR_accessible) {
4159 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004160 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004161 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004162 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004163 }
John McCall1064d7e2010-03-16 05:22:47 +00004164
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004165 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004166 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004167 }
4168}
4169
John McCall48871652010-08-21 09:40:31 +00004170void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004171 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004172 return;
Mike Stump11289f42009-09-09 15:08:12 +00004173
Mike Stump11289f42009-09-09 15:08:12 +00004174 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004175 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004176 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004177 DiagnoseUninitializedFields(*this, Constructor);
4178 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004179}
4180
Mike Stump11289f42009-09-09 15:08:12 +00004181bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004182 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004183 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4184 unsigned DiagID;
4185 AbstractDiagSelID SelID;
4186
4187 public:
4188 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4189 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004190
Craig Toppera798a9d2014-03-02 09:32:10 +00004191 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004192 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004193 if (SelID == -1)
4194 S.Diag(Loc, DiagID) << T;
4195 else
4196 S.Diag(Loc, DiagID) << SelID << T;
4197 }
4198 } Diagnoser(DiagID, SelID);
4199
4200 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004201}
4202
Anders Carlssoneabf7702009-08-27 00:13:57 +00004203bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004204 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004205 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004206 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004207
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004208 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004209 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004210
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004211 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004212 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004213 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004214 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004215
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004216 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004217 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004218 }
Mike Stump11289f42009-09-09 15:08:12 +00004219
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004220 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004221 if (!RT)
4222 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall67da35c2010-02-04 22:26:26 +00004224 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004225
John McCall02db245d2010-08-18 09:41:07 +00004226 // We can't answer whether something is abstract until it has a
4227 // definition. If it's currently being defined, we'll walk back
4228 // over all the declarations when we have a full definition.
4229 const CXXRecordDecl *Def = RD->getDefinition();
4230 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004231 return false;
4232
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004233 if (!RD->isAbstract())
4234 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004235
Douglas Gregorae298422012-05-04 17:09:59 +00004236 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004237 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004238
John McCall02db245d2010-08-18 09:41:07 +00004239 return true;
4240}
4241
4242void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4243 // Check if we've already emitted the list of pure virtual functions
4244 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004245 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004246 return;
Mike Stump11289f42009-09-09 15:08:12 +00004247
Richard Smithbc46e432013-07-22 02:56:56 +00004248 // If the diagnostic is suppressed, don't emit the notes. We're only
4249 // going to emit them once, so try to attach them to a diagnostic we're
4250 // actually going to show.
4251 if (Diags.isLastDiagnosticIgnored())
4252 return;
4253
Douglas Gregor4165bd62010-03-23 23:47:56 +00004254 CXXFinalOverriderMap FinalOverriders;
4255 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004256
Anders Carlssona2f74f32010-06-03 01:00:02 +00004257 // Keep a set of seen pure methods so we won't diagnose the same method
4258 // more than once.
4259 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4260
Douglas Gregor4165bd62010-03-23 23:47:56 +00004261 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4262 MEnd = FinalOverriders.end();
4263 M != MEnd;
4264 ++M) {
4265 for (OverridingMethods::iterator SO = M->second.begin(),
4266 SOEnd = M->second.end();
4267 SO != SOEnd; ++SO) {
4268 // C++ [class.abstract]p4:
4269 // A class is abstract if it contains or inherits at least one
4270 // pure virtual function for which the final overrider is pure
4271 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004272
Douglas Gregor4165bd62010-03-23 23:47:56 +00004273 //
4274 if (SO->second.size() != 1)
4275 continue;
4276
4277 if (!SO->second.front().Method->isPure())
4278 continue;
4279
Anders Carlssona2f74f32010-06-03 01:00:02 +00004280 if (!SeenPureMethods.insert(SO->second.front().Method))
4281 continue;
4282
Douglas Gregor4165bd62010-03-23 23:47:56 +00004283 Diag(SO->second.front().Method->getLocation(),
4284 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004285 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004286 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004287 }
4288
4289 if (!PureVirtualClassDiagSet)
4290 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4291 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004292}
4293
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004294namespace {
John McCall02db245d2010-08-18 09:41:07 +00004295struct AbstractUsageInfo {
4296 Sema &S;
4297 CXXRecordDecl *Record;
4298 CanQualType AbstractType;
4299 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004300
John McCall02db245d2010-08-18 09:41:07 +00004301 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4302 : S(S), Record(Record),
4303 AbstractType(S.Context.getCanonicalType(
4304 S.Context.getTypeDeclType(Record))),
4305 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004306
John McCall02db245d2010-08-18 09:41:07 +00004307 void DiagnoseAbstractType() {
4308 if (Invalid) return;
4309 S.DiagnoseAbstractType(Record);
4310 Invalid = true;
4311 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004312
John McCall02db245d2010-08-18 09:41:07 +00004313 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4314};
4315
4316struct CheckAbstractUsage {
4317 AbstractUsageInfo &Info;
4318 const NamedDecl *Ctx;
4319
4320 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4321 : Info(Info), Ctx(Ctx) {}
4322
4323 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4324 switch (TL.getTypeLocClass()) {
4325#define ABSTRACT_TYPELOC(CLASS, PARENT)
4326#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004327 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004328#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004329 }
John McCall02db245d2010-08-18 09:41:07 +00004330 }
Mike Stump11289f42009-09-09 15:08:12 +00004331
John McCall02db245d2010-08-18 09:41:07 +00004332 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004333 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004334 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4335 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004336 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004337
4338 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004339 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004340 }
John McCall02db245d2010-08-18 09:41:07 +00004341 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004342
John McCall02db245d2010-08-18 09:41:07 +00004343 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4344 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4345 }
Mike Stump11289f42009-09-09 15:08:12 +00004346
John McCall02db245d2010-08-18 09:41:07 +00004347 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4348 // Visit the type parameters from a permissive context.
4349 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4350 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4351 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4352 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4353 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4354 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004355 }
John McCall02db245d2010-08-18 09:41:07 +00004356 }
Mike Stump11289f42009-09-09 15:08:12 +00004357
John McCall02db245d2010-08-18 09:41:07 +00004358 // Visit pointee types from a permissive context.
4359#define CheckPolymorphic(Type) \
4360 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4361 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4362 }
4363 CheckPolymorphic(PointerTypeLoc)
4364 CheckPolymorphic(ReferenceTypeLoc)
4365 CheckPolymorphic(MemberPointerTypeLoc)
4366 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004367 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004368
John McCall02db245d2010-08-18 09:41:07 +00004369 /// Handle all the types we haven't given a more specific
4370 /// implementation for above.
4371 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4372 // Every other kind of type that we haven't called out already
4373 // that has an inner type is either (1) sugar or (2) contains that
4374 // inner type in some way as a subobject.
4375 if (TypeLoc Next = TL.getNextTypeLoc())
4376 return Visit(Next, Sel);
4377
4378 // If there's no inner type and we're in a permissive context,
4379 // don't diagnose.
4380 if (Sel == Sema::AbstractNone) return;
4381
4382 // Check whether the type matches the abstract type.
4383 QualType T = TL.getType();
4384 if (T->isArrayType()) {
4385 Sel = Sema::AbstractArrayType;
4386 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004387 }
John McCall02db245d2010-08-18 09:41:07 +00004388 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4389 if (CT != Info.AbstractType) return;
4390
4391 // It matched; do some magic.
4392 if (Sel == Sema::AbstractArrayType) {
4393 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4394 << T << TL.getSourceRange();
4395 } else {
4396 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4397 << Sel << T << TL.getSourceRange();
4398 }
4399 Info.DiagnoseAbstractType();
4400 }
4401};
4402
4403void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4404 Sema::AbstractDiagSelID Sel) {
4405 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4406}
4407
4408}
4409
4410/// Check for invalid uses of an abstract type in a method declaration.
4411static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4412 CXXMethodDecl *MD) {
4413 // No need to do the check on definitions, which require that
4414 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004415 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004416 return;
4417
4418 // For safety's sake, just ignore it if we don't have type source
4419 // information. This should never happen for non-implicit methods,
4420 // but...
4421 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4422 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4423}
4424
4425/// Check for invalid uses of an abstract type within a class definition.
4426static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4427 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004428 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004429 if (D->isImplicit()) continue;
4430
4431 // Methods and method templates.
4432 if (isa<CXXMethodDecl>(D)) {
4433 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4434 } else if (isa<FunctionTemplateDecl>(D)) {
4435 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4436 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4437
4438 // Fields and static variables.
4439 } else if (isa<FieldDecl>(D)) {
4440 FieldDecl *FD = cast<FieldDecl>(D);
4441 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4442 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4443 } else if (isa<VarDecl>(D)) {
4444 VarDecl *VD = cast<VarDecl>(D);
4445 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4446 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4447
4448 // Nested classes and class templates.
4449 } else if (isa<CXXRecordDecl>(D)) {
4450 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4451 } else if (isa<ClassTemplateDecl>(D)) {
4452 CheckAbstractClassUsage(Info,
4453 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4454 }
4455 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004456}
4457
Hans Wennborg853ae942014-05-30 16:59:42 +00004458/// \brief Check class-level dllimport/dllexport attribute.
4459static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4460 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004461
4462 // MSVC inherits DLL attributes to partial class template specializations.
4463 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4464 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4465 if (Attr *TemplateAttr =
4466 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4467 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4468 A->setInherited(true);
4469 ClassAttr = A;
4470 }
4471 }
4472 }
4473
Hans Wennborg853ae942014-05-30 16:59:42 +00004474 if (!ClassAttr)
4475 return;
4476
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004477 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4478 !ClassAttr->isInherited()) {
4479 // Diagnose dll attributes on members of class with dll attribute.
4480 for (Decl *Member : Class->decls()) {
4481 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4482 continue;
4483 InheritableAttr *MemberAttr = getDLLAttr(Member);
4484 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4485 continue;
4486
4487 S.Diag(MemberAttr->getLocation(),
4488 diag::err_attribute_dll_member_of_dll_class)
4489 << MemberAttr << ClassAttr;
4490 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4491 Member->setInvalidDecl();
4492 }
4493 }
4494
4495 if (Class->getDescribedClassTemplate())
4496 // Don't inherit dll attribute until the template is instantiated.
4497 return;
4498
Hans Wennborg853ae942014-05-30 16:59:42 +00004499 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4500
4501 // Force declaration of implicit members so they can inherit the attribute.
4502 S.ForceDeclarationOfImplicitMembers(Class);
4503
4504 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4505 // seem to be true in practice?
4506
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004507 TemplateSpecializationKind TSK =
4508 Class->getTemplateSpecializationKind();
4509
Hans Wennborg853ae942014-05-30 16:59:42 +00004510 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004511 VarDecl *VD = dyn_cast<VarDecl>(Member);
4512 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4513
4514 // Only methods and static fields inherit the attributes.
4515 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004516 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004517
4518 // Don't process deleted methods.
4519 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004520 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004521
Hans Wennborge8ad3832014-06-11 22:44:39 +00004522 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4523 MD->isInlined()) {
4524 // Current MSVC versions don't export the move assignment operators, so
4525 // don't attempt to import them if we have a definition.
4526 continue;
4527 }
4528
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004529 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004530 auto *NewAttr =
4531 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4532 NewAttr->setInherited(true);
4533 Member->addAttr(NewAttr);
4534 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004535
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004536 if (MD && ClassExported) {
4537 if (MD->isUserProvided()) {
4538 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004539
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004540 // .. except for certain kinds of template specializations.
4541 if (TSK == TSK_ExplicitInstantiationDeclaration)
4542 continue;
4543 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4544 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004545
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004546 S.MarkFunctionReferenced(Class->getLocation(), MD);
4547 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4548 MD->isCopyAssignmentOperator() ||
4549 MD->isMoveAssignmentOperator()) {
4550 // Instantiate non-trivial or explicitly defaulted methods, and the
4551 // copy assignment / move assignment operators.
4552 S.MarkFunctionReferenced(Class->getLocation(), MD);
4553 // Resolve its exception specification; CodeGen needs it.
4554 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4555 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4556 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004557 }
4558 }
4559 }
4560}
4561
Douglas Gregorc99f1552009-12-03 18:33:45 +00004562/// \brief Perform semantic checks on a class definition that has been
4563/// completing, introducing implicitly-declared members, checking for
4564/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004565void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004566 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004567 return;
4568
John McCall02db245d2010-08-18 09:41:07 +00004569 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4570 AbstractUsageInfo Info(*this, Record);
4571 CheckAbstractClassUsage(Info, Record);
4572 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004573
4574 // If this is not an aggregate type and has no user-declared constructor,
4575 // complain about any non-static data members of reference or const scalar
4576 // type, since they will never get initializers.
4577 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004578 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4579 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004580 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004581 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004582 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004583 continue;
4584
Douglas Gregor454a5b62010-04-15 00:00:53 +00004585 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004586 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004587 if (!Complained) {
4588 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4589 << Record->getTagKind() << Record;
4590 Complained = true;
4591 }
4592
4593 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4594 << F->getType()->isReferenceType()
4595 << F->getDeclName();
4596 }
4597 }
4598 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004599
Anders Carlssone771e762011-01-25 18:08:22 +00004600 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004601 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004602
4603 if (Record->getIdentifier()) {
4604 // C++ [class.mem]p13:
4605 // If T is the name of a class, then each of the following shall have a
4606 // name different from T:
4607 // - every member of every anonymous union that is a member of class T.
4608 //
4609 // C++ [class.mem]p14:
4610 // In addition, if class T has a user-declared constructor (12.1), every
4611 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004612 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4613 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4614 ++I) {
4615 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004616 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4617 isa<IndirectFieldDecl>(D)) {
4618 Diag(D->getLocation(), diag::err_member_name_of_class)
4619 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004620 break;
4621 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004622 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004623 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004624
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004625 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004626 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004627 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004628 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4629 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004630 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4631 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4632 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004633
David Majnemera5433082013-10-18 00:33:31 +00004634 if (Record->isAbstract()) {
4635 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4636 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4637 << FA->isSpelledAsSealed();
4638 DiagnoseAbstractType(Record);
4639 }
David Blaikie348df502012-09-21 03:21:07 +00004640 }
4641
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004642 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004643 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004644 // See if a method overloads virtual methods in a base
4645 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004646 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004647 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004648
4649 // Check whether the explicitly-defaulted special members are valid.
4650 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004651 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004652
4653 // For an explicitly defaulted or deleted special member, we defer
4654 // determining triviality until the class is complete. That time is now!
4655 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004656 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004657 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004658 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004659
4660 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004661 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004662 }
4663 }
4664 }
4665 }
4666
4667 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4668 // function that is not a constructor declares that member function to be
4669 // const. [...] The class of which that function is a member shall be
4670 // a literal type.
4671 //
4672 // If the class has virtual bases, any constexpr members will already have
4673 // been diagnosed by the checks performed on the member declaration, so
4674 // suppress this (less useful) diagnostic.
4675 //
4676 // We delay this until we know whether an explicitly-defaulted (or deleted)
4677 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004678 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004679 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004680 for (const auto *M : Record->methods()) {
4681 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004682 switch (Record->getTemplateSpecializationKind()) {
4683 case TSK_ImplicitInstantiation:
4684 case TSK_ExplicitInstantiationDeclaration:
4685 case TSK_ExplicitInstantiationDefinition:
4686 // If a template instantiates to a non-literal type, but its members
4687 // instantiate to constexpr functions, the template is technically
4688 // ill-formed, but we allow it for sanity.
4689 continue;
4690
4691 case TSK_Undeclared:
4692 case TSK_ExplicitSpecialization:
4693 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4694 diag::err_constexpr_method_non_literal);
4695 break;
4696 }
4697
4698 // Only produce one error per class.
4699 break;
4700 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004701 }
4702 }
Sebastian Redl08905022011-02-05 19:23:19 +00004703
John McCall95833f32014-02-27 20:30:49 +00004704 // ms_struct is a request to use the same ABI rules as MSVC. Check
4705 // whether this class uses any C++ features that are implemented
4706 // completely differently in MSVC, and if so, emit a diagnostic.
4707 // That diagnostic defaults to an error, but we allow projects to
4708 // map it down to a warning (or ignore it). It's a fairly common
4709 // practice among users of the ms_struct pragma to mass-annotate
4710 // headers, sweeping up a bunch of types that the project doesn't
4711 // really rely on MSVC-compatible layout for. We must therefore
4712 // support "ms_struct except for C++ stuff" as a secondary ABI.
4713 if (Record->isMsStruct(Context) &&
4714 (Record->isPolymorphic() || Record->getNumBases())) {
4715 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004716 }
4717
Richard Smithc2bc61b2013-03-18 21:12:30 +00004718 // Declare inheriting constructors. We do this eagerly here because:
4719 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004720 // constructors from different classes.
4721 // - The lazy declaration of the other implicit constructors is so as to not
4722 // waste space and performance on classes that are not meant to be
4723 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004724 // have inheriting constructors.
4725 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004726
4727 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004728}
4729
Richard Smith41c35d62013-11-27 03:39:20 +00004730/// Look up the special member function that would be called by a special
4731/// member function for a subobject of class type.
4732///
4733/// \param Class The class type of the subobject.
4734/// \param CSM The kind of special member function.
4735/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4736/// \param ConstRHS True if this is a copy operation with a const object
4737/// on its RHS, that is, if the argument to the outer special member
4738/// function is 'const' and this is not a field marked 'mutable'.
4739static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4740 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4741 unsigned FieldQuals, bool ConstRHS) {
4742 unsigned LHSQuals = 0;
4743 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4744 LHSQuals = FieldQuals;
4745
4746 unsigned RHSQuals = FieldQuals;
4747 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4748 RHSQuals = 0;
4749 else if (ConstRHS)
4750 RHSQuals |= Qualifiers::Const;
4751
4752 return S.LookupSpecialMember(Class, CSM,
4753 RHSQuals & Qualifiers::Const,
4754 RHSQuals & Qualifiers::Volatile,
4755 false,
4756 LHSQuals & Qualifiers::Const,
4757 LHSQuals & Qualifiers::Volatile);
4758}
4759
Richard Smithb5800092012-06-10 05:43:50 +00004760/// Is the special member function which would be selected to perform the
4761/// specified operation on the specified class type a constexpr constructor?
4762static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4763 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004764 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004765 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004766 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004767 if (!SMOR || !SMOR->getMethod())
4768 // A constructor we wouldn't select can't be "involved in initializing"
4769 // anything.
4770 return true;
4771 return SMOR->getMethod()->isConstexpr();
4772}
4773
4774/// Determine whether the specified special member function would be constexpr
4775/// if it were implicitly defined.
4776static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4777 Sema::CXXSpecialMember CSM,
4778 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004779 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004780 return false;
4781
4782 // C++11 [dcl.constexpr]p4:
4783 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004784 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004785 switch (CSM) {
4786 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004787 // Since default constructor lookup is essentially trivial (and cannot
4788 // involve, for instance, template instantiation), we compute whether a
4789 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4790 //
4791 // This is important for performance; we need to know whether the default
4792 // constructor is constexpr to determine whether the type is a literal type.
4793 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4794
Richard Smithb5800092012-06-10 05:43:50 +00004795 case Sema::CXXCopyConstructor:
4796 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004797 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004798 break;
4799
4800 case Sema::CXXCopyAssignment:
4801 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004802 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00004803 return false;
4804 // In C++1y, we need to perform overload resolution.
4805 Ctor = false;
4806 break;
4807
Richard Smithb5800092012-06-10 05:43:50 +00004808 case Sema::CXXDestructor:
4809 case Sema::CXXInvalid:
4810 return false;
4811 }
4812
4813 // -- if the class is a non-empty union, or for each non-empty anonymous
4814 // union member of a non-union class, exactly one non-static data member
4815 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004816 //
4817 // If we squint, this is guaranteed, since exactly one non-static data member
4818 // will be initialized (if the constructor isn't deleted), we just don't know
4819 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004820 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004821 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004822
4823 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004824 if (Ctor && ClassDecl->getNumVBases())
4825 return false;
4826
4827 // C++1y [class.copy]p26:
4828 // -- [the class] is a literal type, and
4829 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004830 return false;
4831
4832 // -- every constructor involved in initializing [...] base class
4833 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004834 // -- the assignment operator selected to copy/move each direct base
4835 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004836 for (const auto &B : ClassDecl->bases()) {
4837 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004838 if (!BaseType) continue;
4839
4840 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004841 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004842 return false;
4843 }
4844
4845 // -- every constructor involved in initializing non-static data members
4846 // [...] shall be a constexpr constructor;
4847 // -- every non-static data member and base class sub-object shall be
4848 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004849 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004850 // thereof), the assignment operator selected to copy/move that member is
4851 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004852 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004853 if (F->isInvalidDecl())
4854 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004855 QualType BaseType = S.Context.getBaseElementType(F->getType());
4856 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004857 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004858 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4859 BaseType.getCVRQualifiers(),
4860 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004861 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004862 }
4863 }
4864
4865 // All OK, it's constexpr!
4866 return true;
4867}
4868
Richard Smithd3b5c9082012-07-27 04:22:15 +00004869static Sema::ImplicitExceptionSpecification
4870computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4871 switch (S.getSpecialMember(MD)) {
4872 case Sema::CXXDefaultConstructor:
4873 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4874 case Sema::CXXCopyConstructor:
4875 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4876 case Sema::CXXCopyAssignment:
4877 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4878 case Sema::CXXMoveConstructor:
4879 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4880 case Sema::CXXMoveAssignment:
4881 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4882 case Sema::CXXDestructor:
4883 return S.ComputeDefaultedDtorExceptionSpec(MD);
4884 case Sema::CXXInvalid:
4885 break;
4886 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004887 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4888 "only special members have implicit exception specs");
4889 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004890}
4891
Reid Kleckner78af0702013-08-27 23:08:25 +00004892static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4893 CXXMethodDecl *MD) {
4894 FunctionProtoType::ExtProtoInfo EPI;
4895
4896 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00004897 EPI.ExceptionSpec.Type = EST_Unevaluated;
4898 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00004899
4900 // Set the calling convention to the default for C++ instance methods.
4901 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4902 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4903 /*IsCXXMethod=*/true));
4904 return EPI;
4905}
4906
Richard Smithd3b5c9082012-07-27 04:22:15 +00004907void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4908 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4909 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4910 return;
4911
Richard Smith7f782272012-07-30 23:48:14 +00004912 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00004913 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00004914
Richard Smith7f782272012-07-30 23:48:14 +00004915 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00004916 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00004917
4918 // A user-provided destructor can be defined outside the class. When that
4919 // happens, be sure to update the exception specification on both
4920 // declarations.
4921 const FunctionProtoType *CanonicalFPT =
4922 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4923 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00004924 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004925}
4926
Richard Smithb9e90b12012-05-15 04:39:51 +00004927void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4928 CXXRecordDecl *RD = MD->getParent();
4929 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004930
Richard Smithb9e90b12012-05-15 04:39:51 +00004931 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4932 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004933
4934 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004935 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004936 bool First = MD == MD->getCanonicalDecl();
4937
4938 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004939
4940 // C++11 [dcl.fct.def.default]p1:
4941 // A function that is explicitly defaulted shall
4942 // -- be a special member function (checked elsewhere),
4943 // -- have the same type (except for ref-qualifiers, and except that a
4944 // copy operation can take a non-const reference) as an implicit
4945 // declaration, and
4946 // -- not have default arguments.
4947 unsigned ExpectedParams = 1;
4948 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4949 ExpectedParams = 0;
4950 if (MD->getNumParams() != ExpectedParams) {
4951 // This also checks for default arguments: a copy or move constructor with a
4952 // default argument is classified as a default constructor, and assignment
4953 // operations and destructors can't have default arguments.
4954 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4955 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004956 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004957 } else if (MD->isVariadic()) {
4958 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4959 << CSM << MD->getSourceRange();
4960 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004961 }
4962
Richard Smithb9e90b12012-05-15 04:39:51 +00004963 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004964
Richard Smithb5800092012-06-10 05:43:50 +00004965 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004966 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004967 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004968 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004969 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004970
Richard Smithb9e90b12012-05-15 04:39:51 +00004971 QualType ReturnType = Context.VoidTy;
4972 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4973 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004974 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004975 QualType ExpectedReturnType =
4976 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4977 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4978 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4979 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4980 HadError = true;
4981 }
4982
4983 // A defaulted special member cannot have cv-qualifiers.
4984 if (Type->getTypeQuals()) {
4985 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004986 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00004987 HadError = true;
4988 }
4989 }
4990
4991 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004992 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004993 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004994 if (ExpectedParams && ArgType->isReferenceType()) {
4995 // Argument must be reference to possibly-const T.
4996 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004997 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004998
4999 if (ReferentType.isVolatileQualified()) {
5000 Diag(MD->getLocation(),
5001 diag::err_defaulted_special_member_volatile_param) << CSM;
5002 HadError = true;
5003 }
5004
Richard Smithb5800092012-06-10 05:43:50 +00005005 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005006 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5007 Diag(MD->getLocation(),
5008 diag::err_defaulted_special_member_copy_const_param)
5009 << (CSM == CXXCopyAssignment);
5010 // FIXME: Explain why this special member can't be const.
5011 } else {
5012 Diag(MD->getLocation(),
5013 diag::err_defaulted_special_member_move_const_param)
5014 << (CSM == CXXMoveAssignment);
5015 }
5016 HadError = true;
5017 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005018 } else if (ExpectedParams) {
5019 // A copy assignment operator can take its argument by value, but a
5020 // defaulted one cannot.
5021 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005022 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005023 HadError = true;
5024 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005025
Richard Smithcc36f692011-12-22 02:22:31 +00005026 // C++11 [dcl.fct.def.default]p2:
5027 // An explicitly-defaulted function may be declared constexpr only if it
5028 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005029 // Do not apply this rule to members of class templates, since core issue 1358
5030 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005031 // functions which cannot be constexpr (for non-constructors in C++11 and for
5032 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005033 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5034 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005035 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005036 : isa<CXXConstructorDecl>(MD)) &&
5037 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005038 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5039 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005040 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005041 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005042 }
Richard Smithbd305122012-12-11 01:14:52 +00005043
Richard Smithcc36f692011-12-22 02:22:31 +00005044 // and may have an explicit exception-specification only if it is compatible
5045 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005046 if (Type->hasExceptionSpec()) {
5047 // Delay the check if this is the first declaration of the special member,
5048 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005049 if (First) {
5050 // If the exception specification needs to be instantiated, do so now,
5051 // before we clobber it with an EST_Unevaluated specification below.
5052 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5053 InstantiateExceptionSpec(MD->getLocStart(), MD);
5054 Type = MD->getType()->getAs<FunctionProtoType>();
5055 }
Richard Smithbd305122012-12-11 01:14:52 +00005056 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005057 } else
Richard Smithbd305122012-12-11 01:14:52 +00005058 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5059 }
Richard Smithcc36f692011-12-22 02:22:31 +00005060
5061 // If a function is explicitly defaulted on its first declaration,
5062 if (First) {
5063 // -- it is implicitly considered to be constexpr if the implicit
5064 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005065 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005066
Richard Smithb9e90b12012-05-15 04:39:51 +00005067 // -- it is implicitly considered to have the same exception-specification
5068 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005069 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005070 EPI.ExceptionSpec.Type = EST_Unevaluated;
5071 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005072 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005073 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005074 ExpectedParams),
5075 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005076 }
5077
Richard Smithb9e90b12012-05-15 04:39:51 +00005078 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005079 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005080 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005081 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005082 // C++11 [dcl.fct.def.default]p4:
5083 // [For a] user-provided explicitly-defaulted function [...] if such a
5084 // function is implicitly defined as deleted, the program is ill-formed.
5085 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005086 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005087 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005088 }
5089 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005090
Richard Smithb9e90b12012-05-15 04:39:51 +00005091 if (HadError)
5092 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005093}
5094
Richard Smithbd305122012-12-11 01:14:52 +00005095/// Check whether the exception specification provided for an
5096/// explicitly-defaulted special member matches the exception specification
5097/// that would have been generated for an implicit special member, per
5098/// C++11 [dcl.fct.def.default]p2.
5099void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5100 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5101 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005102 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5103 /*IsCXXMethod=*/true);
5104 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005105 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5106 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005107 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005108 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005109
5110 // Ensure that it matches.
5111 CheckEquivalentExceptionSpec(
5112 PDiag(diag::err_incorrect_defaulted_exception_spec)
5113 << getSpecialMember(MD), PDiag(),
5114 ImplicitType, SourceLocation(),
5115 SpecifiedType, MD->getLocation());
5116}
5117
Alp Tokerae3a9442013-10-18 05:54:19 +00005118void Sema::CheckDelayedMemberExceptionSpecs() {
5119 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5120 2> Checks;
5121 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005122
Alp Tokerae3a9442013-10-18 05:54:19 +00005123 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5124 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5125
5126 // Perform any deferred checking of exception specifications for virtual
5127 // destructors.
5128 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5129 const CXXDestructorDecl *Dtor = Checks[i].first;
5130 assert(!Dtor->getParent()->isDependentType() &&
5131 "Should not ever add destructors of templates into the list.");
5132 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5133 }
5134
5135 // Check that any explicitly-defaulted methods have exception specifications
5136 // compatible with their implicit exception specifications.
5137 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5138 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5139 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005140}
5141
Richard Smithd951a1d2012-02-18 02:02:13 +00005142namespace {
5143struct SpecialMemberDeletionInfo {
5144 Sema &S;
5145 CXXMethodDecl *MD;
5146 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005147 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005148
5149 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005150 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005151 SourceLocation Loc;
5152
5153 bool AllFieldsAreConst;
5154
5155 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005156 Sema::CXXSpecialMember CSM, bool Diagnose)
5157 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005158 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005159 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005160 AllFieldsAreConst(true) {
5161 switch (CSM) {
5162 case Sema::CXXDefaultConstructor:
5163 case Sema::CXXCopyConstructor:
5164 IsConstructor = true;
5165 break;
5166 case Sema::CXXMoveConstructor:
5167 IsConstructor = true;
5168 IsMove = true;
5169 break;
5170 case Sema::CXXCopyAssignment:
5171 IsAssignment = true;
5172 break;
5173 case Sema::CXXMoveAssignment:
5174 IsAssignment = true;
5175 IsMove = true;
5176 break;
5177 case Sema::CXXDestructor:
5178 break;
5179 case Sema::CXXInvalid:
5180 llvm_unreachable("invalid special member kind");
5181 }
5182
5183 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005184 if (const ReferenceType *RT =
5185 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5186 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005187 }
5188 }
5189
5190 bool inUnion() const { return MD->getParent()->isUnion(); }
5191
5192 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005193 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005194 unsigned Quals, bool IsMutable) {
5195 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5196 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005197 }
5198
Richard Smith852265f2012-03-30 20:53:28 +00005199 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005200
Richard Smith852265f2012-03-30 20:53:28 +00005201 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005202 bool shouldDeleteForField(FieldDecl *FD);
5203 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005204
Richard Smithaf136f82012-07-18 03:51:16 +00005205 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5206 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005207 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5208 Sema::SpecialMemberOverloadResult *SMOR,
5209 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005210
5211 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005212};
5213}
5214
John McCalld4274212012-04-09 20:53:23 +00005215/// Is the given special member inaccessible when used on the given
5216/// sub-object.
5217bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5218 CXXMethodDecl *target) {
5219 /// If we're operating on a base class, the object type is the
5220 /// type of this special member.
5221 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005222 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005223 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5224 objectTy = S.Context.getTypeDeclType(MD->getParent());
5225 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5226
5227 // If we're operating on a field, the object type is the type of the field.
5228 } else {
5229 objectTy = S.Context.getTypeDeclType(target->getParent());
5230 }
5231
5232 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5233}
5234
Richard Smith852265f2012-03-30 20:53:28 +00005235/// Check whether we should delete a special member due to the implicit
5236/// definition containing a call to a special member of a subobject.
5237bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5238 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5239 bool IsDtorCallInCtor) {
5240 CXXMethodDecl *Decl = SMOR->getMethod();
5241 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5242
5243 int DiagKind = -1;
5244
5245 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5246 DiagKind = !Decl ? 0 : 1;
5247 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5248 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005249 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005250 DiagKind = 3;
5251 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5252 !Decl->isTrivial()) {
5253 // A member of a union must have a trivial corresponding special member.
5254 // As a weird special case, a destructor call from a union's constructor
5255 // must be accessible and non-deleted, but need not be trivial. Such a
5256 // destructor is never actually called, but is semantically checked as
5257 // if it were.
5258 DiagKind = 4;
5259 }
5260
5261 if (DiagKind == -1)
5262 return false;
5263
5264 if (Diagnose) {
5265 if (Field) {
5266 S.Diag(Field->getLocation(),
5267 diag::note_deleted_special_member_class_subobject)
5268 << CSM << MD->getParent() << /*IsField*/true
5269 << Field << DiagKind << IsDtorCallInCtor;
5270 } else {
5271 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5272 S.Diag(Base->getLocStart(),
5273 diag::note_deleted_special_member_class_subobject)
5274 << CSM << MD->getParent() << /*IsField*/false
5275 << Base->getType() << DiagKind << IsDtorCallInCtor;
5276 }
5277
5278 if (DiagKind == 1)
5279 S.NoteDeletedFunction(Decl);
5280 // FIXME: Explain inaccessibility if DiagKind == 3.
5281 }
5282
5283 return true;
5284}
5285
Richard Smith921bd202012-02-26 09:11:52 +00005286/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005287/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005288bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005289 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005290 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005291 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005292
5293 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005294 // -- any direct or virtual base class, or non-static data member with no
5295 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005296 // either M has no default constructor or overload resolution as applied
5297 // to M's default constructor results in an ambiguity or in a function
5298 // that is deleted or inaccessible
5299 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5300 // -- a direct or virtual base class B that cannot be copied/moved because
5301 // overload resolution, as applied to B's corresponding special member,
5302 // results in an ambiguity or a function that is deleted or inaccessible
5303 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005304 // C++11 [class.dtor]p5:
5305 // -- any direct or virtual base class [...] has a type with a destructor
5306 // that is deleted or inaccessible
5307 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005308 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005309 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5310 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005311 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005312
Richard Smith852265f2012-03-30 20:53:28 +00005313 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5314 // -- any direct or virtual base class or non-static data member has a
5315 // type with a destructor that is deleted or inaccessible
5316 if (IsConstructor) {
5317 Sema::SpecialMemberOverloadResult *SMOR =
5318 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5319 false, false, false, false, false);
5320 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5321 return true;
5322 }
5323
Richard Smith921bd202012-02-26 09:11:52 +00005324 return false;
5325}
5326
5327/// Check whether we should delete a special member function due to the class
5328/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005329bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005330 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005331 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005332}
5333
5334/// Check whether we should delete a special member function due to the class
5335/// having a particular non-static data member.
5336bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5337 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5338 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5339
5340 if (CSM == Sema::CXXDefaultConstructor) {
5341 // For a default constructor, all references must be initialized in-class
5342 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005343 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5344 if (Diagnose)
5345 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5346 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005347 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005348 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005349 // C++11 [class.ctor]p5: any non-variant non-static data member of
5350 // const-qualified type (or array thereof) with no
5351 // brace-or-equal-initializer does not have a user-provided default
5352 // constructor.
5353 if (!inUnion() && FieldType.isConstQualified() &&
5354 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005355 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5356 if (Diagnose)
5357 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005358 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005359 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005360 }
5361
5362 if (inUnion() && !FieldType.isConstQualified())
5363 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005364 } else if (CSM == Sema::CXXCopyConstructor) {
5365 // For a copy constructor, data members must not be of rvalue reference
5366 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005367 if (FieldType->isRValueReferenceType()) {
5368 if (Diagnose)
5369 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5370 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005371 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005372 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005373 } else if (IsAssignment) {
5374 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005375 if (FieldType->isReferenceType()) {
5376 if (Diagnose)
5377 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5378 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005379 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005380 }
5381 if (!FieldRecord && FieldType.isConstQualified()) {
5382 // C++11 [class.copy]p23:
5383 // -- a non-static data member of const non-class type (or array thereof)
5384 if (Diagnose)
5385 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005386 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005387 return true;
5388 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005389 }
5390
5391 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005392 // Some additional restrictions exist on the variant members.
5393 if (!inUnion() && FieldRecord->isUnion() &&
5394 FieldRecord->isAnonymousStructOrUnion()) {
5395 bool AllVariantFieldsAreConst = true;
5396
Richard Smith5704fe82012-03-29 19:00:10 +00005397 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005398 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005399 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005400
5401 if (!UnionFieldType.isConstQualified())
5402 AllVariantFieldsAreConst = false;
5403
Richard Smith921bd202012-02-26 09:11:52 +00005404 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5405 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005406 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005407 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005408 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005409 }
5410
5411 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005412 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005413 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005414 if (Diagnose)
5415 S.Diag(FieldRecord->getLocation(),
5416 diag::note_deleted_default_ctor_all_const)
5417 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005418 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005419 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005420
Richard Smith5704fe82012-03-29 19:00:10 +00005421 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005422 // This is technically non-conformant, but sanity demands it.
5423 return false;
5424 }
5425
Richard Smithaf136f82012-07-18 03:51:16 +00005426 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5427 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005428 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005429 }
5430
5431 return false;
5432}
5433
5434/// C++11 [class.ctor] p5:
5435/// A defaulted default constructor for a class X is defined as deleted if
5436/// X is a union and all of its variant members are of const-qualified type.
5437bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005438 // This is a silly definition, because it gives an empty union a deleted
5439 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005440 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005441 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005442 if (Diagnose)
5443 S.Diag(MD->getParent()->getLocation(),
5444 diag::note_deleted_default_ctor_all_const)
5445 << MD->getParent() << /*not anonymous union*/0;
5446 return true;
5447 }
5448 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005449}
5450
5451/// Determine whether a defaulted special member function should be defined as
5452/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5453/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005454bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5455 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005456 if (MD->isInvalidDecl())
5457 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005458 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005459 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005460 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005461 return false;
5462
Richard Smithd951a1d2012-02-18 02:02:13 +00005463 // C++11 [expr.lambda.prim]p19:
5464 // The closure type associated with a lambda-expression has a
5465 // deleted (8.4.3) default constructor and a deleted copy
5466 // assignment operator.
5467 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005468 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5469 if (Diagnose)
5470 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005471 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005472 }
5473
Richard Smith6f1e2c62012-04-02 20:59:25 +00005474 // For an anonymous struct or union, the copy and assignment special members
5475 // will never be used, so skip the check. For an anonymous union declared at
5476 // namespace scope, the constructor and destructor are used.
5477 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5478 RD->isAnonymousStructOrUnion())
5479 return false;
5480
Richard Smith852265f2012-03-30 20:53:28 +00005481 // C++11 [class.copy]p7, p18:
5482 // If the class definition declares a move constructor or move assignment
5483 // operator, an implicitly declared copy constructor or copy assignment
5484 // operator is defined as deleted.
5485 if (MD->isImplicit() &&
5486 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005487 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005488
5489 // In Microsoft mode, a user-declared move only causes the deletion of the
5490 // corresponding copy operation, not both copy operations.
5491 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005492 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005493 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005494
5495 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005496 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005497 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005498 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005499 break;
5500 }
5501 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005502 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005503 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005504 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005505 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005506
5507 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005508 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005509 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005510 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005511 break;
5512 }
5513 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005514 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005515 }
5516
5517 if (UserDeclaredMove) {
5518 Diag(UserDeclaredMove->getLocation(),
5519 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005520 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005521 << UserDeclaredMove->isMoveAssignmentOperator();
5522 return true;
5523 }
5524 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005525
Richard Smith6f1e2c62012-04-02 20:59:25 +00005526 // Do access control from the special member function
5527 ContextRAII MethodContext(*this, MD);
5528
Richard Smith921bd202012-02-26 09:11:52 +00005529 // C++11 [class.dtor]p5:
5530 // -- for a virtual destructor, lookup of the non-array deallocation function
5531 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005532 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005533 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005534 DeclarationName Name =
5535 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5536 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005537 OperatorDelete, false)) {
5538 if (Diagnose)
5539 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005540 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005541 }
Richard Smith921bd202012-02-26 09:11:52 +00005542 }
5543
Richard Smith852265f2012-03-30 20:53:28 +00005544 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005545
Aaron Ballman574705e2014-03-13 15:41:46 +00005546 for (auto &BI : RD->bases())
5547 if (!BI.isVirtual() &&
5548 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005549 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005550
Richard Smithd1627032013-07-22 18:06:23 +00005551 // Per DR1611, do not consider virtual bases of constructors of abstract
5552 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005553 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005554 for (auto &BI : RD->vbases())
5555 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005556 return true;
5557 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005558
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005559 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005560 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005561 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005562 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005563
Richard Smithd951a1d2012-02-18 02:02:13 +00005564 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005565 return true;
5566
5567 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005568}
5569
Richard Smith92f241f2012-12-08 02:53:02 +00005570/// Perform lookup for a special member of the specified kind, and determine
5571/// whether it is trivial. If the triviality can be determined without the
5572/// lookup, skip it. This is intended for use when determining whether a
5573/// special member of a containing object is trivial, and thus does not ever
5574/// perform overload resolution for default constructors.
5575///
5576/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5577/// member that was most likely to be intended to be trivial, if any.
5578static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5579 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005580 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005581 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005582 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005583
5584 switch (CSM) {
5585 case Sema::CXXInvalid:
5586 llvm_unreachable("not a special member");
5587
5588 case Sema::CXXDefaultConstructor:
5589 // C++11 [class.ctor]p5:
5590 // A default constructor is trivial if:
5591 // - all the [direct subobjects] have trivial default constructors
5592 //
5593 // Note, no overload resolution is performed in this case.
5594 if (RD->hasTrivialDefaultConstructor())
5595 return true;
5596
5597 if (Selected) {
5598 // If there's a default constructor which could have been trivial, dig it
5599 // out. Otherwise, if there's any user-provided default constructor, point
5600 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005601 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005602 if (RD->needsImplicitDefaultConstructor())
5603 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005604 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005605 if (!CI->isDefaultConstructor())
5606 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005607 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005608 if (!DefCtor->isUserProvided())
5609 break;
5610 }
5611
5612 *Selected = DefCtor;
5613 }
5614
5615 return false;
5616
5617 case Sema::CXXDestructor:
5618 // C++11 [class.dtor]p5:
5619 // A destructor is trivial if:
5620 // - all the direct [subobjects] have trivial destructors
5621 if (RD->hasTrivialDestructor())
5622 return true;
5623
5624 if (Selected) {
5625 if (RD->needsImplicitDestructor())
5626 S.DeclareImplicitDestructor(RD);
5627 *Selected = RD->getDestructor();
5628 }
5629
5630 return false;
5631
5632 case Sema::CXXCopyConstructor:
5633 // C++11 [class.copy]p12:
5634 // A copy constructor is trivial if:
5635 // - the constructor selected to copy each direct [subobject] is trivial
5636 if (RD->hasTrivialCopyConstructor()) {
5637 if (Quals == Qualifiers::Const)
5638 // We must either select the trivial copy constructor or reach an
5639 // ambiguity; no need to actually perform overload resolution.
5640 return true;
5641 } else if (!Selected) {
5642 return false;
5643 }
5644 // In C++98, we are not supposed to perform overload resolution here, but we
5645 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5646 // cases like B as having a non-trivial copy constructor:
5647 // struct A { template<typename T> A(T&); };
5648 // struct B { mutable A a; };
5649 goto NeedOverloadResolution;
5650
5651 case Sema::CXXCopyAssignment:
5652 // C++11 [class.copy]p25:
5653 // A copy assignment operator is trivial if:
5654 // - the assignment operator selected to copy each direct [subobject] is
5655 // trivial
5656 if (RD->hasTrivialCopyAssignment()) {
5657 if (Quals == Qualifiers::Const)
5658 return true;
5659 } else if (!Selected) {
5660 return false;
5661 }
5662 // In C++98, we are not supposed to perform overload resolution here, but we
5663 // treat that as a language defect.
5664 goto NeedOverloadResolution;
5665
5666 case Sema::CXXMoveConstructor:
5667 case Sema::CXXMoveAssignment:
5668 NeedOverloadResolution:
5669 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005670 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005671
5672 // The standard doesn't describe how to behave if the lookup is ambiguous.
5673 // We treat it as not making the member non-trivial, just like the standard
5674 // mandates for the default constructor. This should rarely matter, because
5675 // the member will also be deleted.
5676 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5677 return true;
5678
5679 if (!SMOR->getMethod()) {
5680 assert(SMOR->getKind() ==
5681 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5682 return false;
5683 }
5684
5685 // We deliberately don't check if we found a deleted special member. We're
5686 // not supposed to!
5687 if (Selected)
5688 *Selected = SMOR->getMethod();
5689 return SMOR->getMethod()->isTrivial();
5690 }
5691
5692 llvm_unreachable("unknown special method kind");
5693}
5694
Benjamin Kramer3e350262013-02-15 12:30:38 +00005695static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005696 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005697 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005698 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005699
5700 // Look for constructor templates.
5701 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5702 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5703 if (CXXConstructorDecl *CD =
5704 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5705 return CD;
5706 }
5707
Craig Topperc3ec1492014-05-26 06:22:03 +00005708 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005709}
5710
5711/// The kind of subobject we are checking for triviality. The values of this
5712/// enumeration are used in diagnostics.
5713enum TrivialSubobjectKind {
5714 /// The subobject is a base class.
5715 TSK_BaseClass,
5716 /// The subobject is a non-static data member.
5717 TSK_Field,
5718 /// The object is actually the complete object.
5719 TSK_CompleteObject
5720};
5721
5722/// Check whether the special member selected for a given type would be trivial.
5723static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005724 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005725 Sema::CXXSpecialMember CSM,
5726 TrivialSubobjectKind Kind,
5727 bool Diagnose) {
5728 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5729 if (!SubRD)
5730 return true;
5731
5732 CXXMethodDecl *Selected;
5733 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005734 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005735 return true;
5736
5737 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005738 if (ConstRHS)
5739 SubType.addConst();
5740
Richard Smith92f241f2012-12-08 02:53:02 +00005741 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5742 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5743 << Kind << SubType.getUnqualifiedType();
5744 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5745 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5746 } else if (!Selected)
5747 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5748 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5749 else if (Selected->isUserProvided()) {
5750 if (Kind == TSK_CompleteObject)
5751 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5752 << Kind << SubType.getUnqualifiedType() << CSM;
5753 else {
5754 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5755 << Kind << SubType.getUnqualifiedType() << CSM;
5756 S.Diag(Selected->getLocation(), diag::note_declared_at);
5757 }
5758 } else {
5759 if (Kind != TSK_CompleteObject)
5760 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5761 << Kind << SubType.getUnqualifiedType() << CSM;
5762
5763 // Explain why the defaulted or deleted special member isn't trivial.
5764 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5765 }
5766 }
5767
5768 return false;
5769}
5770
5771/// Check whether the members of a class type allow a special member to be
5772/// trivial.
5773static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5774 Sema::CXXSpecialMember CSM,
5775 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005776 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005777 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5778 continue;
5779
5780 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5781
5782 // Pretend anonymous struct or union members are members of this class.
5783 if (FI->isAnonymousStructOrUnion()) {
5784 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5785 CSM, ConstArg, Diagnose))
5786 return false;
5787 continue;
5788 }
5789
5790 // C++11 [class.ctor]p5:
5791 // A default constructor is trivial if [...]
5792 // -- no non-static data member of its class has a
5793 // brace-or-equal-initializer
5794 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5795 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005796 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005797 return false;
5798 }
5799
5800 // Objective C ARC 4.3.5:
5801 // [...] nontrivally ownership-qualified types are [...] not trivially
5802 // default constructible, copy constructible, move constructible, copy
5803 // assignable, move assignable, or destructible [...]
5804 if (S.getLangOpts().ObjCAutoRefCount &&
5805 FieldType.hasNonTrivialObjCLifetime()) {
5806 if (Diagnose)
5807 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5808 << RD << FieldType.getObjCLifetime();
5809 return false;
5810 }
5811
Richard Smith41c35d62013-11-27 03:39:20 +00005812 bool ConstRHS = ConstArg && !FI->isMutable();
5813 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5814 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005815 return false;
5816 }
5817
5818 return true;
5819}
5820
5821/// Diagnose why the specified class does not have a trivial special member of
5822/// the given kind.
5823void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5824 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005825
Richard Smith41c35d62013-11-27 03:39:20 +00005826 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5827 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005828 TSK_CompleteObject, /*Diagnose*/true);
5829}
5830
5831/// Determine whether a defaulted or deleted special member function is trivial,
5832/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5833/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5834bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5835 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005836 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5837
5838 CXXRecordDecl *RD = MD->getParent();
5839
5840 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005841
Richard Smith2002bfe2013-11-04 02:02:27 +00005842 // C++11 [class.copy]p12, p25: [DR1593]
5843 // A [special member] is trivial if [...] its parameter-type-list is
5844 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005845 switch (CSM) {
5846 case CXXDefaultConstructor:
5847 case CXXDestructor:
5848 // Trivial default constructors and destructors cannot have parameters.
5849 break;
5850
5851 case CXXCopyConstructor:
5852 case CXXCopyAssignment: {
5853 // Trivial copy operations always have const, non-volatile parameter types.
5854 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005855 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005856 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5857 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5858 if (Diagnose)
5859 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5860 << Param0->getSourceRange() << Param0->getType()
5861 << Context.getLValueReferenceType(
5862 Context.getRecordType(RD).withConst());
5863 return false;
5864 }
5865 break;
5866 }
5867
5868 case CXXMoveConstructor:
5869 case CXXMoveAssignment: {
5870 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005871 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005872 const RValueReferenceType *RT =
5873 Param0->getType()->getAs<RValueReferenceType>();
5874 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5875 if (Diagnose)
5876 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5877 << Param0->getSourceRange() << Param0->getType()
5878 << Context.getRValueReferenceType(Context.getRecordType(RD));
5879 return false;
5880 }
5881 break;
5882 }
5883
5884 case CXXInvalid:
5885 llvm_unreachable("not a special member");
5886 }
5887
Richard Smith92f241f2012-12-08 02:53:02 +00005888 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5889 if (Diagnose)
5890 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5891 diag::note_nontrivial_default_arg)
5892 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5893 return false;
5894 }
5895 if (MD->isVariadic()) {
5896 if (Diagnose)
5897 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5898 return false;
5899 }
5900
5901 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5902 // A copy/move [constructor or assignment operator] is trivial if
5903 // -- the [member] selected to copy/move each direct base class subobject
5904 // is trivial
5905 //
5906 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5907 // A [default constructor or destructor] is trivial if
5908 // -- all the direct base classes have trivial [default constructors or
5909 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005910 for (const auto &BI : RD->bases())
5911 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005912 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005913 return false;
5914
5915 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5916 // A copy/move [constructor or assignment operator] for a class X is
5917 // trivial if
5918 // -- for each non-static data member of X that is of class type (or array
5919 // thereof), the constructor selected to copy/move that member is
5920 // trivial
5921 //
5922 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5923 // A [default constructor or destructor] is trivial if
5924 // -- for all of the non-static data members of its class that are of class
5925 // type (or array thereof), each such class has a trivial [default
5926 // constructor or destructor]
5927 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5928 return false;
5929
5930 // C++11 [class.dtor]p5:
5931 // A destructor is trivial if [...]
5932 // -- the destructor is not virtual
5933 if (CSM == CXXDestructor && MD->isVirtual()) {
5934 if (Diagnose)
5935 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5936 return false;
5937 }
5938
5939 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5940 // A [special member] for class X is trivial if [...]
5941 // -- class X has no virtual functions and no virtual base classes
5942 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5943 if (!Diagnose)
5944 return false;
5945
5946 if (RD->getNumVBases()) {
5947 // Check for virtual bases. We already know that the corresponding
5948 // member in all bases is trivial, so vbases must all be direct.
5949 CXXBaseSpecifier &BS = *RD->vbases_begin();
5950 assert(BS.isVirtual());
5951 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5952 return false;
5953 }
5954
5955 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005956 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005957 if (MI->isVirtual()) {
5958 SourceLocation MLoc = MI->getLocStart();
5959 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5960 return false;
5961 }
5962 }
5963
5964 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5965 }
5966
5967 // Looks like it's trivial!
5968 return true;
5969}
5970
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005971/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005972namespace {
5973 struct FindHiddenVirtualMethodData {
5974 Sema *S;
5975 CXXMethodDecl *Method;
5976 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005977 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005978 };
5979}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005980
David Blaikie282c92a2012-10-19 00:53:08 +00005981/// \brief Check whether any most overriden method from MD in Methods
5982static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00005983 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00005984 if (MD->size_overridden_methods() == 0)
5985 return Methods.count(MD->getCanonicalDecl());
5986 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5987 E = MD->end_overridden_methods();
5988 I != E; ++I)
5989 if (CheckMostOverridenMethods(*I, Methods))
5990 return true;
5991 return false;
5992}
5993
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005994/// \brief Member lookup function that determines whether a given C++
5995/// method overloads virtual methods in a base class without overriding any,
5996/// to be used with CXXRecordDecl::lookupInBases().
5997static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5998 CXXBasePath &Path,
5999 void *UserData) {
6000 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6001
6002 FindHiddenVirtualMethodData &Data
6003 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6004
6005 DeclarationName Name = Data.Method->getDeclName();
6006 assert(Name.getNameKind() == DeclarationName::Identifier);
6007
6008 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006009 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006010 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006011 !Path.Decls.empty();
6012 Path.Decls = Path.Decls.slice(1)) {
6013 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006015 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006016 foundSameNameMethod = true;
6017 // Interested only in hidden virtual methods.
6018 if (!MD->isVirtual())
6019 continue;
6020 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006021 // don't warn about the other overloaded methods. Clang deviates from GCC
6022 // by only diagnosing overloads of inherited virtual functions that do not
6023 // override any other virtual functions in the base. GCC's
6024 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6025 // function from a base class. These cases may be better served by a
6026 // warning (not specific to virtual functions) on call sites when the call
6027 // would select a different function from the base class, were it visible.
6028 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006029 if (!Data.S->IsOverload(Data.Method, MD, false))
6030 return true;
6031 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006032 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006033 overloadedMethods.push_back(MD);
6034 }
6035 }
6036
6037 if (foundSameNameMethod)
6038 Data.OverloadedMethods.append(overloadedMethods.begin(),
6039 overloadedMethods.end());
6040 return foundSameNameMethod;
6041}
6042
David Blaikie282c92a2012-10-19 00:53:08 +00006043/// \brief Add the most overriden methods from MD to Methods
6044static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006045 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006046 if (MD->size_overridden_methods() == 0)
6047 Methods.insert(MD->getCanonicalDecl());
6048 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6049 E = MD->end_overridden_methods();
6050 I != E; ++I)
6051 AddMostOverridenMethods(*I, Methods);
6052}
6053
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006054/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006055/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006056void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6057 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006058 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006059 return;
6060
6061 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6062 /*bool RecordPaths=*/false,
6063 /*bool DetectVirtual=*/false);
6064 FindHiddenVirtualMethodData Data;
6065 Data.Method = MD;
6066 Data.S = this;
6067
6068 // Keep the base methods that were overriden or introduced in the subclass
6069 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006070 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006071 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6072 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6073 NamedDecl *ND = *I;
6074 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006075 ND = shad->getTargetDecl();
6076 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6077 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006078 }
6079
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006080 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6081 OverloadedMethods = Data.OverloadedMethods;
6082}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006083
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006084void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6085 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6086 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6087 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6088 PartialDiagnostic PD = PDiag(
6089 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6090 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6091 Diag(overloadedMD->getLocation(), PD);
6092 }
6093}
6094
6095/// \brief Diagnose methods which overload virtual methods in a base class
6096/// without overriding any.
6097void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6098 if (MD->isInvalidDecl())
6099 return;
6100
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006101 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006102 return;
6103
6104 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6105 FindHiddenVirtualMethods(MD, OverloadedMethods);
6106 if (!OverloadedMethods.empty()) {
6107 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6108 << MD << (OverloadedMethods.size() > 1);
6109
6110 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006111 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006112}
6113
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006114void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006115 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006116 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006117 SourceLocation RBrac,
6118 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006119 if (!TagDecl)
6120 return;
Mike Stump11289f42009-09-09 15:08:12 +00006121
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006122 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006123
Rafael Espindola06e1b132012-07-12 04:32:30 +00006124 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6125 if (l->getKind() != AttributeList::AT_Visibility)
6126 continue;
6127 l->setInvalid();
6128 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6129 l->getName();
6130 }
6131
David Blaikie751c5582011-09-22 02:58:26 +00006132 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006133 // strict aliasing violation!
6134 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006135 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006136
Douglas Gregor0be31a22010-07-02 17:43:08 +00006137 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006138 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006139}
6140
Douglas Gregor05379422008-11-03 17:51:48 +00006141/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6142/// special functions, such as the default constructor, copy
6143/// constructor, or destructor, to the given C++ class (C++
6144/// [special]p1). This routine can only be executed just before the
6145/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006146void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006147 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006148 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006149
Richard Smith6b02d462012-12-08 08:32:28 +00006150 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006151 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006152
Richard Smith6b02d462012-12-08 08:32:28 +00006153 // If the properties or semantics of the copy constructor couldn't be
6154 // determined while the class was being declared, force a declaration
6155 // of it now.
6156 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6157 DeclareImplicitCopyConstructor(ClassDecl);
6158 }
6159
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006160 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006161 ++ASTContext::NumImplicitMoveConstructors;
6162
Richard Smith6b02d462012-12-08 08:32:28 +00006163 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6164 DeclareImplicitMoveConstructor(ClassDecl);
6165 }
6166
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006167 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6168 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006169
6170 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006171 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006172 // it shows up in the right place in the vtable and that we diagnose
6173 // problems with the implicit exception specification.
6174 if (ClassDecl->isDynamicClass() ||
6175 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006176 DeclareImplicitCopyAssignment(ClassDecl);
6177 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006178
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006179 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006180 ++ASTContext::NumImplicitMoveAssignmentOperators;
6181
6182 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006183 if (ClassDecl->isDynamicClass() ||
6184 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006185 DeclareImplicitMoveAssignment(ClassDecl);
6186 }
6187
Douglas Gregor7454c562010-07-02 20:37:36 +00006188 if (!ClassDecl->hasUserDeclaredDestructor()) {
6189 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006190
6191 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006192 // have to declare the destructor immediately. This ensures that, e.g., it
6193 // shows up in the right place in the vtable and that we diagnose problems
6194 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006195 if (ClassDecl->isDynamicClass() ||
6196 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006197 DeclareImplicitDestructor(ClassDecl);
6198 }
Douglas Gregor05379422008-11-03 17:51:48 +00006199}
6200
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006201unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006202 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006203 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006204
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006205 // The order of template parameters is not important here. All names
6206 // get added to the same scope.
6207 SmallVector<TemplateParameterList *, 4> ParameterLists;
6208
6209 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6210 D = TD->getTemplatedDecl();
6211
6212 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6213 ParameterLists.push_back(PSD->getTemplateParameters());
6214
6215 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6216 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6217 ParameterLists.push_back(DD->getTemplateParameterList(i));
6218
6219 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6220 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6221 ParameterLists.push_back(FTD->getTemplateParameters());
6222 }
6223 }
6224
6225 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6226 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6227 ParameterLists.push_back(TD->getTemplateParameterList(i));
6228
6229 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6230 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6231 ParameterLists.push_back(CTD->getTemplateParameters());
6232 }
6233 }
6234
6235 unsigned Count = 0;
6236 for (TemplateParameterList *Params : ParameterLists) {
6237 if (Params->size() > 0)
6238 // Ignore explicit specializations; they don't contribute to the template
6239 // depth.
6240 ++Count;
6241 for (NamedDecl *Param : *Params) {
6242 if (Param->getDeclName()) {
6243 S->AddDecl(Param);
6244 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006245 }
6246 }
6247 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006248
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006249 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006250}
6251
John McCall48871652010-08-21 09:40:31 +00006252void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006253 if (!RecordD) return;
6254 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006255 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006256 PushDeclContext(S, Record);
6257}
6258
John McCall48871652010-08-21 09:40:31 +00006259void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006260 if (!RecordD) return;
6261 PopDeclContext();
6262}
6263
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006264/// This is used to implement the constant expression evaluation part of the
6265/// attribute enable_if extension. There is nothing in standard C++ which would
6266/// require reentering parameters.
6267void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6268 if (!Param)
6269 return;
6270
6271 S->AddDecl(Param);
6272 if (Param->getDeclName())
6273 IdResolver.AddDecl(Param);
6274}
6275
Douglas Gregor4d87df52008-12-16 21:30:33 +00006276/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6277/// parsing a top-level (non-nested) C++ class, and we are now
6278/// parsing those parts of the given Method declaration that could
6279/// not be parsed earlier (C++ [class.mem]p2), such as default
6280/// arguments. This action should enter the scope of the given
6281/// Method declaration as if we had just parsed the qualified method
6282/// name. However, it should not bring the parameters into scope;
6283/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006284void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006285}
6286
6287/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6288/// C++ method declaration. We're (re-)introducing the given
6289/// function parameter into scope for use in parsing later parts of
6290/// the method declaration. For example, we could see an
6291/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006292void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006293 if (!ParamD)
6294 return;
Mike Stump11289f42009-09-09 15:08:12 +00006295
John McCall48871652010-08-21 09:40:31 +00006296 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006297
6298 // If this parameter has an unparsed default argument, clear it out
6299 // to make way for the parsed default argument.
6300 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006301 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006302
John McCall48871652010-08-21 09:40:31 +00006303 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006304 if (Param->getDeclName())
6305 IdResolver.AddDecl(Param);
6306}
6307
6308/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6309/// processing the delayed method declaration for Method. The method
6310/// declaration is now considered finished. There may be a separate
6311/// ActOnStartOfFunctionDef action later (not necessarily
6312/// immediately!) for this method, if it was also defined inside the
6313/// class body.
John McCall48871652010-08-21 09:40:31 +00006314void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006315 if (!MethodD)
6316 return;
Mike Stump11289f42009-09-09 15:08:12 +00006317
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006318 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006319
John McCall48871652010-08-21 09:40:31 +00006320 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006321
6322 // Now that we have our default arguments, check the constructor
6323 // again. It could produce additional diagnostics or affect whether
6324 // the class has implicitly-declared destructors, among other
6325 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006326 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6327 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006328
6329 // Check the default arguments, which we may have added.
6330 if (!Method->isInvalidDecl())
6331 CheckCXXDefaultArguments(Method);
6332}
6333
Douglas Gregor831c93f2008-11-05 20:51:48 +00006334/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006335/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006336/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006337/// emit diagnostics and set the invalid bit to true. In any case, the type
6338/// will be updated to reflect a well-formed type for the constructor and
6339/// returned.
6340QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006341 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006342 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006343
6344 // C++ [class.ctor]p3:
6345 // A constructor shall not be virtual (10.3) or static (9.4). A
6346 // constructor can be invoked for a const, volatile or const
6347 // volatile object. A constructor shall not be declared const,
6348 // volatile, or const volatile (9.3.2).
6349 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006350 if (!D.isInvalidType())
6351 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6352 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6353 << SourceRange(D.getIdentifierLoc());
6354 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006355 }
John McCall8e7d6562010-08-26 03:08:43 +00006356 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006357 if (!D.isInvalidType())
6358 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6359 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6360 << SourceRange(D.getIdentifierLoc());
6361 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006362 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006363 }
Mike Stump11289f42009-09-09 15:08:12 +00006364
David Majnemer03f705f2014-07-08 18:18:04 +00006365 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6366 diagnoseIgnoredQualifiers(
6367 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6368 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6369 D.getDeclSpec().getRestrictSpecLoc(),
6370 D.getDeclSpec().getAtomicSpecLoc());
6371 D.setInvalidType();
6372 }
6373
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006374 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006375 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006376 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006377 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6378 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006379 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006380 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6381 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006382 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006383 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6384 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006385 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006386 }
Mike Stump11289f42009-09-09 15:08:12 +00006387
Douglas Gregordb9d6642011-01-26 05:01:58 +00006388 // C++0x [class.ctor]p4:
6389 // A constructor shall not be declared with a ref-qualifier.
6390 if (FTI.hasRefQualifier()) {
6391 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6392 << FTI.RefQualifierIsLValueRef
6393 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6394 D.setInvalidType();
6395 }
6396
Douglas Gregor831c93f2008-11-05 20:51:48 +00006397 // Rebuild the function type "R" without any type qualifiers (in
6398 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006399 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006400 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006401 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006402 return R;
6403
6404 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6405 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006406 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006407
6408 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006409}
6410
Douglas Gregor4d87df52008-12-16 21:30:33 +00006411/// CheckConstructor - Checks a fully-formed constructor for
6412/// well-formedness, issuing any diagnostics required. Returns true if
6413/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006414void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006415 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006416 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6417 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006418 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006419
6420 // C++ [class.copy]p3:
6421 // A declaration of a constructor for a class X is ill-formed if
6422 // its first parameter is of type (optionally cv-qualified) X and
6423 // either there are no other parameters or else all other
6424 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006425 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006426 ((Constructor->getNumParams() == 1) ||
6427 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006428 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6429 Constructor->getTemplateSpecializationKind()
6430 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006431 QualType ParamType = Constructor->getParamDecl(0)->getType();
6432 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6433 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006434 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006435 const char *ConstRef
6436 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6437 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006438 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006439 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006440
6441 // FIXME: Rather that making the constructor invalid, we should endeavor
6442 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006443 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006444 }
6445 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006446}
6447
John McCalldeb646e2010-08-04 01:04:25 +00006448/// CheckDestructor - Checks a fully-formed destructor definition for
6449/// well-formedness, issuing any diagnostics required. Returns true
6450/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006451bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006452 CXXRecordDecl *RD = Destructor->getParent();
6453
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006454 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006455 SourceLocation Loc;
6456
6457 if (!Destructor->isImplicit())
6458 Loc = Destructor->getLocation();
6459 else
6460 Loc = RD->getLocation();
6461
6462 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006463 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006464 DeclarationName Name =
6465 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006466 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006467 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006468 // If there's no class-specific operator delete, look up the global
6469 // non-array delete.
6470 if (!OperatorDelete)
6471 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006472
Eli Friedmanfa0df832012-02-02 03:46:19 +00006473 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006474
6475 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006476 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006477
6478 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006479}
6480
Douglas Gregor831c93f2008-11-05 20:51:48 +00006481/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6482/// the well-formednes of the destructor declarator @p D with type @p
6483/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006484/// emit diagnostics and set the declarator to invalid. Even if this happens,
6485/// will be updated to reflect a well-formed type for the destructor and
6486/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006487QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006488 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006489 // C++ [class.dtor]p1:
6490 // [...] A typedef-name that names a class is a class-name
6491 // (7.1.3); however, a typedef-name that names a class shall not
6492 // be used as the identifier in the declarator for a destructor
6493 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006494 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006495 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006496 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006497 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006498 else if (const TemplateSpecializationType *TST =
6499 DeclaratorType->getAs<TemplateSpecializationType>())
6500 if (TST->isTypeAlias())
6501 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6502 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006503
6504 // C++ [class.dtor]p2:
6505 // A destructor is used to destroy objects of its class type. A
6506 // destructor takes no parameters, and no return type can be
6507 // specified for it (not even void). The address of a destructor
6508 // shall not be taken. A destructor shall not be static. A
6509 // destructor can be invoked for a const, volatile or const
6510 // volatile object. A destructor shall not be declared const,
6511 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006512 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006513 if (!D.isInvalidType())
6514 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6515 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006516 << SourceRange(D.getIdentifierLoc())
6517 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6518
John McCall8e7d6562010-08-26 03:08:43 +00006519 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006520 }
David Majnemer03f705f2014-07-08 18:18:04 +00006521 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006522 // Destructors don't have return types, but the parser will
6523 // happily parse something like:
6524 //
6525 // class X {
6526 // float ~X();
6527 // };
6528 //
6529 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006530 if (D.getDeclSpec().hasTypeSpecifier())
6531 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6532 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6533 << SourceRange(D.getIdentifierLoc());
6534 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6535 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6536 SourceLocation(),
6537 D.getDeclSpec().getConstSpecLoc(),
6538 D.getDeclSpec().getVolatileSpecLoc(),
6539 D.getDeclSpec().getRestrictSpecLoc(),
6540 D.getDeclSpec().getAtomicSpecLoc());
6541 D.setInvalidType();
6542 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006543 }
Mike Stump11289f42009-09-09 15:08:12 +00006544
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006545 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006546 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006547 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006548 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6549 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006550 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006551 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6552 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006553 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006554 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6555 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006556 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006557 }
6558
Douglas Gregordb9d6642011-01-26 05:01:58 +00006559 // C++0x [class.dtor]p2:
6560 // A destructor shall not be declared with a ref-qualifier.
6561 if (FTI.hasRefQualifier()) {
6562 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6563 << FTI.RefQualifierIsLValueRef
6564 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6565 D.setInvalidType();
6566 }
6567
Douglas Gregor831c93f2008-11-05 20:51:48 +00006568 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006569 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006570 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6571
6572 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006573 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006574 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006575 }
6576
Mike Stump11289f42009-09-09 15:08:12 +00006577 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006578 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006579 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006580 D.setInvalidType();
6581 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006582
6583 // Rebuild the function type "R" without any type qualifiers or
6584 // parameters (in case any of the errors above fired) and with
6585 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006586 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006587 if (!D.isInvalidType())
6588 return R;
6589
Douglas Gregor95755162010-07-01 05:10:53 +00006590 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006591 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6592 EPI.Variadic = false;
6593 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006594 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006595 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006596}
6597
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006598/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6599/// well-formednes of the conversion function declarator @p D with
6600/// type @p R. If there are any errors in the declarator, this routine
6601/// will emit diagnostics and return true. Otherwise, it will return
6602/// false. Either way, the type @p R will be updated to reflect a
6603/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006604void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006605 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006606 // C++ [class.conv.fct]p1:
6607 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006608 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006609 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006610 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006611 if (!D.isInvalidType())
6612 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006613 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6614 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006615 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006616 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006617 }
John McCall212fa2e2010-04-13 00:04:31 +00006618
6619 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6620
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006621 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006622 // Conversion functions don't have return types, but the parser will
6623 // happily parse something like:
6624 //
6625 // class X {
6626 // float operator bool();
6627 // };
6628 //
6629 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006630 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6631 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6632 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006633 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006634 }
6635
John McCall212fa2e2010-04-13 00:04:31 +00006636 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6637
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006638 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006639 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006640 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6641
6642 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006643 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006644 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006645 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006646 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006647 D.setInvalidType();
6648 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006649
John McCall212fa2e2010-04-13 00:04:31 +00006650 // Diagnose "&operator bool()" and other such nonsense. This
6651 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006652 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006653 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006654 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006655 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006656 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006657 }
6658
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006659 // C++ [class.conv.fct]p4:
6660 // The conversion-type-id shall not represent a function type nor
6661 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006662 if (ConvType->isArrayType()) {
6663 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6664 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006665 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006666 } else if (ConvType->isFunctionType()) {
6667 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6668 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006669 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006670 }
6671
6672 // Rebuild the function type "R" without any parameters (in case any
6673 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006674 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006675 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006676 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006677
Douglas Gregor5fb53972009-01-14 15:45:31 +00006678 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006679 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006680 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006681 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006682 diag::warn_cxx98_compat_explicit_conversion_functions :
6683 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006684 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006685}
6686
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006687/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6688/// the declaration of the given C++ conversion function. This routine
6689/// is responsible for recording the conversion function in the C++
6690/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006691Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006692 assert(Conversion && "Expected to receive a conversion function declaration");
6693
Douglas Gregor4287b372008-12-12 08:25:50 +00006694 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006695
6696 // Make sure we aren't redeclaring the conversion function.
6697 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006698
6699 // C++ [class.conv.fct]p1:
6700 // [...] A conversion function is never used to convert a
6701 // (possibly cv-qualified) object to the (possibly cv-qualified)
6702 // same object type (or a reference to it), to a (possibly
6703 // cv-qualified) base class of that type (or a reference to it),
6704 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006705 // FIXME: Suppress this warning if the conversion function ends up being a
6706 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006707 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006708 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006709 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006710 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006711 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6712 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006713 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006714 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006715 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6716 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006717 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006718 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006719 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006720 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006721 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006722 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006723 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006724 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006725 }
6726
Douglas Gregor457104e2010-09-29 04:25:11 +00006727 if (FunctionTemplateDecl *ConversionTemplate
6728 = Conversion->getDescribedFunctionTemplate())
6729 return ConversionTemplate;
6730
John McCall48871652010-08-21 09:40:31 +00006731 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006732}
6733
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006734//===----------------------------------------------------------------------===//
6735// Namespace Handling
6736//===----------------------------------------------------------------------===//
6737
Richard Smith45bb8852012-10-04 22:13:39 +00006738/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6739/// reopened.
6740static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6741 SourceLocation Loc,
6742 IdentifierInfo *II, bool *IsInline,
6743 NamespaceDecl *PrevNS) {
6744 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006745
Richard Smithf501cc32012-10-05 01:46:25 +00006746 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6747 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6748 // inline namespaces, with the intention of bringing names into namespace std.
6749 //
6750 // We support this just well enough to get that case working; this is not
6751 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006752 if (*IsInline && II && II->getName().startswith("__atomic") &&
6753 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006754 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006755 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6756 NS = NS->getPreviousDecl())
6757 NS->setInline(*IsInline);
6758 // Patch up the lookup table for the containing namespace. This isn't really
6759 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006760 for (auto *I : PrevNS->decls())
6761 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006762 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6763 return;
6764 }
6765
6766 if (PrevNS->isInline())
6767 // The user probably just forgot the 'inline', so suggest that it
6768 // be added back.
6769 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6770 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6771 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006772 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006773
6774 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6775 *IsInline = PrevNS->isInline();
6776}
John McCallb1be5232010-08-26 09:15:37 +00006777
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006778/// ActOnStartNamespaceDef - This is called at the start of a namespace
6779/// definition.
John McCall48871652010-08-21 09:40:31 +00006780Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006781 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006782 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006783 SourceLocation IdentLoc,
6784 IdentifierInfo *II,
6785 SourceLocation LBrace,
6786 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006787 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6788 // For anonymous namespace, take the location of the left brace.
6789 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006790 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006791 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006792 bool IsStd = false;
6793 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006794 Scope *DeclRegionScope = NamespcScope->getParent();
6795
Craig Topperc3ec1492014-05-26 06:22:03 +00006796 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006797 if (II) {
6798 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006799 // The identifier in an original-namespace-definition shall not
6800 // have been previously defined in the declarative region in
6801 // which the original-namespace-definition appears. The
6802 // identifier in an original-namespace-definition is the name of
6803 // the namespace. Subsequently in that declarative region, it is
6804 // treated as an original-namespace-name.
6805 //
6806 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006807 // look through using directives, just look for any ordinary names.
6808
6809 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006810 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6811 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006812 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006813 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6814 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6815 ++I) {
6816 if ((*I)->getIdentifierNamespace() & IDNS) {
6817 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006818 break;
6819 }
6820 }
6821
Douglas Gregore57e7522012-01-07 09:11:48 +00006822 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6823
6824 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006825 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006826 if (IsInline != PrevNS->isInline())
6827 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6828 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006829 } else if (PrevDecl) {
6830 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006831 Diag(Loc, diag::err_redefinition_different_kind)
6832 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006833 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006834 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006835 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006836 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006837 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006838 // This is the first "real" definition of the namespace "std", so update
6839 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006840 PrevNS = getStdNamespace();
6841 IsStd = true;
6842 AddToKnown = !IsInline;
6843 } else {
6844 // We've seen this namespace for the first time.
6845 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006846 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006847 } else {
John McCall4fa53422009-10-01 00:25:31 +00006848 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006849
6850 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006851 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006852 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006853 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006854 } else {
6855 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006856 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006857 }
6858
Richard Smith45bb8852012-10-04 22:13:39 +00006859 if (PrevNS && IsInline != PrevNS->isInline())
6860 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6861 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006862 }
6863
6864 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6865 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006866 if (IsInvalid)
6867 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006868
6869 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006870
Douglas Gregore57e7522012-01-07 09:11:48 +00006871 // FIXME: Should we be merging attributes?
6872 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006873 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006874
6875 if (IsStd)
6876 StdNamespace = Namespc;
6877 if (AddToKnown)
6878 KnownNamespaces[Namespc] = false;
6879
6880 if (II) {
6881 PushOnScopeChains(Namespc, DeclRegionScope);
6882 } else {
6883 // Link the anonymous namespace into its parent.
6884 DeclContext *Parent = CurContext->getRedeclContext();
6885 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6886 TU->setAnonymousNamespace(Namespc);
6887 } else {
6888 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006889 }
John McCall4fa53422009-10-01 00:25:31 +00006890
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006891 CurContext->addDecl(Namespc);
6892
John McCall4fa53422009-10-01 00:25:31 +00006893 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6894 // behaves as if it were replaced by
6895 // namespace unique { /* empty body */ }
6896 // using namespace unique;
6897 // namespace unique { namespace-body }
6898 // where all occurrences of 'unique' in a translation unit are
6899 // replaced by the same identifier and this identifier differs
6900 // from all other identifiers in the entire program.
6901
6902 // We just create the namespace with an empty name and then add an
6903 // implicit using declaration, just like the standard suggests.
6904 //
6905 // CodeGen enforces the "universally unique" aspect by giving all
6906 // declarations semantically contained within an anonymous
6907 // namespace internal linkage.
6908
Douglas Gregore57e7522012-01-07 09:11:48 +00006909 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006910 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006911 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006912 /* 'using' */ LBrace,
6913 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006914 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006915 /* identifier */ SourceLocation(),
6916 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006917 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006918 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006919 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006920 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006921 }
6922
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006923 ActOnDocumentableDecl(Namespc);
6924
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006925 // Although we could have an invalid decl (i.e. the namespace name is a
6926 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006927 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6928 // for the namespace has the declarations that showed up in that particular
6929 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006930 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006931 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006932}
6933
Sebastian Redla6602e92009-11-23 15:34:23 +00006934/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6935/// is a namespace alias, returns the namespace it points to.
6936static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6937 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6938 return AD->getNamespace();
6939 return dyn_cast_or_null<NamespaceDecl>(D);
6940}
6941
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006942/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6943/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006944void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006945 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6946 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006947 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006948 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006949 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006950 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006951}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006952
John McCall28a0cf72010-08-25 07:42:41 +00006953CXXRecordDecl *Sema::getStdBadAlloc() const {
6954 return cast_or_null<CXXRecordDecl>(
6955 StdBadAlloc.get(Context.getExternalSource()));
6956}
6957
6958NamespaceDecl *Sema::getStdNamespace() const {
6959 return cast_or_null<NamespaceDecl>(
6960 StdNamespace.get(Context.getExternalSource()));
6961}
6962
Douglas Gregorcdf87022010-06-29 17:53:46 +00006963/// \brief Retrieve the special "std" namespace, which may require us to
6964/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006965NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006966 if (!StdNamespace) {
6967 // The "std" namespace has not yet been defined, so build one implicitly.
6968 StdNamespace = NamespaceDecl::Create(Context,
6969 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006970 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006971 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006972 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006973 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006974 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006975 }
6976
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006977 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006978}
6979
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006980bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006981 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006982 "Looking for std::initializer_list outside of C++.");
6983
6984 // We're looking for implicit instantiations of
6985 // template <typename E> class std::initializer_list.
6986
6987 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6988 return false;
6989
Craig Topperc3ec1492014-05-26 06:22:03 +00006990 ClassTemplateDecl *Template = nullptr;
6991 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006992
Sebastian Redl43144e72012-01-17 22:49:58 +00006993 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006994
Sebastian Redl43144e72012-01-17 22:49:58 +00006995 ClassTemplateSpecializationDecl *Specialization =
6996 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6997 if (!Specialization)
6998 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006999
Sebastian Redl43144e72012-01-17 22:49:58 +00007000 Template = Specialization->getSpecializedTemplate();
7001 Arguments = Specialization->getTemplateArgs().data();
7002 } else if (const TemplateSpecializationType *TST =
7003 Ty->getAs<TemplateSpecializationType>()) {
7004 Template = dyn_cast_or_null<ClassTemplateDecl>(
7005 TST->getTemplateName().getAsTemplateDecl());
7006 Arguments = TST->getArgs();
7007 }
7008 if (!Template)
7009 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007010
7011 if (!StdInitializerList) {
7012 // Haven't recognized std::initializer_list yet, maybe this is it.
7013 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7014 if (TemplateClass->getIdentifier() !=
7015 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007016 !getStdNamespace()->InEnclosingNamespaceSetOf(
7017 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007018 return false;
7019 // This is a template called std::initializer_list, but is it the right
7020 // template?
7021 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007022 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007023 return false;
7024 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7025 return false;
7026
7027 // It's the right template.
7028 StdInitializerList = Template;
7029 }
7030
7031 if (Template != StdInitializerList)
7032 return false;
7033
7034 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007035 if (Element)
7036 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007037 return true;
7038}
7039
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007040static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7041 NamespaceDecl *Std = S.getStdNamespace();
7042 if (!Std) {
7043 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007044 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007045 }
7046
7047 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7048 Loc, Sema::LookupOrdinaryName);
7049 if (!S.LookupQualifiedName(Result, Std)) {
7050 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007051 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007052 }
7053 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7054 if (!Template) {
7055 Result.suppressDiagnostics();
7056 // We found something weird. Complain about the first thing we found.
7057 NamedDecl *Found = *Result.begin();
7058 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007059 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007060 }
7061
7062 // We found some template called std::initializer_list. Now verify that it's
7063 // correct.
7064 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007065 if (Params->getMinRequiredArguments() != 1 ||
7066 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007067 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007068 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007069 }
7070
7071 return Template;
7072}
7073
7074QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7075 if (!StdInitializerList) {
7076 StdInitializerList = LookupStdInitializerList(*this, Loc);
7077 if (!StdInitializerList)
7078 return QualType();
7079 }
7080
7081 TemplateArgumentListInfo Args(Loc, Loc);
7082 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7083 Context.getTrivialTypeSourceInfo(Element,
7084 Loc)));
7085 return Context.getCanonicalType(
7086 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7087}
7088
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007089bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7090 // C++ [dcl.init.list]p2:
7091 // A constructor is an initializer-list constructor if its first parameter
7092 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7093 // std::initializer_list<E> for some type E, and either there are no other
7094 // parameters or else all other parameters have default arguments.
7095 if (Ctor->getNumParams() < 1 ||
7096 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7097 return false;
7098
7099 QualType ArgType = Ctor->getParamDecl(0)->getType();
7100 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7101 ArgType = RT->getPointeeType().getUnqualifiedType();
7102
Craig Topperc3ec1492014-05-26 06:22:03 +00007103 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007104}
7105
Douglas Gregora172e082011-03-26 22:25:30 +00007106/// \brief Determine whether a using statement is in a context where it will be
7107/// apply in all contexts.
7108static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7109 switch (CurContext->getDeclKind()) {
7110 case Decl::TranslationUnit:
7111 return true;
7112 case Decl::LinkageSpec:
7113 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7114 default:
7115 return false;
7116 }
7117}
7118
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007119namespace {
7120
7121// Callback to only accept typo corrections that are namespaces.
7122class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007123public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007124 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007125 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007126 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007127 return false;
7128 }
7129};
7130
7131}
7132
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007133static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7134 CXXScopeSpec &SS,
7135 SourceLocation IdentLoc,
7136 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007137 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007138 R.clear();
7139 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007140 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00007141 Validator,
7142 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007143 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007144 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7145 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007146 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007147 S.diagnoseTypo(Corrected,
7148 S.PDiag(diag::err_using_directive_member_suggest)
7149 << Ident << DC << DroppedSpecifier << SS.getRange(),
7150 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007151 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007152 S.diagnoseTypo(Corrected,
7153 S.PDiag(diag::err_using_directive_suggest) << Ident,
7154 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007155 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007156 R.addDecl(Corrected.getCorrectionDecl());
7157 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007158 }
7159 return false;
7160}
7161
John McCall48871652010-08-21 09:40:31 +00007162Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007163 SourceLocation UsingLoc,
7164 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007165 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007166 SourceLocation IdentLoc,
7167 IdentifierInfo *NamespcName,
7168 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007169 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7170 assert(NamespcName && "Invalid NamespcName.");
7171 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007172
7173 // This can only happen along a recovery path.
7174 while (S->getFlags() & Scope::TemplateParamScope)
7175 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007176 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007177
Craig Topperc3ec1492014-05-26 06:22:03 +00007178 UsingDirectiveDecl *UDir = nullptr;
7179 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007180 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007181 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007182
Douglas Gregor34074322009-01-14 22:20:51 +00007183 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007184 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7185 LookupParsedName(R, S, &SS);
7186 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007187 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007188
Douglas Gregorcdf87022010-06-29 17:53:46 +00007189 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007190 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007191 // Allow "using namespace std;" or "using namespace ::std;" even if
7192 // "std" hasn't been defined yet, for GCC compatibility.
7193 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7194 NamespcName->isStr("std")) {
7195 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007196 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007197 R.resolveKind();
7198 }
7199 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007200 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007201 }
7202
John McCall9f3059a2009-10-09 21:13:30 +00007203 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007204 NamedDecl *Named = R.getFoundDecl();
7205 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7206 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007207 // C++ [namespace.udir]p1:
7208 // A using-directive specifies that the names in the nominated
7209 // namespace can be used in the scope in which the
7210 // using-directive appears after the using-directive. During
7211 // unqualified name lookup (3.4.1), the names appear as if they
7212 // were declared in the nearest enclosing namespace which
7213 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007214 // namespace. [Note: in this context, "contains" means "contains
7215 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007216
7217 // Find enclosing context containing both using-directive and
7218 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007219 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007220 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7221 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7222 CommonAncestor = CommonAncestor->getParent();
7223
Sebastian Redla6602e92009-11-23 15:34:23 +00007224 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007225 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007226 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007227
Douglas Gregora172e082011-03-26 22:25:30 +00007228 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007229 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007230 Diag(IdentLoc, diag::warn_using_directive_in_header);
7231 }
7232
Douglas Gregor889ceb72009-02-03 19:21:40 +00007233 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007234 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007235 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007236 }
7237
Richard Smith54ecd982013-02-20 19:22:51 +00007238 if (UDir)
7239 ProcessDeclAttributeList(S, UDir, AttrList);
7240
John McCall48871652010-08-21 09:40:31 +00007241 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007242}
7243
7244void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007245 // If the scope has an associated entity and the using directive is at
7246 // namespace or translation unit scope, add the UsingDirectiveDecl into
7247 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007248 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007249 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007250 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007251 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007252 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007253 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007254 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007255}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007256
Douglas Gregorfec52632009-06-20 00:51:54 +00007257
John McCall48871652010-08-21 09:40:31 +00007258Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007259 AccessSpecifier AS,
7260 bool HasUsingKeyword,
7261 SourceLocation UsingLoc,
7262 CXXScopeSpec &SS,
7263 UnqualifiedId &Name,
7264 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007265 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007266 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007267 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007268
Douglas Gregor220f4272009-11-04 16:30:06 +00007269 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007270 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007271 case UnqualifiedId::IK_Identifier:
7272 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007273 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007274 case UnqualifiedId::IK_ConversionFunctionId:
7275 break;
7276
7277 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007278 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007279 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007280 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007281 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007282 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007283 diag::err_using_decl_constructor)
7284 << SS.getRange();
7285
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007286 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007287
Craig Topperc3ec1492014-05-26 06:22:03 +00007288 return nullptr;
7289
Douglas Gregor220f4272009-11-04 16:30:06 +00007290 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007291 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007292 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007293 return nullptr;
7294
Douglas Gregor220f4272009-11-04 16:30:06 +00007295 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007296 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007297 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007298 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007299 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007300
7301 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7302 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007303 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007304 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007305
Richard Smithc2bc61b2013-03-18 21:12:30 +00007306 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007307 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007308 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007309 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7310 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007311 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007312 }
7313
Douglas Gregorc4356532010-12-16 00:46:58 +00007314 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7315 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007316 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007317
John McCall3f746822009-11-17 05:59:44 +00007318 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007319 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007320 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007321 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007322 if (UD)
7323 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007324
John McCall48871652010-08-21 09:40:31 +00007325 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007326}
7327
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007328/// \brief Determine whether a using declaration considers the given
7329/// declarations as "equivalent", e.g., if they are redeclarations of
7330/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007331static bool
7332IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7333 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007334 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007335
Richard Smithdda56e42011-04-15 14:24:37 +00007336 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007337 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007338 return Context.hasSameType(TD1->getUnderlyingType(),
7339 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007340
7341 return false;
7342}
7343
7344
John McCall84d87672009-12-10 09:41:52 +00007345/// Determines whether to create a using shadow decl for a particular
7346/// decl, given the set of decls existing prior to this using lookup.
7347bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007348 const LookupResult &Previous,
7349 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007350 // Diagnose finding a decl which is not from a base class of the
7351 // current class. We do this now because there are cases where this
7352 // function will silently decide not to build a shadow decl, which
7353 // will pre-empt further diagnostics.
7354 //
7355 // We don't need to do this in C++0x because we do the check once on
7356 // the qualifier.
7357 //
7358 // FIXME: diagnose the following if we care enough:
7359 // struct A { int foo; };
7360 // struct B : A { using A::foo; };
7361 // template <class T> struct C : A {};
7362 // template <class T> struct D : C<T> { using B::foo; } // <---
7363 // This is invalid (during instantiation) in C++03 because B::foo
7364 // resolves to the using decl in B, which is not a base class of D<T>.
7365 // We can't diagnose it immediately because C<T> is an unknown
7366 // specialization. The UsingShadowDecl in D<T> then points directly
7367 // to A::foo, which will look well-formed when we instantiate.
7368 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007369 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007370 DeclContext *OrigDC = Orig->getDeclContext();
7371
7372 // Handle enums and anonymous structs.
7373 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7374 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7375 while (OrigRec->isAnonymousStructOrUnion())
7376 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7377
7378 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7379 if (OrigDC == CurContext) {
7380 Diag(Using->getLocation(),
7381 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007382 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007383 Diag(Orig->getLocation(), diag::note_using_decl_target);
7384 return true;
7385 }
7386
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007387 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007388 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007389 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007390 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007391 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007392 Diag(Orig->getLocation(), diag::note_using_decl_target);
7393 return true;
7394 }
7395 }
7396
7397 if (Previous.empty()) return false;
7398
7399 NamedDecl *Target = Orig;
7400 if (isa<UsingShadowDecl>(Target))
7401 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7402
John McCalla17e83e2009-12-11 02:33:26 +00007403 // If the target happens to be one of the previous declarations, we
7404 // don't have a conflict.
7405 //
7406 // FIXME: but we might be increasing its access, in which case we
7407 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007408 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007409 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007410 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7411 I != E; ++I) {
7412 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007413 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7414 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7415 PrevShadow = Shadow;
7416 FoundEquivalentDecl = true;
7417 }
John McCalla17e83e2009-12-11 02:33:26 +00007418
7419 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7420 }
7421
Richard Smithfd8634a2013-10-23 02:17:46 +00007422 if (FoundEquivalentDecl)
7423 return false;
7424
Alp Tokera2794f92014-01-22 07:29:52 +00007425 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007426 NamedDecl *OldDecl = nullptr;
7427 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7428 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007429 case Ovl_Overload:
7430 return false;
7431
7432 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007433 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007434 break;
Richard Smith18819302014-02-06 01:31:33 +00007435
John McCall84d87672009-12-10 09:41:52 +00007436 // We found a decl with the exact signature.
7437 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007438 // If we're in a record, we want to hide the target, so we
7439 // return true (without a diagnostic) to tell the caller not to
7440 // build a shadow decl.
7441 if (CurContext->isRecord())
7442 return true;
7443
7444 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007445 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007446 break;
7447 }
7448
7449 Diag(Target->getLocation(), diag::note_using_decl_target);
7450 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7451 return true;
7452 }
7453
7454 // Target is not a function.
7455
John McCall84d87672009-12-10 09:41:52 +00007456 if (isa<TagDecl>(Target)) {
7457 // No conflict between a tag and a non-tag.
7458 if (!Tag) return false;
7459
John McCalle29c5cd2009-12-10 19:51:03 +00007460 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007461 Diag(Target->getLocation(), diag::note_using_decl_target);
7462 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7463 return true;
7464 }
7465
7466 // No conflict between a tag and a non-tag.
7467 if (!NonTag) return false;
7468
John McCalle29c5cd2009-12-10 19:51:03 +00007469 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007470 Diag(Target->getLocation(), diag::note_using_decl_target);
7471 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7472 return true;
7473}
7474
John McCall3f746822009-11-17 05:59:44 +00007475/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007476UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007477 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007478 NamedDecl *Orig,
7479 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007480
7481 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007482 NamedDecl *Target = Orig;
7483 if (isa<UsingShadowDecl>(Target)) {
7484 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7485 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007486 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007487
John McCall3f746822009-11-17 05:59:44 +00007488 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007489 = UsingShadowDecl::Create(Context, CurContext,
7490 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007491 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007492
Douglas Gregor457104e2010-09-29 04:25:11 +00007493 Shadow->setAccess(UD->getAccess());
7494 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7495 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007496
7497 Shadow->setPreviousDecl(PrevDecl);
7498
John McCall3f746822009-11-17 05:59:44 +00007499 if (S)
John McCall3969e302009-12-08 07:46:18 +00007500 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007501 else
John McCall3969e302009-12-08 07:46:18 +00007502 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007503
John McCall3969e302009-12-08 07:46:18 +00007504
John McCall84d87672009-12-10 09:41:52 +00007505 return Shadow;
7506}
John McCall3969e302009-12-08 07:46:18 +00007507
John McCall84d87672009-12-10 09:41:52 +00007508/// Hides a using shadow declaration. This is required by the current
7509/// using-decl implementation when a resolvable using declaration in a
7510/// class is followed by a declaration which would hide or override
7511/// one or more of the using decl's targets; for example:
7512///
7513/// struct Base { void foo(int); };
7514/// struct Derived : Base {
7515/// using Base::foo;
7516/// void foo(int);
7517/// };
7518///
7519/// The governing language is C++03 [namespace.udecl]p12:
7520///
7521/// When a using-declaration brings names from a base class into a
7522/// derived class scope, member functions in the derived class
7523/// override and/or hide member functions with the same name and
7524/// parameter types in a base class (rather than conflicting).
7525///
7526/// There are two ways to implement this:
7527/// (1) optimistically create shadow decls when they're not hidden
7528/// by existing declarations, or
7529/// (2) don't create any shadow decls (or at least don't make them
7530/// visible) until we've fully parsed/instantiated the class.
7531/// The problem with (1) is that we might have to retroactively remove
7532/// a shadow decl, which requires several O(n) operations because the
7533/// decl structures are (very reasonably) not designed for removal.
7534/// (2) avoids this but is very fiddly and phase-dependent.
7535void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007536 if (Shadow->getDeclName().getNameKind() ==
7537 DeclarationName::CXXConversionFunctionName)
7538 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7539
John McCall84d87672009-12-10 09:41:52 +00007540 // Remove it from the DeclContext...
7541 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007542
John McCall84d87672009-12-10 09:41:52 +00007543 // ...and the scope, if applicable...
7544 if (S) {
John McCall48871652010-08-21 09:40:31 +00007545 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007546 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007547 }
7548
John McCall84d87672009-12-10 09:41:52 +00007549 // ...and the using decl.
7550 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7551
7552 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007553 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007554}
7555
Richard Smith09d5b3a2014-05-01 00:35:04 +00007556/// Find the base specifier for a base class with the given type.
7557static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7558 QualType DesiredBase,
7559 bool &AnyDependentBases) {
7560 // Check whether the named type is a direct base class.
7561 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7562 for (auto &Base : Derived->bases()) {
7563 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7564 if (CanonicalDesiredBase == BaseType)
7565 return &Base;
7566 if (BaseType->isDependentType())
7567 AnyDependentBases = true;
7568 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007569 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007570}
7571
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007572namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007573class UsingValidatorCCC : public CorrectionCandidateCallback {
7574public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007575 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007576 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007577 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007578 IsInstantiation(IsInstantiation), OldNNS(NNS),
7579 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007580
Craig Toppera798a9d2014-03-02 09:32:10 +00007581 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007582 NamedDecl *ND = Candidate.getCorrectionDecl();
7583
7584 // Keywords are not valid here.
7585 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007586 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007587
7588 // Completely unqualified names are invalid for a 'using' declaration.
7589 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7590 return false;
7591
Richard Smith09d5b3a2014-05-01 00:35:04 +00007592 if (RequireMemberOf) {
7593 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7594 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7595 // No-one ever wants a using-declaration to name an injected-class-name
7596 // of a base class, unless they're declaring an inheriting constructor.
7597 ASTContext &Ctx = ND->getASTContext();
7598 if (!Ctx.getLangOpts().CPlusPlus11)
7599 return false;
7600 QualType FoundType = Ctx.getRecordType(FoundRecord);
7601
7602 // Check that the injected-class-name is named as a member of its own
7603 // type; we don't want to suggest 'using Derived::Base;', since that
7604 // means something else.
7605 NestedNameSpecifier *Specifier =
7606 Candidate.WillReplaceSpecifier()
7607 ? Candidate.getCorrectionSpecifier()
7608 : OldNNS;
7609 if (!Specifier->getAsType() ||
7610 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7611 return false;
7612
7613 // Check that this inheriting constructor declaration actually names a
7614 // direct base class of the current class.
7615 bool AnyDependentBases = false;
7616 if (!findDirectBaseWithType(RequireMemberOf,
7617 Ctx.getRecordType(FoundRecord),
7618 AnyDependentBases) &&
7619 !AnyDependentBases)
7620 return false;
7621 } else {
7622 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7623 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7624 return false;
7625
7626 // FIXME: Check that the base class member is accessible?
7627 }
7628 }
7629
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007630 if (isa<TypeDecl>(ND))
7631 return HasTypenameKeyword || !IsInstantiation;
7632
7633 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007634 }
7635
7636private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007637 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007638 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007639 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007640 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007641};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007642} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007643
John McCalle61f2ba2009-11-18 02:36:19 +00007644/// Builds a using declaration.
7645///
7646/// \param IsInstantiation - Whether this call arises from an
7647/// instantiation of an unresolved using declaration. We treat
7648/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007649NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7650 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007651 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007652 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007653 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007654 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007655 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007656 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007657 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007658 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007659 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007660
Anders Carlssonf038fc22009-08-28 05:49:21 +00007661 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007662
Anders Carlsson59140b32009-08-28 03:16:11 +00007663 if (SS.isEmpty()) {
7664 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007665 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007666 }
Mike Stump11289f42009-09-09 15:08:12 +00007667
John McCall84d87672009-12-10 09:41:52 +00007668 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007669 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007670 ForRedeclaration);
7671 Previous.setHideTags(false);
7672 if (S) {
7673 LookupName(Previous, S);
7674
7675 // It is really dumb that we have to do this.
7676 LookupResult::Filter F = Previous.makeFilter();
7677 while (F.hasNext()) {
7678 NamedDecl *D = F.next();
7679 if (!isDeclInScope(D, CurContext, S))
7680 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007681 // If we found a local extern declaration that's not ordinarily visible,
7682 // and this declaration is being added to a non-block scope, ignore it.
7683 // We're only checking for scope conflicts here, not also for violations
7684 // of the linkage rules.
7685 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7686 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7687 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007688 }
7689 F.done();
7690 } else {
7691 assert(IsInstantiation && "no scope in non-instantiation");
7692 assert(CurContext->isRecord() && "scope not record in instantiation");
7693 LookupQualifiedName(Previous, CurContext);
7694 }
7695
John McCall84d87672009-12-10 09:41:52 +00007696 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007697 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7698 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007699 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007700
7701 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007702 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007703 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007704
John McCall84c16cf2009-11-12 03:15:40 +00007705 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007706 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007707 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007708 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007709 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007710 // FIXME: not all declaration name kinds are legal here
7711 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7712 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007713 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007714 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007715 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007716 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7717 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007718 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007719 D->setAccess(AS);
7720 CurContext->addDecl(D);
7721 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007722 }
John McCallb96ec562009-12-04 22:46:56 +00007723
Richard Smith09d5b3a2014-05-01 00:35:04 +00007724 auto Build = [&](bool Invalid) {
7725 UsingDecl *UD =
7726 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7727 HasTypenameKeyword);
7728 UD->setAccess(AS);
7729 CurContext->addDecl(UD);
7730 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007731 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007732 };
7733 auto BuildInvalid = [&]{ return Build(true); };
7734 auto BuildValid = [&]{ return Build(false); };
7735
7736 if (RequireCompleteDeclContext(SS, LookupContext))
7737 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007738
Richard Smith23d55872012-04-02 01:30:27 +00007739 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007740 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007741 UsingDecl *UD = BuildValid();
7742 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007743 return UD;
7744 }
7745
7746 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007747
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007748 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007749
John McCall3969e302009-12-08 07:46:18 +00007750 // Unlike most lookups, we don't always want to hide tag
7751 // declarations: tag names are visible through the using declaration
7752 // even if hidden by ordinary names, *except* in a dependent context
7753 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007754 if (!IsInstantiation)
7755 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007756
John McCall5dadb652012-04-07 03:04:20 +00007757 // For the purposes of this lookup, we have a base object type
7758 // equal to that of the current context.
7759 if (CurContext->isRecord()) {
7760 R.setBaseObjectType(
7761 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7762 }
7763
John McCall27b18f82009-11-17 02:14:36 +00007764 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007765
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007766 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007767 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007768 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007769 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007770 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007771 R.getLookupKind(), S, &SS, CCC,
7772 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007773 // We reject any correction for which ND would be NULL.
7774 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007775
Richard Smithf9b15102013-08-17 00:46:16 +00007776 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007777 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007778 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7779 << NameInfo.getName() << LookupContext << 0
7780 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007781
7782 // If we corrected to an inheriting constructor, handle it as one.
7783 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7784 if (RD && RD->isInjectedClassName()) {
7785 // Fix up the information we'll use to build the using declaration.
7786 if (Corrected.WillReplaceSpecifier()) {
7787 NestedNameSpecifierLocBuilder Builder;
7788 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7789 QualifierLoc.getSourceRange());
7790 QualifierLoc = Builder.getWithLocInContext(Context);
7791 }
7792
7793 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7794 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007795 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007796
7797 // Build it and process it as an inheriting constructor.
7798 UsingDecl *UD = BuildValid();
7799 CheckInheritingConstructorUsingDecl(UD);
7800 return UD;
7801 }
7802
7803 // FIXME: Pick up all the declarations if we found an overloaded function.
7804 R.setLookupName(Corrected.getCorrection());
7805 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007806 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007807 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007808 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007809 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007810 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007811 }
7812
Richard Smith09d5b3a2014-05-01 00:35:04 +00007813 if (R.isAmbiguous())
7814 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007815
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007816 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007817 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007818 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007819 Diag(IdentLoc, diag::err_using_typename_non_type);
7820 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7821 Diag((*I)->getUnderlyingDecl()->getLocation(),
7822 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007823 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007824 }
7825 } else {
7826 // If we asked for a non-typename and we got a type, error out,
7827 // but only if this is an instantiation of an unresolved using
7828 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007829 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007830 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7831 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007832 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007833 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007834 }
7835
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007836 // C++0x N2914 [namespace.udecl]p6:
7837 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007838 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007839 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7840 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007841 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007842 }
Mike Stump11289f42009-09-09 15:08:12 +00007843
Richard Smith09d5b3a2014-05-01 00:35:04 +00007844 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007845 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007846 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007847 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7848 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007849 }
John McCall3f746822009-11-17 05:59:44 +00007850
7851 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007852}
7853
Sebastian Redl08905022011-02-05 19:23:19 +00007854/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007855bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007856 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007857
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007858 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007859 assert(SourceType &&
7860 "Using decl naming constructor doesn't have type in scope spec.");
7861 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7862
7863 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007864 bool AnyDependentBases = false;
7865 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7866 AnyDependentBases);
7867 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007868 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007869 diag::err_using_decl_constructor_not_in_direct_base)
7870 << UD->getNameInfo().getSourceRange()
7871 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007872 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007873 return true;
7874 }
7875
Richard Smith09d5b3a2014-05-01 00:35:04 +00007876 if (Base)
7877 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007878
7879 return false;
7880}
7881
John McCall84d87672009-12-10 09:41:52 +00007882/// Checks that the given using declaration is not an invalid
7883/// redeclaration. Note that this is checking only for the using decl
7884/// itself, not for any ill-formedness among the UsingShadowDecls.
7885bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007886 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007887 const CXXScopeSpec &SS,
7888 SourceLocation NameLoc,
7889 const LookupResult &Prev) {
7890 // C++03 [namespace.udecl]p8:
7891 // C++0x [namespace.udecl]p10:
7892 // A using-declaration is a declaration and can therefore be used
7893 // repeatedly where (and only where) multiple declarations are
7894 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007895 //
John McCall032092f2010-11-29 18:01:58 +00007896 // That's in non-member contexts.
7897 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007898 return false;
7899
Aaron Ballman4a979672014-01-03 13:56:08 +00007900 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007901
7902 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7903 NamedDecl *D = *I;
7904
7905 bool DTypename;
7906 NestedNameSpecifier *DQual;
7907 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007908 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007909 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007910 } else if (UnresolvedUsingValueDecl *UD
7911 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7912 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007913 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007914 } else if (UnresolvedUsingTypenameDecl *UD
7915 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7916 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007917 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007918 } else continue;
7919
7920 // using decls differ if one says 'typename' and the other doesn't.
7921 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007922 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007923
7924 // using decls differ if they name different scopes (but note that
7925 // template instantiation can cause this check to trigger when it
7926 // didn't before instantiation).
7927 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7928 Context.getCanonicalNestedNameSpecifier(DQual))
7929 continue;
7930
7931 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007932 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007933 return true;
7934 }
7935
7936 return false;
7937}
7938
John McCall3969e302009-12-08 07:46:18 +00007939
John McCallb96ec562009-12-04 22:46:56 +00007940/// Checks that the given nested-name qualifier used in a using decl
7941/// in the current context is appropriately related to the current
7942/// scope. If an error is found, diagnoses it and returns true.
7943bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7944 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007945 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007946 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007947 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007948
John McCall3969e302009-12-08 07:46:18 +00007949 if (!CurContext->isRecord()) {
7950 // C++03 [namespace.udecl]p3:
7951 // C++0x [namespace.udecl]p8:
7952 // A using-declaration for a class member shall be a member-declaration.
7953
7954 // If we weren't able to compute a valid scope, it must be a
7955 // dependent class scope.
7956 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007957 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7958 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007959 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007960
John McCall3969e302009-12-08 07:46:18 +00007961 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7962 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007963
7964 // If we have a complete, non-dependent source type, try to suggest a
7965 // way to get the same effect.
7966 if (!RD)
7967 return true;
7968
7969 // Find what this using-declaration was referring to.
7970 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7971 R.setHideTags(false);
7972 R.suppressDiagnostics();
7973 LookupQualifiedName(R, RD);
7974
7975 if (R.getAsSingle<TypeDecl>()) {
7976 if (getLangOpts().CPlusPlus11) {
7977 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7978 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7979 << 0 // alias declaration
7980 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7981 NameInfo.getName().getAsString() +
7982 " = ");
7983 } else {
7984 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7985 SourceLocation InsertLoc =
7986 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7987 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7988 << 1 // typedef declaration
7989 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7990 << FixItHint::CreateInsertion(
7991 InsertLoc, " " + NameInfo.getName().getAsString());
7992 }
7993 } else if (R.getAsSingle<VarDecl>()) {
7994 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7995 // repeating the type of the static data member here.
7996 FixItHint FixIt;
7997 if (getLangOpts().CPlusPlus11) {
7998 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7999 FixIt = FixItHint::CreateReplacement(
8000 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8001 }
8002
8003 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8004 << 2 // reference declaration
8005 << FixIt;
8006 }
John McCall3969e302009-12-08 07:46:18 +00008007 return true;
8008 }
8009
8010 // Otherwise, everything is known to be fine.
8011 return false;
8012 }
8013
8014 // The current scope is a record.
8015
8016 // If the named context is dependent, we can't decide much.
8017 if (!NamedContext) {
8018 // FIXME: in C++0x, we can diagnose if we can prove that the
8019 // nested-name-specifier does not refer to a base class, which is
8020 // still possible in some cases.
8021
8022 // Otherwise we have to conservatively report that things might be
8023 // okay.
8024 return false;
8025 }
8026
8027 if (!NamedContext->isRecord()) {
8028 // Ideally this would point at the last name in the specifier,
8029 // but we don't have that level of source info.
8030 Diag(SS.getRange().getBegin(),
8031 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008032 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008033 return true;
8034 }
8035
Douglas Gregor7c842292010-12-21 07:41:49 +00008036 if (!NamedContext->isDependentContext() &&
8037 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8038 return true;
8039
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008040 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008041 // C++0x [namespace.udecl]p3:
8042 // In a using-declaration used as a member-declaration, the
8043 // nested-name-specifier shall name a base class of the class
8044 // being defined.
8045
8046 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8047 cast<CXXRecordDecl>(NamedContext))) {
8048 if (CurContext == NamedContext) {
8049 Diag(NameLoc,
8050 diag::err_using_decl_nested_name_specifier_is_current_class)
8051 << SS.getRange();
8052 return true;
8053 }
8054
8055 Diag(SS.getRange().getBegin(),
8056 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008057 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008058 << cast<CXXRecordDecl>(CurContext)
8059 << SS.getRange();
8060 return true;
8061 }
8062
8063 return false;
8064 }
8065
8066 // C++03 [namespace.udecl]p4:
8067 // A using-declaration used as a member-declaration shall refer
8068 // to a member of a base class of the class being defined [etc.].
8069
8070 // Salient point: SS doesn't have to name a base class as long as
8071 // lookup only finds members from base classes. Therefore we can
8072 // diagnose here only if we can prove that that can't happen,
8073 // i.e. if the class hierarchies provably don't intersect.
8074
8075 // TODO: it would be nice if "definitely valid" results were cached
8076 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8077 // need to be repeated.
8078
8079 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008080 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008081
8082 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8083 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8084 Data->Bases.insert(Base);
8085 return true;
8086 }
8087
8088 bool hasDependentBases(const CXXRecordDecl *Class) {
8089 return !Class->forallBases(collect, this);
8090 }
8091
8092 /// Returns true if the base is dependent or is one of the
8093 /// accumulated base classes.
8094 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8095 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8096 return !Data->Bases.count(Base);
8097 }
8098
8099 bool mightShareBases(const CXXRecordDecl *Class) {
8100 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8101 }
8102 };
8103
8104 UserData Data;
8105
8106 // Returns false if we find a dependent base.
8107 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8108 return false;
8109
8110 // Returns false if the class has a dependent base or if it or one
8111 // of its bases is present in the base set of the current context.
8112 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8113 return false;
8114
8115 Diag(SS.getRange().getBegin(),
8116 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008117 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008118 << cast<CXXRecordDecl>(CurContext)
8119 << SS.getRange();
8120
8121 return true;
John McCallb96ec562009-12-04 22:46:56 +00008122}
8123
Richard Smithdda56e42011-04-15 14:24:37 +00008124Decl *Sema::ActOnAliasDeclaration(Scope *S,
8125 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008126 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008127 SourceLocation UsingLoc,
8128 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008129 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008130 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008131 // Skip up to the relevant declaration scope.
8132 while (S->getFlags() & Scope::TemplateParamScope)
8133 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008134 assert((S->getFlags() & Scope::DeclScope) &&
8135 "got alias-declaration outside of declaration scope");
8136
8137 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008138 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008139
8140 bool Invalid = false;
8141 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008142 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008143 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008144
8145 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008146 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008147
8148 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008149 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008150 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008151 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8152 TInfo->getTypeLoc().getBeginLoc());
8153 }
Richard Smithdda56e42011-04-15 14:24:37 +00008154
8155 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8156 LookupName(Previous, S);
8157
8158 // Warn about shadowing the name of a template parameter.
8159 if (Previous.isSingleResult() &&
8160 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008161 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008162 Previous.clear();
8163 }
8164
8165 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8166 "name in alias declaration must be an identifier");
8167 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8168 Name.StartLocation,
8169 Name.Identifier, TInfo);
8170
8171 NewTD->setAccess(AS);
8172
8173 if (Invalid)
8174 NewTD->setInvalidDecl();
8175
Richard Smith54ecd982013-02-20 19:22:51 +00008176 ProcessDeclAttributeList(S, NewTD, AttrList);
8177
Richard Smith3f1b5d02011-05-05 21:57:07 +00008178 CheckTypedefForVariablyModifiedType(S, NewTD);
8179 Invalid |= NewTD->isInvalidDecl();
8180
Richard Smithdda56e42011-04-15 14:24:37 +00008181 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008182
8183 NamedDecl *NewND;
8184 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008185 TypeAliasTemplateDecl *OldDecl = nullptr;
8186 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008187
8188 if (TemplateParamLists.size() != 1) {
8189 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008190 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8191 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008192 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008193 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008194
8195 // Only consider previous declarations in the same scope.
8196 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8197 /*ExplicitInstantiationOrSpecialization*/false);
8198 if (!Previous.empty()) {
8199 Redeclaration = true;
8200
8201 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8202 if (!OldDecl && !Invalid) {
8203 Diag(UsingLoc, diag::err_redefinition_different_kind)
8204 << Name.Identifier;
8205
8206 NamedDecl *OldD = Previous.getRepresentativeDecl();
8207 if (OldD->getLocation().isValid())
8208 Diag(OldD->getLocation(), diag::note_previous_definition);
8209
8210 Invalid = true;
8211 }
8212
8213 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8214 if (TemplateParameterListsAreEqual(TemplateParams,
8215 OldDecl->getTemplateParameters(),
8216 /*Complain=*/true,
8217 TPL_TemplateMatch))
8218 OldTemplateParams = OldDecl->getTemplateParameters();
8219 else
8220 Invalid = true;
8221
8222 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8223 if (!Invalid &&
8224 !Context.hasSameType(OldTD->getUnderlyingType(),
8225 NewTD->getUnderlyingType())) {
8226 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8227 // but we can't reasonably accept it.
8228 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8229 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8230 if (OldTD->getLocation().isValid())
8231 Diag(OldTD->getLocation(), diag::note_previous_definition);
8232 Invalid = true;
8233 }
8234 }
8235 }
8236
8237 // Merge any previous default template arguments into our parameters,
8238 // and check the parameter list.
8239 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8240 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008241 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008242
8243 TypeAliasTemplateDecl *NewDecl =
8244 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8245 Name.Identifier, TemplateParams,
8246 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008247 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008248
8249 NewDecl->setAccess(AS);
8250
8251 if (Invalid)
8252 NewDecl->setInvalidDecl();
8253 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008254 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008255
8256 NewND = NewDecl;
8257 } else {
8258 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8259 NewND = NewTD;
8260 }
Richard Smithdda56e42011-04-15 14:24:37 +00008261
8262 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008263 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008264
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008265 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008266 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008267}
8268
Richard Smithf4634362014-09-03 23:11:22 +00008269Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8270 SourceLocation AliasLoc,
8271 IdentifierInfo *Alias, CXXScopeSpec &SS,
8272 SourceLocation IdentLoc,
8273 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008274
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008275 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008276 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8277 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008278
John McCall27b18f82009-11-17 02:14:36 +00008279 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008280 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008281
John McCall9f3059a2009-10-09 21:13:30 +00008282 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008283 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008284 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008285 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008286 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008287 }
Richard Smithf4634362014-09-03 23:11:22 +00008288 assert(!R.isAmbiguous() && !R.empty());
8289
8290 // Check if we have a previous declaration with the same name.
8291 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8292 ForRedeclaration);
8293 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8294 PrevDecl = nullptr;
8295
8296 if (PrevDecl) {
8297 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8298 // We already have an alias with the same name that points to the same
8299 // namespace; check that it matches.
8300 if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) {
8301 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8302 << Alias;
8303 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8304 << AD->getNamespace();
8305 return nullptr;
8306 }
8307 } else {
8308 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8309 ? diag::err_redefinition
8310 : diag::err_redefinition_different_kind;
8311 Diag(AliasLoc, DiagID) << Alias;
8312 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8313 return nullptr;
8314 }
8315 }
Mike Stump11289f42009-09-09 15:08:12 +00008316
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008317 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008318 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008319 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008320 IdentLoc, R.getFoundDecl());
Richard Smithf4634362014-09-03 23:11:22 +00008321 if (PrevDecl)
8322 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008323
John McCalld8d0d432010-02-16 06:53:13 +00008324 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008325 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008326}
8327
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008328Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008329Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8330 CXXMethodDecl *MD) {
8331 CXXRecordDecl *ClassDecl = MD->getParent();
8332
Douglas Gregor6d880b12010-07-01 22:31:05 +00008333 // C++ [except.spec]p14:
8334 // An implicitly declared special member function (Clause 12) shall have an
8335 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008336 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008337 if (ClassDecl->isInvalidDecl())
8338 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008339
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008340 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008341 for (const auto &B : ClassDecl->bases()) {
8342 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008343 continue;
8344
Aaron Ballman574705e2014-03-13 15:41:46 +00008345 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008346 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008347 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8348 // If this is a deleted function, add it anyway. This might be conformant
8349 // with the standard. This might not. I'm not sure. It might not matter.
8350 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008351 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008352 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008353 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008354
8355 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008356 for (const auto &B : ClassDecl->vbases()) {
8357 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008358 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008359 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8360 // If this is a deleted function, add it anyway. This might be conformant
8361 // with the standard. This might not. I'm not sure. It might not matter.
8362 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008363 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008364 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008365 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008366
8367 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008368 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008369 if (F->hasInClassInitializer()) {
8370 if (Expr *E = F->getInClassInitializer())
8371 ExceptSpec.CalledExpr(E);
8372 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008373 // DR1351:
8374 // If the brace-or-equal-initializer of a non-static data member
8375 // invokes a defaulted default constructor of its class or of an
8376 // enclosing class in a potentially evaluated subexpression, the
8377 // program is ill-formed.
8378 //
8379 // This resolution is unworkable: the exception specification of the
8380 // default constructor can be needed in an unevaluated context, in
8381 // particular, in the operand of a noexcept-expression, and we can be
8382 // unable to compute an exception specification for an enclosed class.
8383 //
8384 // We do not allow an in-class initializer to require the evaluation
8385 // of the exception specification for any in-class initializer whose
8386 // definition is not lexically complete.
8387 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008388 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008389 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008390 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8391 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8392 // If this is a deleted function, add it anyway. This might be conformant
8393 // with the standard. This might not. I'm not sure. It might not matter.
8394 // In particular, the problem is that this function never gets called. It
8395 // might just be ill-formed because this function attempts to refer to
8396 // a deleted function here.
8397 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008398 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008399 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008400 }
John McCalldb40c7f2010-12-14 08:05:40 +00008401
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008402 return ExceptSpec;
8403}
8404
Richard Smithc2bc61b2013-03-18 21:12:30 +00008405Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008406Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8407 CXXRecordDecl *ClassDecl = CD->getParent();
8408
8409 // C++ [except.spec]p14:
8410 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008411 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008412 if (ClassDecl->isInvalidDecl())
8413 return ExceptSpec;
8414
8415 // Inherited constructor.
8416 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8417 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8418 // FIXME: Copying or moving the parameters could add extra exceptions to the
8419 // set, as could the default arguments for the inherited constructor. This
8420 // will be addressed when we implement the resolution of core issue 1351.
8421 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8422
8423 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008424 for (const auto &B : ClassDecl->bases()) {
8425 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008426 continue;
8427
Aaron Ballman574705e2014-03-13 15:41:46 +00008428 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008429 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8430 if (BaseClassDecl == InheritedDecl)
8431 continue;
8432 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8433 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008434 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008435 }
8436 }
8437
8438 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008439 for (const auto &B : ClassDecl->vbases()) {
8440 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008441 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8442 if (BaseClassDecl == InheritedDecl)
8443 continue;
8444 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8445 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008446 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008447 }
8448 }
8449
8450 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008451 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008452 if (F->hasInClassInitializer()) {
8453 if (Expr *E = F->getInClassInitializer())
8454 ExceptSpec.CalledExpr(E);
8455 else if (!F->isInvalidDecl())
8456 Diag(CD->getLocation(),
8457 diag::err_in_class_initializer_references_def_ctor) << CD;
8458 } else if (const RecordType *RecordTy
8459 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8460 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8461 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8462 if (Constructor)
8463 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8464 }
8465 }
8466
Richard Smithc2bc61b2013-03-18 21:12:30 +00008467 return ExceptSpec;
8468}
8469
Richard Smith8bf22e52012-11-29 01:34:07 +00008470namespace {
8471/// RAII object to register a special member as being currently declared.
8472struct DeclaringSpecialMember {
8473 Sema &S;
8474 Sema::SpecialMemberDecl D;
8475 bool WasAlreadyBeingDeclared;
8476
8477 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8478 : S(S), D(RD, CSM) {
8479 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8480 if (WasAlreadyBeingDeclared)
8481 // This almost never happens, but if it does, ensure that our cache
8482 // doesn't contain a stale result.
8483 S.SpecialMemberCache.clear();
8484
8485 // FIXME: Register a note to be produced if we encounter an error while
8486 // declaring the special member.
8487 }
8488 ~DeclaringSpecialMember() {
8489 if (!WasAlreadyBeingDeclared)
8490 S.SpecialMembersBeingDeclared.erase(D);
8491 }
8492
8493 /// \brief Are we already trying to declare this special member?
8494 bool isAlreadyBeingDeclared() const {
8495 return WasAlreadyBeingDeclared;
8496 }
8497};
8498}
8499
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008500CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8501 CXXRecordDecl *ClassDecl) {
8502 // C++ [class.ctor]p5:
8503 // A default constructor for a class X is a constructor of class X
8504 // that can be called without an argument. If there is no
8505 // user-declared constructor for class X, a default constructor is
8506 // implicitly declared. An implicitly-declared default constructor
8507 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008508 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008509 "Should not build implicit default constructor!");
8510
Richard Smith8bf22e52012-11-29 01:34:07 +00008511 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8512 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008513 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008514
Richard Smithb5800092012-06-10 05:43:50 +00008515 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8516 CXXDefaultConstructor,
8517 false);
8518
Douglas Gregor6d880b12010-07-01 22:31:05 +00008519 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008520 CanQualType ClassType
8521 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008522 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008523 DeclarationName Name
8524 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008525 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008526 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008527 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8528 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8529 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008530 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008531 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008532 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008533
8534 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008535 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008536 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008537
Richard Smith6b02d462012-12-08 08:32:28 +00008538 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8539 // constructors is easy to compute.
8540 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8541
8542 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008543 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008544
Douglas Gregor9672f922010-07-03 00:47:00 +00008545 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008546 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008547
Douglas Gregor0be31a22010-07-02 17:43:08 +00008548 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008549 PushOnScopeChains(DefaultCon, S, false);
8550 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008551
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008552 return DefaultCon;
8553}
8554
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008555void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8556 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008557 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008558 !Constructor->doesThisDeclarationHaveABody() &&
8559 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008560 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008561
Anders Carlsson423f5d82010-04-23 16:04:08 +00008562 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008563 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008564
Eli Friedmaneaf34142012-10-18 20:14:08 +00008565 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008566 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008567 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008568 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008569 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008570 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008571 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008572 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008573 }
Douglas Gregor73193272010-09-20 16:48:21 +00008574
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008575 SourceLocation Loc = Constructor->getLocEnd().isValid()
8576 ? Constructor->getLocEnd()
8577 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008578 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008579
Eli Friedman276dd182013-09-05 00:02:25 +00008580 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008581 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008582
8583 if (ASTMutationListener *L = getASTMutationListener()) {
8584 L->CompletedImplicitDefinition(Constructor);
8585 }
Richard Trieuef64e942013-10-25 00:56:00 +00008586
8587 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008588}
8589
Richard Smith938f40b2011-06-11 17:19:42 +00008590void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008591 // Perform any delayed checks on exception specifications.
8592 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008593}
8594
Richard Smith185be182013-04-10 05:48:59 +00008595namespace {
8596/// Information on inheriting constructors to declare.
8597class InheritingConstructorInfo {
8598public:
8599 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8600 : SemaRef(SemaRef), Derived(Derived) {
8601 // Mark the constructors that we already have in the derived class.
8602 //
8603 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8604 // unless there is a user-declared constructor with the same signature in
8605 // the class where the using-declaration appears.
8606 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8607 }
8608
8609 void inheritAll(CXXRecordDecl *RD) {
8610 visitAll(RD, &InheritingConstructorInfo::inherit);
8611 }
8612
8613private:
8614 /// Information about an inheriting constructor.
8615 struct InheritingConstructor {
8616 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008617 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008618
8619 /// If \c true, a constructor with this signature is already declared
8620 /// in the derived class.
8621 bool DeclaredInDerived;
8622
8623 /// The constructor which is inherited.
8624 const CXXConstructorDecl *BaseCtor;
8625
8626 /// The derived constructor we declared.
8627 CXXConstructorDecl *DerivedCtor;
8628 };
8629
8630 /// Inheriting constructors with a given canonical type. There can be at
8631 /// most one such non-template constructor, and any number of templated
8632 /// constructors.
8633 struct InheritingConstructorsForType {
8634 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008635 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8636 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008637
8638 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8639 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8640 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8641 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8642 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8643 false, S.TPL_TemplateMatch))
8644 return Templates[I].second;
8645 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8646 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008647 }
Richard Smith185be182013-04-10 05:48:59 +00008648
8649 return NonTemplate;
8650 }
8651 };
8652
8653 /// Get or create the inheriting constructor record for a constructor.
8654 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8655 QualType CtorType) {
8656 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8657 .getEntry(SemaRef, Ctor);
8658 }
8659
8660 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8661
8662 /// Process all constructors for a class.
8663 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008664 for (const auto *Ctor : RD->ctors())
8665 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008666 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8667 I(RD->decls_begin()), E(RD->decls_end());
8668 I != E; ++I) {
8669 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8670 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8671 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008672 }
8673 }
Richard Smith185be182013-04-10 05:48:59 +00008674
8675 /// Note that a constructor (or constructor template) was declared in Derived.
8676 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8677 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8678 }
8679
8680 /// Inherit a single constructor.
8681 void inherit(const CXXConstructorDecl *Ctor) {
8682 const FunctionProtoType *CtorType =
8683 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00008684 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00008685 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8686
8687 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8688
8689 // Core issue (no number yet): the ellipsis is always discarded.
8690 if (EPI.Variadic) {
8691 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8692 SemaRef.Diag(Ctor->getLocation(),
8693 diag::note_using_decl_constructor_ellipsis);
8694 EPI.Variadic = false;
8695 }
8696
8697 // Declare a constructor for each number of parameters.
8698 //
8699 // C++11 [class.inhctor]p1:
8700 // The candidate set of inherited constructors from the class X named in
8701 // the using-declaration consists of [... modulo defects ...] for each
8702 // constructor or constructor template of X, the set of constructors or
8703 // constructor templates that results from omitting any ellipsis parameter
8704 // specification and successively omitting parameters with a default
8705 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008706 unsigned MinParams = minParamsToInherit(Ctor);
8707 unsigned Params = Ctor->getNumParams();
8708 if (Params >= MinParams) {
8709 do
8710 declareCtor(UsingLoc, Ctor,
8711 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008712 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008713 while (Params > MinParams &&
8714 Ctor->getParamDecl(--Params)->hasDefaultArg());
8715 }
Richard Smith185be182013-04-10 05:48:59 +00008716 }
8717
8718 /// Find the using-declaration which specified that we should inherit the
8719 /// constructors of \p Base.
8720 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8721 // No fancy lookup required; just look for the base constructor name
8722 // directly within the derived class.
8723 ASTContext &Context = SemaRef.Context;
8724 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8725 Context.getCanonicalType(Context.getRecordType(Base)));
8726 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8727 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8728 }
8729
8730 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8731 // C++11 [class.inhctor]p3:
8732 // [F]or each constructor template in the candidate set of inherited
8733 // constructors, a constructor template is implicitly declared
8734 if (Ctor->getDescribedFunctionTemplate())
8735 return 0;
8736
8737 // For each non-template constructor in the candidate set of inherited
8738 // constructors other than a constructor having no parameters or a
8739 // copy/move constructor having a single parameter, a constructor is
8740 // implicitly declared [...]
8741 if (Ctor->getNumParams() == 0)
8742 return 1;
8743 if (Ctor->isCopyOrMoveConstructor())
8744 return 2;
8745
8746 // Per discussion on core reflector, never inherit a constructor which
8747 // would become a default, copy, or move constructor of Derived either.
8748 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8749 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8750 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8751 }
8752
8753 /// Declare a single inheriting constructor, inheriting the specified
8754 /// constructor, with the given type.
8755 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8756 QualType DerivedType) {
8757 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8758
8759 // C++11 [class.inhctor]p3:
8760 // ... a constructor is implicitly declared with the same constructor
8761 // characteristics unless there is a user-declared constructor with
8762 // the same signature in the class where the using-declaration appears
8763 if (Entry.DeclaredInDerived)
8764 return;
8765
8766 // C++11 [class.inhctor]p7:
8767 // If two using-declarations declare inheriting constructors with the
8768 // same signature, the program is ill-formed
8769 if (Entry.DerivedCtor) {
8770 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8771 // Only diagnose this once per constructor.
8772 if (Entry.DerivedCtor->isInvalidDecl())
8773 return;
8774 Entry.DerivedCtor->setInvalidDecl();
8775
8776 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8777 SemaRef.Diag(BaseCtor->getLocation(),
8778 diag::note_using_decl_constructor_conflict_current_ctor);
8779 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8780 diag::note_using_decl_constructor_conflict_previous_ctor);
8781 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8782 diag::note_using_decl_constructor_conflict_previous_using);
8783 } else {
8784 // Core issue (no number): if the same inheriting constructor is
8785 // produced by multiple base class constructors from the same base
8786 // class, the inheriting constructor is defined as deleted.
8787 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8788 }
8789
8790 return;
8791 }
8792
8793 ASTContext &Context = SemaRef.Context;
8794 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8795 Context.getCanonicalType(Context.getRecordType(Derived)));
8796 DeclarationNameInfo NameInfo(Name, UsingLoc);
8797
Craig Topperc3ec1492014-05-26 06:22:03 +00008798 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008799 if (const FunctionTemplateDecl *FTD =
8800 BaseCtor->getDescribedFunctionTemplate()) {
8801 TemplateParams = FTD->getTemplateParameters();
8802 // We're reusing template parameters from a different DeclContext. This
8803 // is questionable at best, but works out because the template depth in
8804 // both places is guaranteed to be 0.
8805 // FIXME: Rebuild the template parameters in the new context, and
8806 // transform the function type to refer to them.
8807 }
8808
8809 // Build type source info pointing at the using-declaration. This is
8810 // required by template instantiation.
8811 TypeSourceInfo *TInfo =
8812 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8813 FunctionProtoTypeLoc ProtoLoc =
8814 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8815
8816 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8817 Context, Derived, UsingLoc, NameInfo, DerivedType,
8818 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8819 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8820
8821 // Build an unevaluated exception specification for this constructor.
8822 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8823 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00008824 EPI.ExceptionSpec.Type = EST_Unevaluated;
8825 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008826 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008827 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008828
8829 // Build the parameter declarations.
8830 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008831 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008832 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008833 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008834 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008835 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8836 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008837 PD->setScopeInfo(0, I);
8838 PD->setImplicit();
8839 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008840 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008841 }
8842
8843 // Set up the new constructor.
8844 DerivedCtor->setAccess(BaseCtor->getAccess());
8845 DerivedCtor->setParams(ParamDecls);
8846 DerivedCtor->setInheritedConstructor(BaseCtor);
8847 if (BaseCtor->isDeleted())
8848 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8849
8850 // If this is a constructor template, build the template declaration.
8851 if (TemplateParams) {
8852 FunctionTemplateDecl *DerivedTemplate =
8853 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8854 TemplateParams, DerivedCtor);
8855 DerivedTemplate->setAccess(BaseCtor->getAccess());
8856 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8857 Derived->addDecl(DerivedTemplate);
8858 } else {
8859 Derived->addDecl(DerivedCtor);
8860 }
8861
8862 Entry.BaseCtor = BaseCtor;
8863 Entry.DerivedCtor = DerivedCtor;
8864 }
8865
8866 Sema &SemaRef;
8867 CXXRecordDecl *Derived;
8868 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8869 MapType Map;
8870};
8871}
8872
8873void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8874 // Defer declaring the inheriting constructors until the class is
8875 // instantiated.
8876 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008877 return;
8878
Richard Smith185be182013-04-10 05:48:59 +00008879 // Find base classes from which we might inherit constructors.
8880 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008881 for (const auto &BaseIt : ClassDecl->bases())
8882 if (BaseIt.getInheritConstructors())
8883 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008884
Richard Smith185be182013-04-10 05:48:59 +00008885 // Go no further if we're not inheriting any constructors.
8886 if (InheritedBases.empty())
8887 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008888
Richard Smith185be182013-04-10 05:48:59 +00008889 // Declare the inherited constructors.
8890 InheritingConstructorInfo ICI(*this, ClassDecl);
8891 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8892 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008893}
8894
Richard Smithc2bc61b2013-03-18 21:12:30 +00008895void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8896 CXXConstructorDecl *Constructor) {
8897 CXXRecordDecl *ClassDecl = Constructor->getParent();
8898 assert(Constructor->getInheritedConstructor() &&
8899 !Constructor->doesThisDeclarationHaveABody() &&
8900 !Constructor->isDeleted());
8901
8902 SynthesizedFunctionScope Scope(*this, Constructor);
8903 DiagnosticErrorTrap Trap(Diags);
8904 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8905 Trap.hasErrorOccurred()) {
8906 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8907 << Context.getTagDeclType(ClassDecl);
8908 Constructor->setInvalidDecl();
8909 return;
8910 }
8911
8912 SourceLocation Loc = Constructor->getLocation();
8913 Constructor->setBody(new (Context) CompoundStmt(Loc));
8914
Eli Friedman276dd182013-09-05 00:02:25 +00008915 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008916 MarkVTableUsed(CurrentLocation, ClassDecl);
8917
8918 if (ASTMutationListener *L = getASTMutationListener()) {
8919 L->CompletedImplicitDefinition(Constructor);
8920 }
8921}
8922
8923
Alexis Huntf91729462011-05-12 22:46:25 +00008924Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008925Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8926 CXXRecordDecl *ClassDecl = MD->getParent();
8927
Douglas Gregorf1203042010-07-01 19:09:28 +00008928 // C++ [except.spec]p14:
8929 // An implicitly declared special member function (Clause 12) shall have
8930 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008931 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008932 if (ClassDecl->isInvalidDecl())
8933 return ExceptSpec;
8934
Douglas Gregorf1203042010-07-01 19:09:28 +00008935 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008936 for (const auto &B : ClassDecl->bases()) {
8937 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008938 continue;
8939
Aaron Ballman574705e2014-03-13 15:41:46 +00008940 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8941 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008942 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008943 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008944
Douglas Gregorf1203042010-07-01 19:09:28 +00008945 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008946 for (const auto &B : ClassDecl->vbases()) {
8947 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8948 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008949 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008950 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008951
Douglas Gregorf1203042010-07-01 19:09:28 +00008952 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008953 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008954 if (const RecordType *RecordTy
8955 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008956 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008957 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008958 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008959
Alexis Huntf91729462011-05-12 22:46:25 +00008960 return ExceptSpec;
8961}
8962
8963CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8964 // C++ [class.dtor]p2:
8965 // If a class has no user-declared destructor, a destructor is
8966 // declared implicitly. An implicitly-declared destructor is an
8967 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008968 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008969
Richard Smith8bf22e52012-11-29 01:34:07 +00008970 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8971 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008972 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008973
Douglas Gregor7454c562010-07-02 20:37:36 +00008974 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008975 CanQualType ClassType
8976 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008977 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008978 DeclarationName Name
8979 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008980 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008981 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008982 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008983 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008984 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008985 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008986 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008987 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008988
8989 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008990 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008991 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008992
Richard Smith6b02d462012-12-08 08:32:28 +00008993 AddOverriddenMethods(ClassDecl, Destructor);
8994
8995 // We don't need to use SpecialMemberIsTrivial here; triviality for
8996 // destructors is easy to compute.
8997 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8998
8999 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009000 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009001
Douglas Gregor7454c562010-07-02 20:37:36 +00009002 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009003 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009004
Douglas Gregor7454c562010-07-02 20:37:36 +00009005 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009006 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009007 PushOnScopeChains(Destructor, S, false);
9008 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009009
Douglas Gregorf1203042010-07-01 19:09:28 +00009010 return Destructor;
9011}
9012
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009013void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009014 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009015 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009016 !Destructor->doesThisDeclarationHaveABody() &&
9017 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009018 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009019 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009020 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009021
Douglas Gregor54818f02010-05-12 16:39:35 +00009022 if (Destructor->isInvalidDecl())
9023 return;
9024
Eli Friedmaneaf34142012-10-18 20:14:08 +00009025 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009026
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009027 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009028 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9029 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009030
Douglas Gregor54818f02010-05-12 16:39:35 +00009031 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009032 Diag(CurrentLocation, diag::note_member_synthesized_at)
9033 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9034
9035 Destructor->setInvalidDecl();
9036 return;
9037 }
9038
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009039 SourceLocation Loc = Destructor->getLocEnd().isValid()
9040 ? Destructor->getLocEnd()
9041 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009042 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009043 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009044 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009045
9046 if (ASTMutationListener *L = getASTMutationListener()) {
9047 L->CompletedImplicitDefinition(Destructor);
9048 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009049}
9050
Richard Smith84973e52012-04-21 18:42:51 +00009051/// \brief Perform any semantic analysis which needs to be delayed until all
9052/// pending class member declarations have been parsed.
9053void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009054 // If the context is an invalid C++ class, just suppress these checks.
9055 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9056 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009057 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009058 DelayedDestructorExceptionSpecChecks.clear();
9059 return;
9060 }
9061 }
Richard Smith84973e52012-04-21 18:42:51 +00009062}
9063
Richard Smithd3b5c9082012-07-27 04:22:15 +00009064void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9065 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009066 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009067 "adjusting dtor exception specs was introduced in c++11");
9068
Sebastian Redl623ea822011-05-19 05:13:44 +00009069 // C++11 [class.dtor]p3:
9070 // A declaration of a destructor that does not have an exception-
9071 // specification is implicitly considered to have the same exception-
9072 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009073 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009074 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009075 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009076 return;
9077
Chandler Carruth9a797572011-09-20 04:55:26 +00009078 // Replace the destructor's type, building off the existing one. Fortunately,
9079 // the only thing of interest in the destructor type is its extended info.
9080 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009081 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009082 EPI.ExceptionSpec.Type = EST_Unevaluated;
9083 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009084 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009085
Sebastian Redl623ea822011-05-19 05:13:44 +00009086 // FIXME: If the destructor has a body that could throw, and the newly created
9087 // spec doesn't allow exceptions, we should emit a warning, because this
9088 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009089 // However, we don't have a body or an exception specification yet, so it
9090 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009091}
9092
Pavel Labath58934982013-08-30 08:52:28 +00009093namespace {
9094/// \brief An abstract base class for all helper classes used in building the
9095// copy/move operators. These classes serve as factory functions and help us
9096// avoid using the same Expr* in the AST twice.
9097class ExprBuilder {
9098 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9099 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9100
9101protected:
9102 static Expr *assertNotNull(Expr *E) {
9103 assert(E && "Expression construction must not fail.");
9104 return E;
9105 }
9106
9107public:
9108 ExprBuilder() {}
9109 virtual ~ExprBuilder() {}
9110
9111 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9112};
9113
9114class RefBuilder: public ExprBuilder {
9115 VarDecl *Var;
9116 QualType VarType;
9117
9118public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009119 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009120 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009121 }
9122
9123 RefBuilder(VarDecl *Var, QualType VarType)
9124 : Var(Var), VarType(VarType) {}
9125};
9126
9127class ThisBuilder: public ExprBuilder {
9128public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009129 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009130 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009131 }
9132};
9133
9134class CastBuilder: public ExprBuilder {
9135 const ExprBuilder &Builder;
9136 QualType Type;
9137 ExprValueKind Kind;
9138 const CXXCastPath &Path;
9139
9140public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009141 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009142 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9143 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009144 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009145 }
9146
9147 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9148 const CXXCastPath &Path)
9149 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9150};
9151
9152class DerefBuilder: public ExprBuilder {
9153 const ExprBuilder &Builder;
9154
9155public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009156 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009157 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009158 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009159 }
9160
9161 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9162};
9163
9164class MemberBuilder: public ExprBuilder {
9165 const ExprBuilder &Builder;
9166 QualType Type;
9167 CXXScopeSpec SS;
9168 bool IsArrow;
9169 LookupResult &MemberLookup;
9170
9171public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009172 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009173 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009174 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009175 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009176 }
9177
9178 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9179 LookupResult &MemberLookup)
9180 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9181 MemberLookup(MemberLookup) {}
9182};
9183
9184class MoveCastBuilder: public ExprBuilder {
9185 const ExprBuilder &Builder;
9186
9187public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009188 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009189 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9190 }
9191
9192 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9193};
9194
9195class LvalueConvBuilder: public ExprBuilder {
9196 const ExprBuilder &Builder;
9197
9198public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009199 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009200 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009201 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009202 }
9203
9204 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9205};
9206
9207class SubscriptBuilder: public ExprBuilder {
9208 const ExprBuilder &Base;
9209 const ExprBuilder &Index;
9210
9211public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009212 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009213 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009214 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009215 }
9216
9217 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9218 : Base(Base), Index(Index) {}
9219};
9220
9221} // end anonymous namespace
9222
Richard Smith41ae3282012-11-14 00:50:40 +00009223/// When generating a defaulted copy or move assignment operator, if a field
9224/// should be copied with __builtin_memcpy rather than via explicit assignments,
9225/// do so. This optimization only applies for arrays of scalars, and for arrays
9226/// of class type where the selected copy/move-assignment operator is trivial.
9227static StmtResult
9228buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009229 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009230 // Compute the size of the memory buffer to be copied.
9231 QualType SizeType = S.Context.getSizeType();
9232 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9233 S.Context.getTypeSizeInChars(T).getQuantity());
9234
9235 // Take the address of the field references for "from" and "to". We
9236 // directly construct UnaryOperators here because semantic analysis
9237 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009238 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009239 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9240 S.Context.getPointerType(From->getType()),
9241 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009242 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009243 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9244 S.Context.getPointerType(To->getType()),
9245 VK_RValue, OK_Ordinary, Loc);
9246
9247 const Type *E = T->getBaseElementTypeUnsafe();
9248 bool NeedsCollectableMemCpy =
9249 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9250
9251 // Create a reference to the __builtin_objc_memmove_collectable function
9252 StringRef MemCpyName = NeedsCollectableMemCpy ?
9253 "__builtin_objc_memmove_collectable" :
9254 "__builtin_memcpy";
9255 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9256 Sema::LookupOrdinaryName);
9257 S.LookupName(R, S.TUScope, true);
9258
9259 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9260 if (!MemCpy)
9261 // Something went horribly wrong earlier, and we will have complained
9262 // about it.
9263 return StmtError();
9264
9265 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009266 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009267 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9268
9269 Expr *CallArgs[] = {
9270 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9271 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009272 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009273 Loc, CallArgs, Loc);
9274
9275 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009276 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009277}
9278
Sebastian Redl22653ba2011-08-30 19:58:05 +00009279/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009280/// \c To.
9281///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009282/// This routine is used to copy/move the members of a class with an
9283/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009284/// copied are arrays, this routine builds for loops to copy them.
9285///
9286/// \param S The Sema object used for type-checking.
9287///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009288/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009289///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009290/// \param T The type of the expressions being copied/moved. Both expressions
9291/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009292///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009293/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009294///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009295/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009296///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009297/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009298/// Otherwise, it's a non-static member subobject.
9299///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009300/// \param Copying Whether we're copying or moving.
9301///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009302/// \param Depth Internal parameter recording the depth of the recursion.
9303///
Richard Smith41ae3282012-11-14 00:50:40 +00009304/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9305/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009306static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009307buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009308 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009309 bool CopyingBaseSubobject, bool Copying,
9310 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009311 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009312 // Each subobject is assigned in the manner appropriate to its type:
9313 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009314 // - if the subobject is of class type, as if by a call to operator= with
9315 // the subobject as the object expression and the corresponding
9316 // subobject of x as a single function argument (as if by explicit
9317 // qualification; that is, ignoring any possible virtual overriding
9318 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009319 //
9320 // C++03 [class.copy]p13:
9321 // - if the subobject is of class type, the copy assignment operator for
9322 // the class is used (as if by explicit qualification; that is,
9323 // ignoring any possible virtual overriding functions in more derived
9324 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009325 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9326 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009327
Douglas Gregorb139cd52010-05-01 20:49:11 +00009328 // Look for operator=.
9329 DeclarationName Name
9330 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9331 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9332 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009333
Richard Smith52c0b582012-11-13 00:54:12 +00009334 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9335 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009336 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009337 LookupResult::Filter F = OpLookup.makeFilter();
9338 while (F.hasNext()) {
9339 NamedDecl *D = F.next();
9340 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9341 if (Method->isCopyAssignmentOperator() ||
9342 (!Copying && Method->isMoveAssignmentOperator()))
9343 continue;
9344
9345 F.erase();
9346 }
9347 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009348 }
Richard Smith52c0b582012-11-13 00:54:12 +00009349
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009350 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009351 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009352 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009353 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009354 // ambiguities), we need to cast "this" to that subobject type; to
9355 // ensure that we don't go through the virtual call mechanism, we need
9356 // to qualify the operator= name with the base class (see below). However,
9357 // this means that if the base class has a protected copy assignment
9358 // operator, the protected member access check will fail. So, we
9359 // rewrite "protected" access to "public" access in this case, since we
9360 // know by construction that we're calling from a derived class.
9361 if (CopyingBaseSubobject) {
9362 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9363 L != LEnd; ++L) {
9364 if (L.getAccess() == AS_protected)
9365 L.setAccess(AS_public);
9366 }
9367 }
Richard Smith52c0b582012-11-13 00:54:12 +00009368
Douglas Gregorb139cd52010-05-01 20:49:11 +00009369 // Create the nested-name-specifier that will be used to qualify the
9370 // reference to operator=; this is required to suppress the virtual
9371 // call mechanism.
9372 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009373 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009374 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009375 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009376 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009377 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009378
Douglas Gregorb139cd52010-05-01 20:49:11 +00009379 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009380 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009381 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9382 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009383 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009384 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009385 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009386 /*SuppressQualifierCheck=*/true);
9387 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009388 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009389
Douglas Gregorb139cd52010-05-01 20:49:11 +00009390 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009391
Pavel Labath58934982013-08-30 08:52:28 +00009392 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009393 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009394 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009395 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009396 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009397 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009398
Richard Smith41ae3282012-11-14 00:50:40 +00009399 // If we built a call to a trivial 'operator=' while copying an array,
9400 // bail out. We'll replace the whole shebang with a memcpy.
9401 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9402 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009403 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009404
Richard Smith52c0b582012-11-13 00:54:12 +00009405 // Convert to an expression-statement, and clean up any produced
9406 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009407 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009408 }
John McCallab8c2732010-03-16 06:11:48 +00009409
Richard Smith52c0b582012-11-13 00:54:12 +00009410 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009411 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009412 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009413 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009414 ExprResult Assignment = S.CreateBuiltinBinOp(
9415 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009416 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009417 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009418 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009419 }
Richard Smith52c0b582012-11-13 00:54:12 +00009420
9421 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009422 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009423
Douglas Gregorb139cd52010-05-01 20:49:11 +00009424 // Construct a loop over the array bounds, e.g.,
9425 //
9426 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9427 //
9428 // that will copy each of the array elements.
9429 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009430
Douglas Gregorb139cd52010-05-01 20:49:11 +00009431 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009432 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009433 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009434 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009435 llvm::raw_svector_ostream OS(Str);
9436 OS << "__i" << Depth;
9437 IterationVarName = &S.Context.Idents.get(OS.str());
9438 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009439 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009440 IterationVarName, SizeType,
9441 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009442 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009443
Douglas Gregorb139cd52010-05-01 20:49:11 +00009444 // Initialize the iteration variable to zero.
9445 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009446 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009447
Pavel Labath58934982013-08-30 08:52:28 +00009448 // Creates a reference to the iteration variable.
9449 RefBuilder IterationVarRef(IterationVar, SizeType);
9450 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009451
Douglas Gregorb139cd52010-05-01 20:49:11 +00009452 // Create the DeclStmt that holds the iteration variable.
9453 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009454
Douglas Gregorb139cd52010-05-01 20:49:11 +00009455 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009456 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9457 MoveCastBuilder FromIndexMove(FromIndexCopy);
9458 const ExprBuilder *FromIndex;
9459 if (Copying)
9460 FromIndex = &FromIndexCopy;
9461 else
9462 FromIndex = &FromIndexMove;
9463
9464 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009465
9466 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009467 StmtResult Copy =
9468 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009469 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009470 Copying, Depth + 1);
9471 // Bail out if copying fails or if we determined that we should use memcpy.
9472 if (Copy.isInvalid() || !Copy.get())
9473 return Copy;
9474
9475 // Create the comparison against the array bound.
9476 llvm::APInt Upper
9477 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9478 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009479 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009480 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9481 BO_NE, S.Context.BoolTy,
9482 VK_RValue, OK_Ordinary, Loc, false);
9483
9484 // Create the pre-increment of the iteration variable.
9485 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009486 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9487 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009488
Douglas Gregorb139cd52010-05-01 20:49:11 +00009489 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009490 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009491 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009492 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009493 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009494}
9495
Richard Smith41ae3282012-11-14 00:50:40 +00009496static StmtResult
9497buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009498 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009499 bool CopyingBaseSubobject, bool Copying) {
9500 // Maybe we should use a memcpy?
9501 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9502 T.isTriviallyCopyableType(S.Context))
9503 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9504
9505 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9506 CopyingBaseSubobject,
9507 Copying, 0));
9508
9509 // If we ended up picking a trivial assignment operator for an array of a
9510 // non-trivially-copyable class type, just emit a memcpy.
9511 if (!Result.isInvalid() && !Result.get())
9512 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9513
9514 return Result;
9515}
9516
Richard Smithd3b5c9082012-07-27 04:22:15 +00009517Sema::ImplicitExceptionSpecification
9518Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9519 CXXRecordDecl *ClassDecl = MD->getParent();
9520
9521 ImplicitExceptionSpecification ExceptSpec(*this);
9522 if (ClassDecl->isInvalidDecl())
9523 return ExceptSpec;
9524
9525 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009526 assert(T->getNumParams() == 1 && "not a copy assignment op");
9527 unsigned ArgQuals =
9528 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009529
Douglas Gregor68e11362010-07-01 17:48:08 +00009530 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009531 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009532 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009533
9534 // It is unspecified whether or not an implicit copy assignment operator
9535 // attempts to deduplicate calls to assignment operators of virtual bases are
9536 // made. As such, this exception specification is effectively unspecified.
9537 // Based on a similar decision made for constness in C++0x, we're erring on
9538 // the side of assuming such calls to be made regardless of whether they
9539 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009540 for (const auto &Base : ClassDecl->bases()) {
9541 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009542 continue;
9543
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009544 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009545 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009546 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9547 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009548 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009549 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009550
Aaron Ballman445a9392014-03-13 16:15:17 +00009551 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009552 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009553 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009554 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9555 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009556 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009557 }
9558
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009559 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009560 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009561 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9562 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009563 LookupCopyingAssignment(FieldClassDecl,
9564 ArgQuals | FieldType.getCVRQualifiers(),
9565 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009566 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009567 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009568 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009569
Richard Smithd3b5c9082012-07-27 04:22:15 +00009570 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009571}
9572
9573CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9574 // Note: The following rules are largely analoguous to the copy
9575 // constructor rules. Note that virtual bases are not taken into account
9576 // for determining the argument type of the operator. Note also that
9577 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009578 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009579
Richard Smith8bf22e52012-11-29 01:34:07 +00009580 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9581 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009582 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009583
Alexis Hunt119f3652011-05-14 05:23:20 +00009584 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9585 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009586 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9587 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009588 ArgType = ArgType.withConst();
9589 ArgType = Context.getLValueReferenceType(ArgType);
9590
Richard Smith99005e62013-05-07 03:19:20 +00009591 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9592 CXXCopyAssignment,
9593 Const);
9594
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009595 // An implicitly-declared copy assignment operator is an inline public
9596 // member of its class.
9597 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009598 SourceLocation ClassLoc = ClassDecl->getLocation();
9599 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009600 CXXMethodDecl *CopyAssignment =
9601 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009602 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9603 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009604 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009605 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009606 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009607
9608 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009609 FunctionProtoType::ExtProtoInfo EPI =
9610 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009611 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009612
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009613 // Add the parameter to the operator.
9614 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009615 ClassLoc, ClassLoc,
9616 /*Id=*/nullptr, ArgType,
9617 /*TInfo=*/nullptr, SC_None,
9618 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009619 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009620
Richard Smith6b02d462012-12-08 08:32:28 +00009621 AddOverriddenMethods(ClassDecl, CopyAssignment);
9622
9623 CopyAssignment->setTrivial(
9624 ClassDecl->needsOverloadResolutionForCopyAssignment()
9625 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9626 : ClassDecl->hasTrivialCopyAssignment());
9627
Richard Smith852265f2012-03-30 20:53:28 +00009628 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009629 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009630
Richard Smith6b02d462012-12-08 08:32:28 +00009631 // Note that we have added this copy-assignment operator.
9632 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9633
9634 if (Scope *S = getScopeForContext(ClassDecl))
9635 PushOnScopeChains(CopyAssignment, S, false);
9636 ClassDecl->addDecl(CopyAssignment);
9637
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009638 return CopyAssignment;
9639}
9640
Richard Smithd577fbb2013-06-13 03:23:42 +00009641/// Diagnose an implicit copy operation for a class which is odr-used, but
9642/// which is deprecated because the class has a user-declared copy constructor,
9643/// copy assignment operator, or destructor.
9644static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9645 SourceLocation UseLoc) {
9646 assert(CopyOp->isImplicit());
9647
9648 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009649 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009650
9651 // In Microsoft mode, assignment operations don't affect constructors and
9652 // vice versa.
9653 if (RD->hasUserDeclaredDestructor()) {
9654 UserDeclaredOperation = RD->getDestructor();
9655 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9656 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009657 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009658 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009659 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009660 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009661 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009662 break;
9663 }
9664 }
9665 assert(UserDeclaredOperation);
9666 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9667 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009668 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009669 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009670 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009671 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009672 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009673 break;
9674 }
9675 }
9676 assert(UserDeclaredOperation);
9677 }
9678
9679 if (UserDeclaredOperation) {
9680 S.Diag(UserDeclaredOperation->getLocation(),
9681 diag::warn_deprecated_copy_operation)
9682 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9683 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9684 S.Diag(UseLoc, diag::note_member_synthesized_at)
9685 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9686 : Sema::CXXCopyAssignment)
9687 << RD;
9688 }
9689}
9690
Douglas Gregorb139cd52010-05-01 20:49:11 +00009691void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9692 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009693 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009694 CopyAssignOperator->isOverloadedOperator() &&
9695 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009696 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9697 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009698 "DefineImplicitCopyAssignment called for wrong function");
9699
9700 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9701
9702 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9703 CopyAssignOperator->setInvalidDecl();
9704 return;
9705 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009706
9707 // C++11 [class.copy]p18:
9708 // The [definition of an implicitly declared copy assignment operator] is
9709 // deprecated if the class has a user-declared copy constructor or a
9710 // user-declared destructor.
9711 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9712 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9713
Eli Friedman276dd182013-09-05 00:02:25 +00009714 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009715
Eli Friedmaneaf34142012-10-18 20:14:08 +00009716 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009717 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009718
9719 // C++0x [class.copy]p30:
9720 // The implicitly-defined or explicitly-defaulted copy assignment operator
9721 // for a non-union class X performs memberwise copy assignment of its
9722 // subobjects. The direct base classes of X are assigned first, in the
9723 // order of their declaration in the base-specifier-list, and then the
9724 // immediate non-static data members of X are assigned, in the order in
9725 // which they were declared in the class definition.
9726
9727 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009728 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009729
9730 // The parameter for the "other" object, which we are copying from.
9731 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9732 Qualifiers OtherQuals = Other->getType().getQualifiers();
9733 QualType OtherRefType = Other->getType();
9734 if (const LValueReferenceType *OtherRef
9735 = OtherRefType->getAs<LValueReferenceType>()) {
9736 OtherRefType = OtherRef->getPointeeType();
9737 OtherQuals = OtherRefType.getQualifiers();
9738 }
9739
9740 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009741 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9742 ? CopyAssignOperator->getLocEnd()
9743 : CopyAssignOperator->getLocation();
9744
Pavel Labath58934982013-08-30 08:52:28 +00009745 // Builds a DeclRefExpr for the "other" object.
9746 RefBuilder OtherRef(Other, OtherRefType);
9747
9748 // Builds the "this" pointer.
9749 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009750
9751 // Assign base classes.
9752 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009753 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009754 // Form the assignment:
9755 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009756 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009757 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009758 Invalid = true;
9759 continue;
9760 }
9761
John McCallcf142162010-08-07 06:22:56 +00009762 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009763 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009764
Douglas Gregorb139cd52010-05-01 20:49:11 +00009765 // Construct the "from" expression, which is an implicit cast to the
9766 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009767 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9768 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009769
9770 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009771 DerefBuilder DerefThis(This);
9772 CastBuilder To(DerefThis,
9773 Context.getCVRQualifiedType(
9774 BaseType, CopyAssignOperator->getTypeQualifiers()),
9775 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009776
9777 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009778 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009779 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009780 /*CopyingBaseSubobject=*/true,
9781 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009782 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009783 Diag(CurrentLocation, diag::note_member_synthesized_at)
9784 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9785 CopyAssignOperator->setInvalidDecl();
9786 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009787 }
9788
9789 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009790 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009791 }
9792
Douglas Gregorb139cd52010-05-01 20:49:11 +00009793 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009794 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009795 if (Field->isUnnamedBitfield())
9796 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009797
9798 if (Field->isInvalidDecl()) {
9799 Invalid = true;
9800 continue;
9801 }
9802
Douglas Gregorb139cd52010-05-01 20:49:11 +00009803 // Check for members of reference type; we can't copy those.
9804 if (Field->getType()->isReferenceType()) {
9805 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9806 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9807 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009808 Diag(CurrentLocation, diag::note_member_synthesized_at)
9809 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009810 Invalid = true;
9811 continue;
9812 }
9813
9814 // Check for members of const-qualified, non-class type.
9815 QualType BaseType = Context.getBaseElementType(Field->getType());
9816 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9817 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9818 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9819 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009820 Diag(CurrentLocation, diag::note_member_synthesized_at)
9821 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009822 Invalid = true;
9823 continue;
9824 }
John McCall1b1a1db2011-06-17 00:18:42 +00009825
9826 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009827 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9828 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009829
9830 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009831 if (FieldType->isIncompleteArrayType()) {
9832 assert(ClassDecl->hasFlexibleArrayMember() &&
9833 "Incomplete array type is not valid");
9834 continue;
9835 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009836
9837 // Build references to the field in the object we're copying from and to.
9838 CXXScopeSpec SS; // Intentionally empty
9839 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9840 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009841 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009842 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009843
9844 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9845
9846 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009847
Douglas Gregorb139cd52010-05-01 20:49:11 +00009848 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009849 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009850 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009851 /*CopyingBaseSubobject=*/false,
9852 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009853 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009854 Diag(CurrentLocation, diag::note_member_synthesized_at)
9855 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9856 CopyAssignOperator->setInvalidDecl();
9857 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009858 }
9859
9860 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009861 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009862 }
9863
9864 if (!Invalid) {
9865 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009866 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009867
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009868 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009869 if (Return.isInvalid())
9870 Invalid = true;
9871 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009872 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009873
9874 if (Trap.hasErrorOccurred()) {
9875 Diag(CurrentLocation, diag::note_member_synthesized_at)
9876 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9877 Invalid = true;
9878 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009879 }
9880 }
9881
9882 if (Invalid) {
9883 CopyAssignOperator->setInvalidDecl();
9884 return;
9885 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009886
9887 StmtResult Body;
9888 {
9889 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009890 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009891 /*isStmtExpr=*/false);
9892 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9893 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009894 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009895
9896 if (ASTMutationListener *L = getASTMutationListener()) {
9897 L->CompletedImplicitDefinition(CopyAssignOperator);
9898 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009899}
9900
Sebastian Redl22653ba2011-08-30 19:58:05 +00009901Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009902Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9903 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009904
Richard Smithd3b5c9082012-07-27 04:22:15 +00009905 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009906 if (ClassDecl->isInvalidDecl())
9907 return ExceptSpec;
9908
9909 // C++0x [except.spec]p14:
9910 // An implicitly declared special member function (Clause 12) shall have an
9911 // exception-specification. [...]
9912
9913 // It is unspecified whether or not an implicit move assignment operator
9914 // attempts to deduplicate calls to assignment operators of virtual bases are
9915 // made. As such, this exception specification is effectively unspecified.
9916 // Based on a similar decision made for constness in C++0x, we're erring on
9917 // the side of assuming such calls to be made regardless of whether they
9918 // actually happen.
9919 // Note that a move constructor is not implicitly declared when there are
9920 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009921 for (const auto &Base : ClassDecl->bases()) {
9922 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009923 continue;
9924
9925 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009926 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009927 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009928 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009929 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009930 }
9931
Aaron Ballman445a9392014-03-13 16:15:17 +00009932 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009933 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009934 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009935 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009936 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009937 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009938 }
9939
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009940 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009941 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009942 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009943 if (CXXMethodDecl *MoveAssign =
9944 LookupMovingAssignment(FieldClassDecl,
9945 FieldType.getCVRQualifiers(),
9946 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009947 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009948 }
9949 }
9950
9951 return ExceptSpec;
9952}
9953
9954CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009955 assert(ClassDecl->needsImplicitMoveAssignment());
9956
Richard Smith8bf22e52012-11-29 01:34:07 +00009957 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9958 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009959 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009960
Sebastian Redl22653ba2011-08-30 19:58:05 +00009961 // Note: The following rules are largely analoguous to the move
9962 // constructor rules.
9963
Sebastian Redl22653ba2011-08-30 19:58:05 +00009964 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9965 QualType RetType = Context.getLValueReferenceType(ArgType);
9966 ArgType = Context.getRValueReferenceType(ArgType);
9967
Richard Smith99005e62013-05-07 03:19:20 +00009968 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9969 CXXMoveAssignment,
9970 false);
9971
Sebastian Redl22653ba2011-08-30 19:58:05 +00009972 // An implicitly-declared move assignment operator is an inline public
9973 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009974 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9975 SourceLocation ClassLoc = ClassDecl->getLocation();
9976 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009977 CXXMethodDecl *MoveAssignment =
9978 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009979 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009980 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009981 MoveAssignment->setAccess(AS_public);
9982 MoveAssignment->setDefaulted();
9983 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009984
Richard Smithd3b5c9082012-07-27 04:22:15 +00009985 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009986 FunctionProtoType::ExtProtoInfo EPI =
9987 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009988 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009989
Sebastian Redl22653ba2011-08-30 19:58:05 +00009990 // Add the parameter to the operator.
9991 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009992 ClassLoc, ClassLoc,
9993 /*Id=*/nullptr, ArgType,
9994 /*TInfo=*/nullptr, SC_None,
9995 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009996 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009997
Richard Smith6b02d462012-12-08 08:32:28 +00009998 AddOverriddenMethods(ClassDecl, MoveAssignment);
9999
10000 MoveAssignment->setTrivial(
10001 ClassDecl->needsOverloadResolutionForMoveAssignment()
10002 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10003 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010004
Richard Smithd951a1d2012-02-18 02:02:13 +000010005 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010006 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10007 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010008 }
10009
Richard Smith6b02d462012-12-08 08:32:28 +000010010 // Note that we have added this copy-assignment operator.
10011 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10012
Sebastian Redl22653ba2011-08-30 19:58:05 +000010013 if (Scope *S = getScopeForContext(ClassDecl))
10014 PushOnScopeChains(MoveAssignment, S, false);
10015 ClassDecl->addDecl(MoveAssignment);
10016
Sebastian Redl22653ba2011-08-30 19:58:05 +000010017 return MoveAssignment;
10018}
10019
Richard Smithb2504bd2013-11-04 04:26:14 +000010020/// Check if we're implicitly defining a move assignment operator for a class
10021/// with virtual bases. Such a move assignment might move-assign the virtual
10022/// base multiple times.
10023static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10024 SourceLocation CurrentLocation) {
10025 assert(!Class->isDependentContext() && "should not define dependent move");
10026
10027 // Only a virtual base could get implicitly move-assigned multiple times.
10028 // Only a non-trivial move assignment can observe this. We only want to
10029 // diagnose if we implicitly define an assignment operator that assigns
10030 // two base classes, both of which move-assign the same virtual base.
10031 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10032 Class->getNumBases() < 2)
10033 return;
10034
10035 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10036 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10037 VBaseMap VBases;
10038
Aaron Ballman574705e2014-03-13 15:41:46 +000010039 for (auto &BI : Class->bases()) {
10040 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010041 while (!Worklist.empty()) {
10042 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10043 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10044
10045 // If the base has no non-trivial move assignment operators,
10046 // we don't care about moves from it.
10047 if (!Base->hasNonTrivialMoveAssignment())
10048 continue;
10049
10050 // If there's nothing virtual here, skip it.
10051 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10052 continue;
10053
10054 // If we're not actually going to call a move assignment for this base,
10055 // or the selected move assignment is trivial, skip it.
10056 Sema::SpecialMemberOverloadResult *SMOR =
10057 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10058 /*ConstArg*/false, /*VolatileArg*/false,
10059 /*RValueThis*/true, /*ConstThis*/false,
10060 /*VolatileThis*/false);
10061 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10062 !SMOR->getMethod()->isMoveAssignmentOperator())
10063 continue;
10064
10065 if (BaseSpec->isVirtual()) {
10066 // We're going to move-assign this virtual base, and its move
10067 // assignment operator is not trivial. If this can happen for
10068 // multiple distinct direct bases of Class, diagnose it. (If it
10069 // only happens in one base, we'll diagnose it when synthesizing
10070 // that base class's move assignment operator.)
10071 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010072 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010073 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010074 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010075 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10076 << Class << Base;
10077 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10078 << (Base->getCanonicalDecl() ==
10079 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10080 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010081 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010082 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010083 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10084 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010085
10086 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010087 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010088 }
10089 } else {
10090 // Only walk over bases that have defaulted move assignment operators.
10091 // We assume that any user-provided move assignment operator handles
10092 // the multiple-moves-of-vbase case itself somehow.
10093 if (!SMOR->getMethod()->isDefaulted())
10094 continue;
10095
10096 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010097 for (auto &BI : Base->bases())
10098 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010099 }
10100 }
10101 }
10102}
10103
Sebastian Redl22653ba2011-08-30 19:58:05 +000010104void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10105 CXXMethodDecl *MoveAssignOperator) {
10106 assert((MoveAssignOperator->isDefaulted() &&
10107 MoveAssignOperator->isOverloadedOperator() &&
10108 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010109 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10110 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010111 "DefineImplicitMoveAssignment called for wrong function");
10112
10113 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10114
10115 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10116 MoveAssignOperator->setInvalidDecl();
10117 return;
10118 }
10119
Eli Friedman276dd182013-09-05 00:02:25 +000010120 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010121
Eli Friedmaneaf34142012-10-18 20:14:08 +000010122 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010123 DiagnosticErrorTrap Trap(Diags);
10124
10125 // C++0x [class.copy]p28:
10126 // The implicitly-defined or move assignment operator for a non-union class
10127 // X performs memberwise move assignment of its subobjects. The direct base
10128 // classes of X are assigned first, in the order of their declaration in the
10129 // base-specifier-list, and then the immediate non-static data members of X
10130 // are assigned, in the order in which they were declared in the class
10131 // definition.
10132
Richard Smithb2504bd2013-11-04 04:26:14 +000010133 // Issue a warning if our implicit move assignment operator will move
10134 // from a virtual base more than once.
10135 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010136
Sebastian Redl22653ba2011-08-30 19:58:05 +000010137 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010138 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010139
10140 // The parameter for the "other" object, which we are move from.
10141 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10142 QualType OtherRefType = Other->getType()->
10143 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010144 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010145 "Bad argument type of defaulted move assignment");
10146
10147 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010148 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10149 ? MoveAssignOperator->getLocEnd()
10150 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010151
Pavel Labath58934982013-08-30 08:52:28 +000010152 // Builds a reference to the "other" object.
10153 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010154 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010155 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010156
Pavel Labath58934982013-08-30 08:52:28 +000010157 // Builds the "this" pointer.
10158 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010159
Sebastian Redl22653ba2011-08-30 19:58:05 +000010160 // Assign base classes.
10161 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010162 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010163 // C++11 [class.copy]p28:
10164 // It is unspecified whether subobjects representing virtual base classes
10165 // are assigned more than once by the implicitly-defined copy assignment
10166 // operator.
10167 // FIXME: Do not assign to a vbase that will be assigned by some other base
10168 // class. For a move-assignment, this can result in the vbase being moved
10169 // multiple times.
10170
Sebastian Redl22653ba2011-08-30 19:58:05 +000010171 // Form the assignment:
10172 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010173 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010174 if (!BaseType->isRecordType()) {
10175 Invalid = true;
10176 continue;
10177 }
10178
10179 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010180 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010181
10182 // Construct the "from" expression, which is an implicit cast to the
10183 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010184 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010185
10186 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010187 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010188
10189 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010190 CastBuilder To(DerefThis,
10191 Context.getCVRQualifiedType(
10192 BaseType, MoveAssignOperator->getTypeQualifiers()),
10193 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194
10195 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010196 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010197 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010198 /*CopyingBaseSubobject=*/true,
10199 /*Copying=*/false);
10200 if (Move.isInvalid()) {
10201 Diag(CurrentLocation, diag::note_member_synthesized_at)
10202 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10203 MoveAssignOperator->setInvalidDecl();
10204 return;
10205 }
10206
10207 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010208 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010209 }
10210
Sebastian Redl22653ba2011-08-30 19:58:05 +000010211 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010212 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010213 if (Field->isUnnamedBitfield())
10214 continue;
10215
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010216 if (Field->isInvalidDecl()) {
10217 Invalid = true;
10218 continue;
10219 }
10220
Sebastian Redl22653ba2011-08-30 19:58:05 +000010221 // Check for members of reference type; we can't move those.
10222 if (Field->getType()->isReferenceType()) {
10223 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10224 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10225 Diag(Field->getLocation(), diag::note_declared_at);
10226 Diag(CurrentLocation, diag::note_member_synthesized_at)
10227 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10228 Invalid = true;
10229 continue;
10230 }
10231
10232 // Check for members of const-qualified, non-class type.
10233 QualType BaseType = Context.getBaseElementType(Field->getType());
10234 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10235 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10236 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10237 Diag(Field->getLocation(), diag::note_declared_at);
10238 Diag(CurrentLocation, diag::note_member_synthesized_at)
10239 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10240 Invalid = true;
10241 continue;
10242 }
10243
10244 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010245 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10246 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010247
10248 QualType FieldType = Field->getType().getNonReferenceType();
10249 if (FieldType->isIncompleteArrayType()) {
10250 assert(ClassDecl->hasFlexibleArrayMember() &&
10251 "Incomplete array type is not valid");
10252 continue;
10253 }
10254
10255 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010256 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10257 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010258 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010259 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010260 MemberBuilder From(MoveOther, OtherRefType,
10261 /*IsArrow=*/false, MemberLookup);
10262 MemberBuilder To(This, getCurrentThisType(),
10263 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010264
Pavel Labath58934982013-08-30 08:52:28 +000010265 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010266 "Member reference with rvalue base must be rvalue except for reference "
10267 "members, which aren't allowed for move assignment.");
10268
Sebastian Redl22653ba2011-08-30 19:58:05 +000010269 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010270 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010271 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010272 /*CopyingBaseSubobject=*/false,
10273 /*Copying=*/false);
10274 if (Move.isInvalid()) {
10275 Diag(CurrentLocation, diag::note_member_synthesized_at)
10276 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10277 MoveAssignOperator->setInvalidDecl();
10278 return;
10279 }
Richard Smith11d19592012-11-12 23:33:00 +000010280
Sebastian Redl22653ba2011-08-30 19:58:05 +000010281 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010282 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010283 }
10284
10285 if (!Invalid) {
10286 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010287 ExprResult ThisObj =
10288 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10289
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010290 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010291 if (Return.isInvalid())
10292 Invalid = true;
10293 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010294 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010295
10296 if (Trap.hasErrorOccurred()) {
10297 Diag(CurrentLocation, diag::note_member_synthesized_at)
10298 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10299 Invalid = true;
10300 }
10301 }
10302 }
10303
10304 if (Invalid) {
10305 MoveAssignOperator->setInvalidDecl();
10306 return;
10307 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010308
10309 StmtResult Body;
10310 {
10311 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010312 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010313 /*isStmtExpr=*/false);
10314 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10315 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010316 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010317
10318 if (ASTMutationListener *L = getASTMutationListener()) {
10319 L->CompletedImplicitDefinition(MoveAssignOperator);
10320 }
10321}
10322
Richard Smithd3b5c9082012-07-27 04:22:15 +000010323Sema::ImplicitExceptionSpecification
10324Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10325 CXXRecordDecl *ClassDecl = MD->getParent();
10326
10327 ImplicitExceptionSpecification ExceptSpec(*this);
10328 if (ClassDecl->isInvalidDecl())
10329 return ExceptSpec;
10330
10331 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010332 assert(T->getNumParams() >= 1 && "not a copy ctor");
10333 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010334
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010335 // C++ [except.spec]p14:
10336 // An implicitly declared special member function (Clause 12) shall have an
10337 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010338 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010339 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010340 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010341 continue;
10342
Douglas Gregora6d69502010-07-02 23:41:54 +000010343 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010344 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010345 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010346 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010347 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010348 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010349 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010350 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010351 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010352 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010353 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010354 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010355 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010356 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010357 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010358 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10359 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010360 LookupCopyingConstructor(FieldClassDecl,
10361 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010362 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010363 }
10364 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010365
Richard Smithd3b5c9082012-07-27 04:22:15 +000010366 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010367}
10368
10369CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10370 CXXRecordDecl *ClassDecl) {
10371 // C++ [class.copy]p4:
10372 // If the class definition does not explicitly declare a copy
10373 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010374 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010375
Richard Smith8bf22e52012-11-29 01:34:07 +000010376 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10377 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010378 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010379
Alexis Hunt913820d2011-05-13 06:10:58 +000010380 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10381 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010382 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010383 if (Const)
10384 ArgType = ArgType.withConst();
10385 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010386
Richard Smithb5800092012-06-10 05:43:50 +000010387 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10388 CXXCopyConstructor,
10389 Const);
10390
Douglas Gregor54be3392010-07-01 17:57:27 +000010391 DeclarationName Name
10392 = Context.DeclarationNames.getCXXConstructorName(
10393 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010394 SourceLocation ClassLoc = ClassDecl->getLocation();
10395 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010396
10397 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010398 // member of its class.
10399 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010400 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010401 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010402 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010403 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010404 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010405
Richard Smithd3b5c9082012-07-27 04:22:15 +000010406 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010407 FunctionProtoType::ExtProtoInfo EPI =
10408 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010409 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010410 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010411
Douglas Gregor54be3392010-07-01 17:57:27 +000010412 // Add the parameter to the constructor.
10413 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010414 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010415 /*IdentifierInfo=*/nullptr,
10416 ArgType, /*TInfo=*/nullptr,
10417 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010418 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010419
Richard Smith6b02d462012-12-08 08:32:28 +000010420 CopyConstructor->setTrivial(
10421 ClassDecl->needsOverloadResolutionForCopyConstructor()
10422 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10423 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010424
Richard Smith852265f2012-03-30 20:53:28 +000010425 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010426 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010427
Richard Smith6b02d462012-12-08 08:32:28 +000010428 // Note that we have declared this constructor.
10429 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10430
10431 if (Scope *S = getScopeForContext(ClassDecl))
10432 PushOnScopeChains(CopyConstructor, S, false);
10433 ClassDecl->addDecl(CopyConstructor);
10434
Douglas Gregor54be3392010-07-01 17:57:27 +000010435 return CopyConstructor;
10436}
10437
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010438void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010439 CXXConstructorDecl *CopyConstructor) {
10440 assert((CopyConstructor->isDefaulted() &&
10441 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010442 !CopyConstructor->doesThisDeclarationHaveABody() &&
10443 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010444 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010445
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010446 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010447 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010448
Richard Smithd577fbb2013-06-13 03:23:42 +000010449 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010450 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010451 // deprecated if the class has a user-declared copy assignment operator
10452 // or a user-declared destructor.
10453 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10454 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10455
Eli Friedmaneaf34142012-10-18 20:14:08 +000010456 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010457 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010458
David Blaikie3fc2f912013-01-17 05:26:25 +000010459 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010460 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010461 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010462 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010463 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010464 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010465 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10466 ? CopyConstructor->getLocEnd()
10467 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010468 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010469 CopyConstructor->setBody(
10470 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010471 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010472
Eli Friedman276dd182013-09-05 00:02:25 +000010473 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010474 MarkVTableUsed(CurrentLocation, ClassDecl);
10475
Sebastian Redlab238a72011-04-24 16:28:06 +000010476 if (ASTMutationListener *L = getASTMutationListener()) {
10477 L->CompletedImplicitDefinition(CopyConstructor);
10478 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010479}
10480
Sebastian Redl22653ba2011-08-30 19:58:05 +000010481Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010482Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10483 CXXRecordDecl *ClassDecl = MD->getParent();
10484
Sebastian Redl22653ba2011-08-30 19:58:05 +000010485 // C++ [except.spec]p14:
10486 // An implicitly declared special member function (Clause 12) shall have an
10487 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010488 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010489 if (ClassDecl->isInvalidDecl())
10490 return ExceptSpec;
10491
10492 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010493 for (const auto &B : ClassDecl->bases()) {
10494 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010495 continue;
10496
Aaron Ballman574705e2014-03-13 15:41:46 +000010497 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010498 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010499 CXXConstructorDecl *Constructor =
10500 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010501 // If this is a deleted function, add it anyway. This might be conformant
10502 // with the standard. This might not. I'm not sure. It might not matter.
10503 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010504 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010505 }
10506 }
10507
10508 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010509 for (const auto &B : ClassDecl->vbases()) {
10510 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010511 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010512 CXXConstructorDecl *Constructor =
10513 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010514 // If this is a deleted function, add it anyway. This might be conformant
10515 // with the standard. This might not. I'm not sure. It might not matter.
10516 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010517 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010518 }
10519 }
10520
10521 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010522 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010523 QualType FieldType = Context.getBaseElementType(F->getType());
10524 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10525 CXXConstructorDecl *Constructor =
10526 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010527 // If this is a deleted function, add it anyway. This might be conformant
10528 // with the standard. This might not. I'm not sure. It might not matter.
10529 // In particular, the problem is that this function never gets called. It
10530 // might just be ill-formed because this function attempts to refer to
10531 // a deleted function here.
10532 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010533 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010534 }
10535 }
10536
10537 return ExceptSpec;
10538}
10539
10540CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10541 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010542 assert(ClassDecl->needsImplicitMoveConstructor());
10543
Richard Smith8bf22e52012-11-29 01:34:07 +000010544 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10545 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010546 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010547
Sebastian Redl22653ba2011-08-30 19:58:05 +000010548 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10549 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010550
Richard Smithb5800092012-06-10 05:43:50 +000010551 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10552 CXXMoveConstructor,
10553 false);
10554
Sebastian Redl22653ba2011-08-30 19:58:05 +000010555 DeclarationName Name
10556 = Context.DeclarationNames.getCXXConstructorName(
10557 Context.getCanonicalType(ClassType));
10558 SourceLocation ClassLoc = ClassDecl->getLocation();
10559 DeclarationNameInfo NameInfo(Name, ClassLoc);
10560
Richard Smith99005e62013-05-07 03:19:20 +000010561 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010562 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010563 // member of its class.
10564 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010565 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010566 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010567 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010568 MoveConstructor->setAccess(AS_public);
10569 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010570
Richard Smithd3b5c9082012-07-27 04:22:15 +000010571 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010572 FunctionProtoType::ExtProtoInfo EPI =
10573 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010574 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010575 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010576
Sebastian Redl22653ba2011-08-30 19:58:05 +000010577 // Add the parameter to the constructor.
10578 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10579 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010580 /*IdentifierInfo=*/nullptr,
10581 ArgType, /*TInfo=*/nullptr,
10582 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010583 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010584
Richard Smith6b02d462012-12-08 08:32:28 +000010585 MoveConstructor->setTrivial(
10586 ClassDecl->needsOverloadResolutionForMoveConstructor()
10587 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10588 : ClassDecl->hasTrivialMoveConstructor());
10589
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010590 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010591 ClassDecl->setImplicitMoveConstructorIsDeleted();
10592 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010593 }
10594
10595 // Note that we have declared this constructor.
10596 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10597
10598 if (Scope *S = getScopeForContext(ClassDecl))
10599 PushOnScopeChains(MoveConstructor, S, false);
10600 ClassDecl->addDecl(MoveConstructor);
10601
10602 return MoveConstructor;
10603}
10604
10605void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10606 CXXConstructorDecl *MoveConstructor) {
10607 assert((MoveConstructor->isDefaulted() &&
10608 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010609 !MoveConstructor->doesThisDeclarationHaveABody() &&
10610 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010611 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10612
10613 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10614 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10615
Eli Friedmaneaf34142012-10-18 20:14:08 +000010616 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010617 DiagnosticErrorTrap Trap(Diags);
10618
David Blaikie3fc2f912013-01-17 05:26:25 +000010619 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010620 Trap.hasErrorOccurred()) {
10621 Diag(CurrentLocation, diag::note_member_synthesized_at)
10622 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10623 MoveConstructor->setInvalidDecl();
10624 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010625 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10626 ? MoveConstructor->getLocEnd()
10627 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010628 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010629 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010630 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010631 }
10632
Eli Friedman276dd182013-09-05 00:02:25 +000010633 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010634 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010635
10636 if (ASTMutationListener *L = getASTMutationListener()) {
10637 L->CompletedImplicitDefinition(MoveConstructor);
10638 }
10639}
10640
Douglas Gregor74f7d502012-02-15 19:33:52 +000010641bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010642 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010643}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010644
10645void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010646 SourceLocation CurrentLocation,
10647 CXXConversionDecl *Conv) {
10648 CXXRecordDecl *Lambda = Conv->getParent();
10649 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10650 // If we are defining a specialization of a conversion to function-ptr
10651 // cache the deduced template arguments for this specialization
10652 // so that we can use them to retrieve the corresponding call-operator
10653 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010654 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10655
Faisal Vali571df122013-09-29 08:45:24 +000010656 // Retrieve the corresponding call-operator specialization.
10657 if (Lambda->isGenericLambda()) {
10658 assert(Conv->isFunctionTemplateSpecialization());
10659 FunctionTemplateDecl *CallOpTemplate =
10660 CallOp->getDescribedFunctionTemplate();
10661 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010662 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010663 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010664 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010665 InsertPos);
10666 assert(CallOpSpec &&
10667 "Conversion operator must have a corresponding call operator");
10668 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10669 }
10670 // Mark the call operator referenced (and add to pending instantiations
10671 // if necessary).
10672 // For both the conversion and static-invoker template specializations
10673 // we construct their body's in this function, so no need to add them
10674 // to the PendingInstantiations.
10675 MarkFunctionReferenced(CurrentLocation, CallOp);
10676
Eli Friedmaneaf34142012-10-18 20:14:08 +000010677 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010678 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010679
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010680 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010681 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10682 // ... and get the corresponding specialization for a generic lambda.
10683 if (Lambda->isGenericLambda()) {
10684 assert(DeducedTemplateArgs &&
10685 "Must have deduced template arguments from Conversion Operator");
10686 FunctionTemplateDecl *InvokeTemplate =
10687 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010688 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010689 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010690 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010691 InsertPos);
10692 assert(InvokeSpec &&
10693 "Must have a corresponding static invoker specialization");
10694 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10695 }
10696 // Construct the body of the conversion function { return __invoke; }.
10697 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010698 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010699 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010700 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010701 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10702 Conv->getLocation(),
10703 Conv->getLocation()));
10704
10705 Conv->markUsed(Context);
10706 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010707
Faisal Vali571df122013-09-29 08:45:24 +000010708 // Fill in the __invoke function with a dummy implementation. IR generation
10709 // will fill in the actual details.
10710 Invoker->markUsed(Context);
10711 Invoker->setReferenced();
10712 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10713
Douglas Gregord3b672c2012-02-16 01:06:16 +000010714 if (ASTMutationListener *L = getASTMutationListener()) {
10715 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010716 L->CompletedImplicitDefinition(Invoker);
10717 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010718}
10719
Faisal Vali571df122013-09-29 08:45:24 +000010720
10721
Douglas Gregord3b672c2012-02-16 01:06:16 +000010722void Sema::DefineImplicitLambdaToBlockPointerConversion(
10723 SourceLocation CurrentLocation,
10724 CXXConversionDecl *Conv)
10725{
Faisal Vali850da1a2013-09-29 17:08:32 +000010726 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010727
Eli Friedman276dd182013-09-05 00:02:25 +000010728 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010729
Eli Friedmaneaf34142012-10-18 20:14:08 +000010730 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010731 DiagnosticErrorTrap Trap(Diags);
10732
Douglas Gregored90df32012-02-22 05:02:47 +000010733 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010734 Expr *This = ActOnCXXThis(CurrentLocation).get();
10735 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010736
Eli Friedman98b01ed2012-03-01 04:01:32 +000010737 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10738 Conv->getLocation(),
10739 Conv, DerefThis);
10740
10741 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10742 // behavior. Note that only the general conversion function does this
10743 // (since it's unusable otherwise); in the case where we inline the
10744 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010745 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010746 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10747 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010748 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010749
10750 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010751 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010752 Conv->setInvalidDecl();
10753 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010754 }
Douglas Gregored90df32012-02-22 05:02:47 +000010755
Douglas Gregored90df32012-02-22 05:02:47 +000010756 // Create the return statement that returns the block from the conversion
10757 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010758 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010759 if (Return.isInvalid()) {
10760 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10761 Conv->setInvalidDecl();
10762 return;
10763 }
10764
10765 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010766 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010767 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010768 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010769 Conv->getLocation()));
10770
Douglas Gregored90df32012-02-22 05:02:47 +000010771 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010772 if (ASTMutationListener *L = getASTMutationListener()) {
10773 L->CompletedImplicitDefinition(Conv);
10774 }
10775}
10776
Douglas Gregord2f70072012-03-10 06:53:13 +000010777/// \brief Determine whether the given list arguments contains exactly one
10778/// "real" (non-default) argument.
10779static bool hasOneRealArgument(MultiExprArg Args) {
10780 switch (Args.size()) {
10781 case 0:
10782 return false;
10783
10784 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010785 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010786 return false;
10787
10788 // fall through
10789 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010790 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010791 }
10792
10793 return false;
10794}
10795
John McCalldadc5752010-08-24 06:29:42 +000010796ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010797Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010798 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010799 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010800 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010801 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010802 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010803 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010804 unsigned ConstructKind,
10805 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010806 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010807
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010808 // C++0x [class.copy]p34:
10809 // When certain criteria are met, an implementation is allowed to
10810 // omit the copy/move construction of a class object, even if the
10811 // copy/move constructor and/or destructor for the object have
10812 // side effects. [...]
10813 // - when a temporary class object that has not been bound to a
10814 // reference (12.2) would be copied/moved to a class object
10815 // with the same cv-unqualified type, the copy/move operation
10816 // can be omitted by constructing the temporary object
10817 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010818 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010819 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010820 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010821 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010822 }
Mike Stump11289f42009-09-09 15:08:12 +000010823
10824 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010825 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010826 IsListInitialization,
10827 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000010828 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010829}
10830
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010831/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10832/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010833ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010834Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10835 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010836 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010837 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010838 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010839 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010840 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010841 unsigned ConstructKind,
10842 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010843 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010844 return CXXConstructExpr::Create(
10845 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010846 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10847 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010848 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10849 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010850}
10851
John McCall03c48482010-02-02 09:10:11 +000010852void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010853 if (VD->isInvalidDecl()) return;
10854
John McCall03c48482010-02-02 09:10:11 +000010855 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010856 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010857 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010858 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010859
Chandler Carruth86d17d32011-03-27 21:26:48 +000010860 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010861 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010862 CheckDestructorAccess(VD->getLocation(), Destructor,
10863 PDiag(diag::err_access_dtor_var)
10864 << VD->getDeclName()
10865 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010866 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010867
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010868 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010869 if (!VD->hasGlobalStorage()) return;
10870
10871 // Emit warning for non-trivial dtor in global scope (a real global,
10872 // class-static, function-static).
10873 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10874
10875 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010876 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010877 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010878}
10879
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010880/// \brief Given a constructor and the set of arguments provided for the
10881/// constructor, convert the arguments and add any required default arguments
10882/// to form a proper call to this constructor.
10883///
10884/// \returns true if an error occurred, false otherwise.
10885bool
10886Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10887 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010888 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010889 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010890 bool AllowExplicit,
10891 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010892 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10893 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010894 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010895
10896 const FunctionProtoType *Proto
10897 = Constructor->getType()->getAs<FunctionProtoType>();
10898 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010899 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010900
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010901 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010902 if (NumArgs < NumParams)
10903 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010904 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010905 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010906
10907 VariadicCallType CallType =
10908 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010909 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010910 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010911 Proto, 0,
10912 llvm::makeArrayRef(Args, NumArgs),
10913 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010914 CallType, AllowExplicit,
10915 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010916 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010917
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010918 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010919
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010920 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000010921 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010922 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010923
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010924 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010925}
10926
Anders Carlssone363c8e2009-12-12 00:32:00 +000010927static inline bool
10928CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10929 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010930 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010931 if (isa<NamespaceDecl>(DC)) {
10932 return SemaRef.Diag(FnDecl->getLocation(),
10933 diag::err_operator_new_delete_declared_in_namespace)
10934 << FnDecl->getDeclName();
10935 }
10936
10937 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010938 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010939 return SemaRef.Diag(FnDecl->getLocation(),
10940 diag::err_operator_new_delete_declared_static)
10941 << FnDecl->getDeclName();
10942 }
10943
Anders Carlsson60659a82009-12-12 02:43:16 +000010944 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010945}
10946
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010947static inline bool
10948CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10949 CanQualType ExpectedResultType,
10950 CanQualType ExpectedFirstParamType,
10951 unsigned DependentParamTypeDiag,
10952 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010953 QualType ResultType =
10954 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010955
10956 // Check that the result type is not dependent.
10957 if (ResultType->isDependentType())
10958 return SemaRef.Diag(FnDecl->getLocation(),
10959 diag::err_operator_new_delete_dependent_result_type)
10960 << FnDecl->getDeclName() << ExpectedResultType;
10961
10962 // Check that the result type is what we expect.
10963 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10964 return SemaRef.Diag(FnDecl->getLocation(),
10965 diag::err_operator_new_delete_invalid_result_type)
10966 << FnDecl->getDeclName() << ExpectedResultType;
10967
10968 // A function template must have at least 2 parameters.
10969 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10970 return SemaRef.Diag(FnDecl->getLocation(),
10971 diag::err_operator_new_delete_template_too_few_parameters)
10972 << FnDecl->getDeclName();
10973
10974 // The function decl must have at least 1 parameter.
10975 if (FnDecl->getNumParams() == 0)
10976 return SemaRef.Diag(FnDecl->getLocation(),
10977 diag::err_operator_new_delete_too_few_parameters)
10978 << FnDecl->getDeclName();
10979
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010980 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010981 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10982 if (FirstParamType->isDependentType())
10983 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10984 << FnDecl->getDeclName() << ExpectedFirstParamType;
10985
10986 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010987 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010988 ExpectedFirstParamType)
10989 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10990 << FnDecl->getDeclName() << ExpectedFirstParamType;
10991
10992 return false;
10993}
10994
Anders Carlsson12308f42009-12-11 23:23:22 +000010995static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010996CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010997 // C++ [basic.stc.dynamic.allocation]p1:
10998 // A program is ill-formed if an allocation function is declared in a
10999 // namespace scope other than global scope or declared static in global
11000 // scope.
11001 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11002 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011003
11004 CanQualType SizeTy =
11005 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11006
11007 // C++ [basic.stc.dynamic.allocation]p1:
11008 // The return type shall be void*. The first parameter shall have type
11009 // std::size_t.
11010 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11011 SizeTy,
11012 diag::err_operator_new_dependent_param_type,
11013 diag::err_operator_new_param_type))
11014 return true;
11015
11016 // C++ [basic.stc.dynamic.allocation]p1:
11017 // The first parameter shall not have an associated default argument.
11018 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011019 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011020 diag::err_operator_new_default_arg)
11021 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11022
11023 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011024}
11025
11026static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011027CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011028 // C++ [basic.stc.dynamic.deallocation]p1:
11029 // A program is ill-formed if deallocation functions are declared in a
11030 // namespace scope other than global scope or declared static in global
11031 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011032 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11033 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011034
11035 // C++ [basic.stc.dynamic.deallocation]p2:
11036 // Each deallocation function shall return void and its first parameter
11037 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011038 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11039 SemaRef.Context.VoidPtrTy,
11040 diag::err_operator_delete_dependent_param_type,
11041 diag::err_operator_delete_param_type))
11042 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011043
Anders Carlsson12308f42009-12-11 23:23:22 +000011044 return false;
11045}
11046
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011047/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11048/// of this overloaded operator is well-formed. If so, returns false;
11049/// otherwise, emits appropriate diagnostics and returns true.
11050bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011051 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011052 "Expected an overloaded operator declaration");
11053
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011054 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11055
Mike Stump11289f42009-09-09 15:08:12 +000011056 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011057 // The allocation and deallocation functions, operator new,
11058 // operator new[], operator delete and operator delete[], are
11059 // described completely in 3.7.3. The attributes and restrictions
11060 // found in the rest of this subclause do not apply to them unless
11061 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011062 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011063 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011064
Anders Carlsson22f443f2009-12-12 00:26:23 +000011065 if (Op == OO_New || Op == OO_Array_New)
11066 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011067
11068 // C++ [over.oper]p6:
11069 // An operator function shall either be a non-static member
11070 // function or be a non-member function and have at least one
11071 // parameter whose type is a class, a reference to a class, an
11072 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011073 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11074 if (MethodDecl->isStatic())
11075 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011076 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011077 } else {
11078 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011079 for (auto Param : FnDecl->params()) {
11080 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011081 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11082 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011083 ClassOrEnumParam = true;
11084 break;
11085 }
11086 }
11087
Douglas Gregord69246b2008-11-17 16:14:12 +000011088 if (!ClassOrEnumParam)
11089 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011090 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011091 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011092 }
11093
11094 // C++ [over.oper]p8:
11095 // An operator function cannot have default arguments (8.3.6),
11096 // except where explicitly stated below.
11097 //
Mike Stump11289f42009-09-09 15:08:12 +000011098 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011099 // (C++ [over.call]p1).
11100 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011101 for (auto Param : FnDecl->params()) {
11102 if (Param->hasDefaultArg())
11103 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011104 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011105 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011106 }
11107 }
11108
Douglas Gregor6cf08062008-11-10 13:38:07 +000011109 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11110 { false, false, false }
11111#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11112 , { Unary, Binary, MemberOnly }
11113#include "clang/Basic/OperatorKinds.def"
11114 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011115
Douglas Gregor6cf08062008-11-10 13:38:07 +000011116 bool CanBeUnaryOperator = OperatorUses[Op][0];
11117 bool CanBeBinaryOperator = OperatorUses[Op][1];
11118 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011119
11120 // C++ [over.oper]p8:
11121 // [...] Operator functions cannot have more or fewer parameters
11122 // than the number required for the corresponding operator, as
11123 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011124 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011125 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011126 if (Op != OO_Call &&
11127 ((NumParams == 1 && !CanBeUnaryOperator) ||
11128 (NumParams == 2 && !CanBeBinaryOperator) ||
11129 (NumParams < 1) || (NumParams > 2))) {
11130 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011131 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011132 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011133 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011134 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011135 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011136 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011137 assert(CanBeBinaryOperator &&
11138 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011139 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011140 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011141
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011142 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011143 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011144 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011145
Douglas Gregord69246b2008-11-17 16:14:12 +000011146 // Overloaded operators other than operator() cannot be variadic.
11147 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011148 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011149 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011150 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011151 }
11152
11153 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011154 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11155 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011156 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011157 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011158 }
11159
11160 // C++ [over.inc]p1:
11161 // The user-defined function called operator++ implements the
11162 // prefix and postfix ++ operator. If this function is a member
11163 // function with no parameters, or a non-member function with one
11164 // parameter of class or enumeration type, it defines the prefix
11165 // increment operator ++ for objects of that type. If the function
11166 // is a member function with one parameter (which shall be of type
11167 // int) or a non-member function with two parameters (the second
11168 // of which shall be of type int), it defines the postfix
11169 // increment operator ++ for objects of that type.
11170 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11171 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011172 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011173
Richard Smith538b52a2014-01-30 22:24:05 +000011174 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11175 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011176 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011177 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011178 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011179 }
11180
Douglas Gregord69246b2008-11-17 16:14:12 +000011181 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011182}
Chris Lattner3b024a32008-12-17 07:09:26 +000011183
Alexis Huntc88db062010-01-13 09:01:02 +000011184/// CheckLiteralOperatorDeclaration - Check whether the declaration
11185/// of this literal operator function is well-formed. If so, returns
11186/// false; otherwise, emits appropriate diagnostics and returns true.
11187bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011188 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011189 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11190 << FnDecl->getDeclName();
11191 return true;
11192 }
11193
Richard Smith72eebee2012-03-04 09:41:16 +000011194 if (FnDecl->isExternC()) {
11195 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11196 return true;
11197 }
11198
Alexis Huntc88db062010-01-13 09:01:02 +000011199 bool Valid = false;
11200
Richard Smithbcc22fc2012-03-09 08:00:36 +000011201 // This might be the definition of a literal operator template.
11202 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11203 // This might be a specialization of a literal operator template.
11204 if (!TpDecl)
11205 TpDecl = FnDecl->getPrimaryTemplate();
11206
Richard Smithb8b41d32013-10-07 19:57:58 +000011207 // template <char...> type operator "" name() and
11208 // template <class T, T...> type operator "" name() are the only valid
11209 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011210 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011211 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011212 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011213 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11214 if (Params->size() == 1) {
11215 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011216 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011217
Alexis Hunt7dd26172010-04-07 23:11:06 +000011218 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011219 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11220 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11221 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011222 } else if (Params->size() == 2) {
11223 TemplateTypeParmDecl *PmType =
11224 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11225 NonTypeTemplateParmDecl *PmArgs =
11226 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11227
11228 // The second template parameter must be a parameter pack with the
11229 // first template parameter as its type.
11230 if (PmType && PmArgs &&
11231 !PmType->isTemplateParameterPack() &&
11232 PmArgs->isTemplateParameterPack()) {
11233 const TemplateTypeParmType *TArgs =
11234 PmArgs->getType()->getAs<TemplateTypeParmType>();
11235 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11236 TArgs->getIndex() == PmType->getIndex()) {
11237 Valid = true;
11238 if (ActiveTemplateInstantiations.empty())
11239 Diag(FnDecl->getLocation(),
11240 diag::ext_string_literal_operator_template);
11241 }
11242 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011243 }
11244 }
Richard Smith72eebee2012-03-04 09:41:16 +000011245 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011246 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011247 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11248
Richard Smith72eebee2012-03-04 09:41:16 +000011249 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011250
Alexis Hunt079a6f72010-04-07 22:57:35 +000011251 // unsigned long long int, long double, and any character type are allowed
11252 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011253 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11254 Context.hasSameType(T, Context.LongDoubleTy) ||
11255 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011256 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011257 Context.hasSameType(T, Context.Char16Ty) ||
11258 Context.hasSameType(T, Context.Char32Ty)) {
11259 if (++Param == FnDecl->param_end())
11260 Valid = true;
11261 goto FinishedParams;
11262 }
11263
Alexis Hunt079a6f72010-04-07 22:57:35 +000011264 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011265 const PointerType *PT = T->getAs<PointerType>();
11266 if (!PT)
11267 goto FinishedParams;
11268 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011269 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011270 goto FinishedParams;
11271 T = T.getUnqualifiedType();
11272
11273 // Move on to the second parameter;
11274 ++Param;
11275
11276 // If there is no second parameter, the first must be a const char *
11277 if (Param == FnDecl->param_end()) {
11278 if (Context.hasSameType(T, Context.CharTy))
11279 Valid = true;
11280 goto FinishedParams;
11281 }
11282
11283 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11284 // are allowed as the first parameter to a two-parameter function
11285 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011286 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011287 Context.hasSameType(T, Context.Char16Ty) ||
11288 Context.hasSameType(T, Context.Char32Ty)))
11289 goto FinishedParams;
11290
11291 // The second and final parameter must be an std::size_t
11292 T = (*Param)->getType().getUnqualifiedType();
11293 if (Context.hasSameType(T, Context.getSizeType()) &&
11294 ++Param == FnDecl->param_end())
11295 Valid = true;
11296 }
11297
11298 // FIXME: This diagnostic is absolutely terrible.
11299FinishedParams:
11300 if (!Valid) {
11301 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11302 << FnDecl->getDeclName();
11303 return true;
11304 }
11305
Richard Smith768cecc2012-03-09 08:16:22 +000011306 // A parameter-declaration-clause containing a default argument is not
11307 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011308 for (auto Param : FnDecl->params()) {
11309 if (Param->hasDefaultArg()) {
11310 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011311 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011312 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011313 break;
11314 }
11315 }
11316
Richard Smith0df56f42012-03-08 02:39:21 +000011317 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011318 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11319 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011320 // C++11 [usrlit.suffix]p1:
11321 // Literal suffix identifiers that do not start with an underscore
11322 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011323 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11324 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011325 }
Richard Smith0df56f42012-03-08 02:39:21 +000011326
Alexis Huntc88db062010-01-13 09:01:02 +000011327 return false;
11328}
11329
Douglas Gregor07665a62009-01-05 19:45:36 +000011330/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11331/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011332/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11333/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011334/// the '{' brace. Otherwise, this linkage specification does not
11335/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011336Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011337 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011338 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011339 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11340 if (!Lit->isAscii()) {
11341 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11342 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011343 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011344 }
11345
11346 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011347 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011348 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011349 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011350 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011351 Language = LinkageSpecDecl::lang_cxx;
11352 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011353 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11354 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011355 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011356 }
Mike Stump11289f42009-09-09 15:08:12 +000011357
Chris Lattner438e5012008-12-17 07:13:27 +000011358 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011359
Richard Smith4ee696d2014-02-17 23:25:27 +000011360 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11361 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011362 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011363 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011364 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011365 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011366}
11367
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011368/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011369/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11370/// valid, it's the position of the closing '}' brace in a linkage
11371/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011372Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011373 Decl *LinkageSpec,
11374 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011375 if (RBraceLoc.isValid()) {
11376 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11377 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011378 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011379 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011380 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011381}
11382
Michael Han84324352013-02-22 17:15:32 +000011383Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11384 AttributeList *AttrList,
11385 SourceLocation SemiLoc) {
11386 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11387 // Attribute declarations appertain to empty declaration so we handle
11388 // them here.
11389 if (AttrList)
11390 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011391
Michael Han84324352013-02-22 17:15:32 +000011392 CurContext->addDecl(ED);
11393 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011394}
11395
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011396/// \brief Perform semantic analysis for the variable declaration that
11397/// occurs within a C++ catch clause, returning the newly-created
11398/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011399VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011400 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011401 SourceLocation StartLoc,
11402 SourceLocation Loc,
11403 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011404 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011405 QualType ExDeclType = TInfo->getType();
11406
Sebastian Redl54c04d42008-12-22 19:15:10 +000011407 // Arrays and functions decay.
11408 if (ExDeclType->isArrayType())
11409 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11410 else if (ExDeclType->isFunctionType())
11411 ExDeclType = Context.getPointerType(ExDeclType);
11412
11413 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11414 // The exception-declaration shall not denote a pointer or reference to an
11415 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011416 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011417 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011418 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011419 Invalid = true;
11420 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011421
Sebastian Redl54c04d42008-12-22 19:15:10 +000011422 QualType BaseType = ExDeclType;
11423 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011424 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011425 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011426 BaseType = Ptr->getPointeeType();
11427 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011428 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011429 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011430 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011431 BaseType = Ref->getPointeeType();
11432 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011433 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011434 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011435 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011436 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011437 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011438
Mike Stump11289f42009-09-09 15:08:12 +000011439 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011440 RequireNonAbstractType(Loc, ExDeclType,
11441 diag::err_abstract_type_in_decl,
11442 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011443 Invalid = true;
11444
John McCall2ca705e2010-07-24 00:37:23 +000011445 // Only the non-fragile NeXT runtime currently supports C++ catches
11446 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011447 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011448 QualType T = ExDeclType;
11449 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11450 T = RT->getPointeeType();
11451
11452 if (T->isObjCObjectType()) {
11453 Diag(Loc, diag::err_objc_object_catch);
11454 Invalid = true;
11455 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011456 // FIXME: should this be a test for macosx-fragile specifically?
11457 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011458 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011459 }
11460 }
11461
Abramo Bagnaradff19302011-03-08 08:55:46 +000011462 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011463 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011464 ExDecl->setExceptionVariable(true);
11465
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011466 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011467 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011468 Invalid = true;
11469
Douglas Gregor750734c2011-07-06 18:14:43 +000011470 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011471 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011472 // Insulate this from anything else we might currently be parsing.
11473 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11474
Douglas Gregor6de584c2010-03-05 23:38:39 +000011475 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011476 // The object declared in an exception-declaration or, if the
11477 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011478 // copy-initialized (8.5) from the exception object. [...]
11479 // The object is destroyed when the handler exits, after the destruction
11480 // of any automatic objects initialized within the handler.
11481 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011482 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011483 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011484 QualType initType = ExDeclType;
11485
11486 InitializedEntity entity =
11487 InitializedEntity::InitializeVariable(ExDecl);
11488 InitializationKind initKind =
11489 InitializationKind::CreateCopy(Loc, SourceLocation());
11490
11491 Expr *opaqueValue =
11492 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011493 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11494 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011495 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011496 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011497 else {
11498 // If the constructor used was non-trivial, set this as the
11499 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011500 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011501 if (!construct->getConstructor()->isTrivial()) {
11502 Expr *init = MaybeCreateExprWithCleanups(construct);
11503 ExDecl->setInit(init);
11504 }
11505
11506 // And make sure it's destructable.
11507 FinalizeVarWithDestructor(ExDecl, recordType);
11508 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011509 }
11510 }
11511
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011512 if (Invalid)
11513 ExDecl->setInvalidDecl();
11514
11515 return ExDecl;
11516}
11517
11518/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11519/// handler.
John McCall48871652010-08-21 09:40:31 +000011520Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011521 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011522 bool Invalid = D.isInvalidType();
11523
11524 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011525 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11526 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011527 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11528 D.getIdentifierLoc());
11529 Invalid = true;
11530 }
11531
Sebastian Redl54c04d42008-12-22 19:15:10 +000011532 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011533 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011534 LookupOrdinaryName,
11535 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011536 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011537 // it contains any previous declaration, except for function parameters in
11538 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011539 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011540 if (isDeclInScope(PrevDecl, CurContext, S)) {
11541 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11542 << D.getIdentifier();
11543 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11544 Invalid = true;
11545 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011546 // Maybe we will complain about the shadowed template parameter.
11547 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011548 }
11549
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011550 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011551 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11552 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011553 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011554 }
11555
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011556 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011557 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011558 D.getIdentifierLoc(),
11559 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011560 if (Invalid)
11561 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011562
Sebastian Redl54c04d42008-12-22 19:15:10 +000011563 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011564 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011565 PushOnScopeChains(ExDecl, S);
11566 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011567 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011568
Douglas Gregor758a8692009-06-17 21:51:59 +000011569 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011570 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011571}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011572
Abramo Bagnaraea947882011-03-08 16:41:52 +000011573Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011574 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011575 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011576 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011577 StringLiteral *AssertMessage =
11578 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011579
Richard Smithded9c2e2012-07-11 22:37:56 +000011580 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011581 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011582
11583 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11584 AssertMessage, RParenLoc, false);
11585}
11586
11587Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11588 Expr *AssertExpr,
11589 StringLiteral *AssertMessage,
11590 SourceLocation RParenLoc,
11591 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011592 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011593 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11594 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011595 // In a static_assert-declaration, the constant-expression shall be a
11596 // constant expression that can be contextually converted to bool.
11597 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11598 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011599 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011600
Richard Smith902ca212011-12-14 23:32:26 +000011601 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011602 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011603 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011604 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011605 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011606
Richard Smithded9c2e2012-07-11 22:37:56 +000011607 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011608 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011609 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011610 if (AssertMessage)
11611 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011612 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011613 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011614 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011615 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011616 }
Mike Stump11289f42009-09-09 15:08:12 +000011617
Abramo Bagnaraea947882011-03-08 16:41:52 +000011618 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011619 AssertExpr, AssertMessage, RParenLoc,
11620 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011621
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011622 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011623 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011624}
Sebastian Redlf769df52009-03-24 22:27:57 +000011625
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011626/// \brief Perform semantic analysis of the given friend type declaration.
11627///
11628/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011629FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011630 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011631 TypeSourceInfo *TSInfo) {
11632 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11633
11634 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011635 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011636
Richard Smithc8239732011-10-18 21:39:00 +000011637 // C++03 [class.friend]p2:
11638 // An elaborated-type-specifier shall be used in a friend declaration
11639 // for a class.*
11640 //
11641 // * The class-key of the elaborated-type-specifier is required.
11642 if (!ActiveTemplateInstantiations.empty()) {
11643 // Do not complain about the form of friend template types during
11644 // template instantiation; we will already have complained when the
11645 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011646 } else {
11647 if (!T->isElaboratedTypeSpecifier()) {
11648 // If we evaluated the type to a record type, suggest putting
11649 // a tag in front.
11650 if (const RecordType *RT = T->getAs<RecordType>()) {
11651 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011652
11653 SmallString<16> InsertionText(" ");
11654 InsertionText += RD->getKindName();
11655
Nick Lewycky36722d22013-02-06 05:59:33 +000011656 Diag(TypeRange.getBegin(),
11657 getLangOpts().CPlusPlus11 ?
11658 diag::warn_cxx98_compat_unelaborated_friend_type :
11659 diag::ext_unelaborated_friend_type)
11660 << (unsigned) RD->getTagKind()
11661 << T
11662 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11663 InsertionText);
11664 } else {
11665 Diag(FriendLoc,
11666 getLangOpts().CPlusPlus11 ?
11667 diag::warn_cxx98_compat_nonclass_type_friend :
11668 diag::ext_nonclass_type_friend)
11669 << T
11670 << TypeRange;
11671 }
11672 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011673 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011674 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011675 diag::warn_cxx98_compat_enum_friend :
11676 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011677 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011678 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011679 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011680
Nick Lewycky36722d22013-02-06 05:59:33 +000011681 // C++11 [class.friend]p3:
11682 // A friend declaration that does not declare a function shall have one
11683 // of the following forms:
11684 // friend elaborated-type-specifier ;
11685 // friend simple-type-specifier ;
11686 // friend typename-specifier ;
11687 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11688 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11689 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011690
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011691 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011692 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011693 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011694 return FriendDecl::Create(Context, CurContext,
11695 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11696 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011697}
11698
John McCallace48cd2010-10-19 01:40:49 +000011699/// Handle a friend tag declaration where the scope specifier was
11700/// templated.
11701Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11702 unsigned TagSpec, SourceLocation TagLoc,
11703 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011704 IdentifierInfo *Name,
11705 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011706 AttributeList *Attr,
11707 MultiTemplateParamsArg TempParamLists) {
11708 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11709
11710 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011711 bool Invalid = false;
11712
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011713 if (TemplateParameterList *TemplateParams =
11714 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011715 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011716 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011717 if (TemplateParams->size() > 0) {
11718 // This is a declaration of a class template.
11719 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011720 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011721
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011722 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11723 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011724 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011725 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011726 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011727 } else {
11728 // The "template<>" header is extraneous.
11729 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11730 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11731 isExplicitSpecialization = true;
11732 }
11733 }
11734
Craig Topperc3ec1492014-05-26 06:22:03 +000011735 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011736
John McCallace48cd2010-10-19 01:40:49 +000011737 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011738 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011739 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011740 isAllExplicitSpecializations = false;
11741 break;
11742 }
11743 }
11744
11745 // FIXME: don't ignore attributes.
11746
11747 // If it's explicit specializations all the way down, just forget
11748 // about the template header and build an appropriate non-templated
11749 // friend. TODO: for source fidelity, remember the headers.
11750 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011751 if (SS.isEmpty()) {
11752 bool Owned = false;
11753 bool IsDependent = false;
11754 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011755 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011756 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011757 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011758 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011759 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011760 /*UnderlyingType=*/TypeResult(),
11761 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011762 }
Richard Smith649c7b062014-01-08 00:56:48 +000011763
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011764 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011765 ElaboratedTypeKeyword Keyword
11766 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011767 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011768 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011769 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011770 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011771
11772 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11773 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011774 DependentNameTypeLoc TL =
11775 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011776 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011777 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011778 TL.setNameLoc(NameLoc);
11779 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011780 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011781 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011782 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011783 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011784 }
11785
11786 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011787 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011788 Friend->setAccess(AS_public);
11789 CurContext->addDecl(Friend);
11790 return Friend;
11791 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011792
11793 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11794
11795
John McCallace48cd2010-10-19 01:40:49 +000011796
11797 // Handle the case of a templated-scope friend class. e.g.
11798 // template <class T> class A<T>::B;
11799 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011800 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11801 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011802 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11803 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11804 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011805 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011806 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011807 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011808 TL.setNameLoc(NameLoc);
11809
11810 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011811 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011812 Friend->setAccess(AS_public);
11813 Friend->setUnsupportedFriend(true);
11814 CurContext->addDecl(Friend);
11815 return Friend;
11816}
11817
11818
John McCall11083da2009-09-16 22:47:08 +000011819/// Handle a friend type declaration. This works in tandem with
11820/// ActOnTag.
11821///
11822/// Notes on friend class templates:
11823///
11824/// We generally treat friend class declarations as if they were
11825/// declaring a class. So, for example, the elaborated type specifier
11826/// in a friend declaration is required to obey the restrictions of a
11827/// class-head (i.e. no typedefs in the scope chain), template
11828/// parameters are required to match up with simple template-ids, &c.
11829/// However, unlike when declaring a template specialization, it's
11830/// okay to refer to a template specialization without an empty
11831/// template parameter declaration, e.g.
11832/// friend class A<T>::B<unsigned>;
11833/// We permit this as a special case; if there are any template
11834/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011835/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011836Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011837 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011838 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011839
11840 assert(DS.isFriendSpecified());
11841 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11842
John McCall11083da2009-09-16 22:47:08 +000011843 // Try to convert the decl specifier to a type. This works for
11844 // friend templates because ActOnTag never produces a ClassTemplateDecl
11845 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011846 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011847 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11848 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011849 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011850 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011851
Douglas Gregor6c110f32010-12-16 01:14:37 +000011852 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011853 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011854
John McCall11083da2009-09-16 22:47:08 +000011855 // This is definitely an error in C++98. It's probably meant to
11856 // be forbidden in C++0x, too, but the specification is just
11857 // poorly written.
11858 //
11859 // The problem is with declarations like the following:
11860 // template <T> friend A<T>::foo;
11861 // where deciding whether a class C is a friend or not now hinges
11862 // on whether there exists an instantiation of A that causes
11863 // 'foo' to equal C. There are restrictions on class-heads
11864 // (which we declare (by fiat) elaborated friend declarations to
11865 // be) that makes this tractable.
11866 //
11867 // FIXME: handle "template <> friend class A<T>;", which
11868 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011869 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011870 Diag(Loc, diag::err_tagless_friend_type_template)
11871 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011872 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011873 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011874
John McCallaa74a0c2009-08-28 07:59:38 +000011875 // C++98 [class.friend]p1: A friend of a class is a function
11876 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011877 // This is fixed in DR77, which just barely didn't make the C++03
11878 // deadline. It's also a very silly restriction that seriously
11879 // affects inner classes and which nobody else seems to implement;
11880 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011881 //
11882 // But note that we could warn about it: it's always useless to
11883 // friend one of your own members (it's not, however, worthless to
11884 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011885
John McCall11083da2009-09-16 22:47:08 +000011886 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011887 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011888 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011889 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011890 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011891 TSI,
John McCall11083da2009-09-16 22:47:08 +000011892 DS.getFriendSpecLoc());
11893 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011894 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011895
11896 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011897 return nullptr;
11898
John McCall11083da2009-09-16 22:47:08 +000011899 D->setAccess(AS_public);
11900 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011901
John McCall48871652010-08-21 09:40:31 +000011902 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011903}
11904
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011905NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11906 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011907 const DeclSpec &DS = D.getDeclSpec();
11908
11909 assert(DS.isFriendSpecified());
11910 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11911
11912 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011913 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011914
11915 // C++ [class.friend]p1
11916 // A friend of a class is a function or class....
11917 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011918 // It *doesn't* see through dependent types, which is correct
11919 // according to [temp.arg.type]p3:
11920 // If a declaration acquires a function type through a
11921 // type dependent on a template-parameter and this causes
11922 // a declaration that does not use the syntactic form of a
11923 // function declarator to have a function type, the program
11924 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011925 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011926 Diag(Loc, diag::err_unexpected_friend);
11927
11928 // It might be worthwhile to try to recover by creating an
11929 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011930 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011931 }
11932
11933 // C++ [namespace.memdef]p3
11934 // - If a friend declaration in a non-local class first declares a
11935 // class or function, the friend class or function is a member
11936 // of the innermost enclosing namespace.
11937 // - The name of the friend is not found by simple name lookup
11938 // until a matching declaration is provided in that namespace
11939 // scope (either before or after the class declaration granting
11940 // friendship).
11941 // - If a friend function is called, its name may be found by the
11942 // name lookup that considers functions from namespaces and
11943 // classes associated with the types of the function arguments.
11944 // - When looking for a prior declaration of a class or a function
11945 // declared as a friend, scopes outside the innermost enclosing
11946 // namespace scope are not considered.
11947
John McCallde3fd222010-10-12 23:13:28 +000011948 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011949 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11950 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011951 assert(Name);
11952
Douglas Gregor6c110f32010-12-16 01:14:37 +000011953 // Check for unexpanded parameter packs.
11954 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11955 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11956 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011957 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011958
John McCall07e91c02009-08-06 02:15:43 +000011959 // The context we found the declaration in, or in which we should
11960 // create the declaration.
11961 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011962 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011963 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011964 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011965
Richard Smith114394f2013-08-09 04:35:01 +000011966 // There are five cases here.
11967 // - There's no scope specifier and we're in a local class. Only look
11968 // for functions declared in the immediately-enclosing block scope.
11969 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011970 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011971 if ((SS.isInvalid() || !SS.isSet()) &&
11972 (FunctionContainingLocalClass =
11973 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11974 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011975 // If a friend declaration appears in a local class and the name
11976 // specified is an unqualified name, a prior declaration is
11977 // looked up without considering scopes that are outside the
11978 // innermost enclosing non-class scope. For a friend function
11979 // declaration, if there is no prior declaration, the program is
11980 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011981
11982 // Find the innermost enclosing non-class scope. This is the block
11983 // scope containing the local class definition (or for a nested class,
11984 // the outer local class).
11985 DCScope = S->getFnParent();
11986
11987 // Look up the function name in the scope.
11988 Previous.clear(LookupLocalFriendName);
11989 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11990
11991 if (!Previous.empty()) {
11992 // All possible previous declarations must have the same context:
11993 // either they were declared at block scope or they are members of
11994 // one of the enclosing local classes.
11995 DC = Previous.getRepresentativeDecl()->getDeclContext();
11996 } else {
11997 // This is ill-formed, but provide the context that we would have
11998 // declared the function in, if we were permitted to, for error recovery.
11999 DC = FunctionContainingLocalClass;
12000 }
Richard Smith541b38b2013-09-20 01:15:31 +000012001 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012002
12003 // C++ [class.friend]p6:
12004 // A function can be defined in a friend declaration of a class if and
12005 // only if the class is a non-local class (9.8), the function name is
12006 // unqualified, and the function has namespace scope.
12007 if (D.isFunctionDefinition()) {
12008 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12009 }
12010
12011 // - There's no scope specifier, in which case we just go to the
12012 // appropriate scope and look for a function or function template
12013 // there as appropriate.
12014 } else if (SS.isInvalid() || !SS.isSet()) {
12015 // C++11 [namespace.memdef]p3:
12016 // If the name in a friend declaration is neither qualified nor
12017 // a template-id and the declaration is a function or an
12018 // elaborated-type-specifier, the lookup to determine whether
12019 // the entity has been previously declared shall not consider
12020 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012021 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012022
John McCallf7cfb222010-10-13 05:45:15 +000012023 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012024 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012025
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012026 // Skip class contexts. If someone can cite chapter and verse
12027 // for this behavior, that would be nice --- it's what GCC and
12028 // EDG do, and it seems like a reasonable intent, but the spec
12029 // really only says that checks for unqualified existing
12030 // declarations should stop at the nearest enclosing namespace,
12031 // not that they should only consider the nearest enclosing
12032 // namespace.
12033 while (DC->isRecord())
12034 DC = DC->getParent();
12035
12036 DeclContext *LookupDC = DC;
12037 while (LookupDC->isTransparentContext())
12038 LookupDC = LookupDC->getParent();
12039
12040 while (true) {
12041 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012042
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012043 if (!Previous.empty()) {
12044 DC = LookupDC;
12045 break;
John McCallf4776592010-10-14 22:22:28 +000012046 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012047
12048 if (isTemplateId) {
12049 if (isa<TranslationUnitDecl>(LookupDC)) break;
12050 } else {
12051 if (LookupDC->isFileContext()) break;
12052 }
12053 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012054 }
12055
John McCallccbc0322010-10-13 06:22:15 +000012056 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012057
John McCallde3fd222010-10-12 23:13:28 +000012058 // - There's a non-dependent scope specifier, in which case we
12059 // compute it and do a previous lookup there for a function
12060 // or function template.
12061 } else if (!SS.getScopeRep()->isDependent()) {
12062 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012063 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012064
Craig Topperc3ec1492014-05-26 06:22:03 +000012065 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012066
12067 LookupQualifiedName(Previous, DC);
12068
12069 // Ignore things found implicitly in the wrong scope.
12070 // TODO: better diagnostics for this case. Suggesting the right
12071 // qualified scope would be nice...
12072 LookupResult::Filter F = Previous.makeFilter();
12073 while (F.hasNext()) {
12074 NamedDecl *D = F.next();
12075 if (!DC->InEnclosingNamespaceSetOf(
12076 D->getDeclContext()->getRedeclContext()))
12077 F.erase();
12078 }
12079 F.done();
12080
12081 if (Previous.empty()) {
12082 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012083 Diag(Loc, diag::err_qualified_friend_not_found)
12084 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012085 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012086 }
12087
12088 // C++ [class.friend]p1: A friend of a class is a function or
12089 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012090 if (DC->Equals(CurContext))
12091 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012092 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012093 diag::warn_cxx98_compat_friend_is_member :
12094 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012095
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012096 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012097 // C++ [class.friend]p6:
12098 // A function can be defined in a friend declaration of a class if and
12099 // only if the class is a non-local class (9.8), the function name is
12100 // unqualified, and the function has namespace scope.
12101 SemaDiagnosticBuilder DB
12102 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12103
12104 DB << SS.getScopeRep();
12105 if (DC->isFileContext())
12106 DB << FixItHint::CreateRemoval(SS.getRange());
12107 SS.clear();
12108 }
John McCallde3fd222010-10-12 23:13:28 +000012109
12110 // - There's a scope specifier that does not match any template
12111 // parameter lists, in which case we use some arbitrary context,
12112 // create a method or method template, and wait for instantiation.
12113 // - There's a scope specifier that does match some template
12114 // parameter lists, which we don't handle right now.
12115 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012116 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012117 // C++ [class.friend]p6:
12118 // A function can be defined in a friend declaration of a class if and
12119 // only if the class is a non-local class (9.8), the function name is
12120 // unqualified, and the function has namespace scope.
12121 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12122 << SS.getScopeRep();
12123 }
12124
John McCallde3fd222010-10-12 23:13:28 +000012125 DC = CurContext;
12126 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012127 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012128
John McCallf7cfb222010-10-13 05:45:15 +000012129 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012130 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012131 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12132 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12133 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012134 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012135 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12136 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012137 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012138 }
John McCall07e91c02009-08-06 02:15:43 +000012139 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012140
Douglas Gregordd847ba2011-11-03 16:37:14 +000012141 // FIXME: This is an egregious hack to cope with cases where the scope stack
12142 // does not contain the declaration context, i.e., in an out-of-line
12143 // definition of a class.
12144 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12145 if (!DCScope) {
12146 FakeDCScope.setEntity(DC);
12147 DCScope = &FakeDCScope;
12148 }
Richard Smith114394f2013-08-09 04:35:01 +000012149
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012150 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012151 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012152 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012153 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012154
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012155 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012156
Richard Smith114394f2013-08-09 04:35:01 +000012157 // If we performed typo correction, we might have added a scope specifier
12158 // and changed the decl context.
12159 DC = ND->getDeclContext();
12160
John McCall759e32b2009-08-31 22:39:49 +000012161 // Add the function declaration to the appropriate lookup tables,
12162 // adjusting the redeclarations list as necessary. We don't
12163 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012164 //
John McCall759e32b2009-08-31 22:39:49 +000012165 // Also update the scope-based lookup if the target context's
12166 // lookup context is in lexical scope.
12167 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012168 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012169 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012170 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012171 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012172 }
John McCallaa74a0c2009-08-28 07:59:38 +000012173
12174 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012175 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012176 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012177 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012178 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012179
John McCalla0a96892012-08-10 03:15:35 +000012180 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012181 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012182 } else {
12183 if (DC->isRecord()) CheckFriendAccess(ND);
12184
John McCall2c2eb122010-10-16 06:59:13 +000012185 FunctionDecl *FD;
12186 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12187 FD = FTD->getTemplatedDecl();
12188 else
12189 FD = cast<FunctionDecl>(ND);
12190
David Majnemer502b0ed2013-06-25 23:09:30 +000012191 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12192 // default argument expression, that declaration shall be a definition
12193 // and shall be the only declaration of the function or function
12194 // template in the translation unit.
12195 if (functionDeclHasDefaultArgument(FD)) {
12196 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12197 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12198 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12199 } else if (!D.isFunctionDefinition())
12200 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12201 }
12202
John McCall2c2eb122010-10-16 06:59:13 +000012203 // Mark templated-scope function declarations as unsupported.
12204 if (FD->getNumTemplateParameterLists())
12205 FrD->setUnsupportedFriend(true);
12206 }
John McCallde3fd222010-10-12 23:13:28 +000012207
John McCall48871652010-08-21 09:40:31 +000012208 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012209}
12210
John McCall48871652010-08-21 09:40:31 +000012211void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12212 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012213
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012214 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012215 if (!Fn) {
12216 Diag(DelLoc, diag::err_deleted_non_function);
12217 return;
12218 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012219
Douglas Gregorec9fd132012-01-14 16:38:05 +000012220 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012221 // Don't consider the implicit declaration we generate for explicit
12222 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012223 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12224 Prev->getPreviousDecl()) &&
12225 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012226 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012227 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12228 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12229 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012230 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012231 // If the declaration wasn't the first, we delete the function anyway for
12232 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012233 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012234 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012235
Nico Rieck9de0a572014-05-29 16:51:19 +000012236 // dllimport/dllexport cannot be deleted.
12237 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12238 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12239 Fn->setInvalidDecl();
12240 }
12241
Richard Smithb4d2a152013-04-02 19:38:47 +000012242 if (Fn->isDeleted())
12243 return;
12244
12245 // See if we're deleting a function which is already known to override a
12246 // non-deleted virtual function.
12247 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12248 bool IssuedDiagnostic = false;
12249 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12250 E = MD->end_overridden_methods();
12251 I != E; ++I) {
12252 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12253 if (!IssuedDiagnostic) {
12254 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12255 IssuedDiagnostic = true;
12256 }
12257 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12258 }
12259 }
12260 }
12261
Richard Smithb63b6ee2014-01-22 01:43:19 +000012262 // C++11 [basic.start.main]p3:
12263 // A program that defines main as deleted [...] is ill-formed.
12264 if (Fn->isMain())
12265 Diag(DelLoc, diag::err_deleted_main);
12266
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012267 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012268}
Sebastian Redl4c018662009-04-27 21:33:24 +000012269
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012270void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012271 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012272
12273 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012274 if (MD->getParent()->isDependentType()) {
12275 MD->setDefaulted();
12276 MD->setExplicitlyDefaulted();
12277 return;
12278 }
12279
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012280 CXXSpecialMember Member = getSpecialMember(MD);
12281 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012282 if (!MD->isInvalidDecl())
12283 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012284 return;
12285 }
12286
12287 MD->setDefaulted();
12288 MD->setExplicitlyDefaulted();
12289
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012290 // If this definition appears within the record, do the checking when
12291 // the record is complete.
12292 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012293 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012294 // Find the uninstantiated declaration that actually had the '= default'
12295 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012296 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012297
Richard Smith3901dfe2013-03-27 00:22:47 +000012298 // If the method was defaulted on its first declaration, we will have
12299 // already performed the checking in CheckCompletedCXXClass. Such a
12300 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012301 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012302 return;
12303
Richard Smithd3b5c9082012-07-27 04:22:15 +000012304 CheckExplicitlyDefaultedSpecialMember(MD);
12305
Richard Smithbd305122012-12-11 01:14:52 +000012306 // The exception specification is needed because we are defining the
12307 // function.
12308 ResolveExceptionSpec(DefaultLoc,
12309 MD->getType()->castAs<FunctionProtoType>());
12310
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012311 if (MD->isInvalidDecl())
12312 return;
12313
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012314 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012315 case CXXDefaultConstructor:
12316 DefineImplicitDefaultConstructor(DefaultLoc,
12317 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012318 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012319 case CXXCopyConstructor:
12320 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012321 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012322 case CXXCopyAssignment:
12323 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012324 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012325 case CXXDestructor:
12326 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012327 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012328 case CXXMoveConstructor:
12329 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012330 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012331 case CXXMoveAssignment:
12332 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012333 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012334 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012335 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012336 }
12337 } else {
12338 Diag(DefaultLoc, diag::err_default_special_members);
12339 }
12340}
12341
Sebastian Redl4c018662009-04-27 21:33:24 +000012342static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012343 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012344 Stmt *SubStmt = *CI;
12345 if (!SubStmt)
12346 continue;
12347 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012348 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012349 diag::err_return_in_constructor_handler);
12350 if (!isa<Expr>(SubStmt))
12351 SearchForReturnInStmt(Self, SubStmt);
12352 }
12353}
12354
12355void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12356 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12357 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12358 SearchForReturnInStmt(*this, Handler);
12359 }
12360}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012361
David Blaikie68f71a32013-01-18 23:03:15 +000012362bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012363 const CXXMethodDecl *Old) {
12364 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12365 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12366
12367 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12368
12369 // If the calling conventions match, everything is fine
12370 if (NewCC == OldCC)
12371 return false;
12372
Hans Wennborg2545efe2013-12-11 17:42:11 +000012373 // If the calling conventions mismatch because the new function is static,
12374 // suppress the calling convention mismatch error; the error about static
12375 // function override (err_static_overrides_virtual from
12376 // Sema::CheckFunctionDeclaration) is more clear.
12377 if (New->getStorageClass() == SC_Static)
12378 return false;
12379
Reid Kleckner78af0702013-08-27 23:08:25 +000012380 Diag(New->getLocation(),
12381 diag::err_conflicting_overriding_cc_attributes)
12382 << New->getDeclName() << New->getType() << Old->getType();
12383 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12384 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012385}
12386
Mike Stump11289f42009-09-09 15:08:12 +000012387bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012388 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012389 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12390 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012391
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012392 if (Context.hasSameType(NewTy, OldTy) ||
12393 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012394 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012395
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012396 // Check if the return types are covariant
12397 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012398
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012399 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012400 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12401 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012402 NewClassTy = NewPT->getPointeeType();
12403 OldClassTy = OldPT->getPointeeType();
12404 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012405 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12406 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12407 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12408 NewClassTy = NewRT->getPointeeType();
12409 OldClassTy = OldRT->getPointeeType();
12410 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012411 }
12412 }
Mike Stump11289f42009-09-09 15:08:12 +000012413
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012414 // The return types aren't either both pointers or references to a class type.
12415 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012416 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012417 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012418 << New->getDeclName() << NewTy << OldTy
12419 << New->getReturnTypeSourceRange();
12420 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12421 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012422
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012423 return true;
12424 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012425
Anders Carlssone60365b2009-12-31 18:34:24 +000012426 // C++ [class.virtual]p6:
12427 // If the return type of D::f differs from the return type of B::f, the
12428 // class type in the return type of D::f shall be complete at the point of
12429 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012430 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12431 if (!RT->isBeingDefined() &&
12432 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012433 diag::err_covariant_return_incomplete,
12434 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012435 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012436 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012437
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012438 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012439 // Check if the new class derives from the old class.
12440 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012441 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12442 << New->getDeclName() << NewTy << OldTy
12443 << New->getReturnTypeSourceRange();
12444 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12445 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012446 return true;
12447 }
Mike Stump11289f42009-09-09 15:08:12 +000012448
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012449 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012450 if (CheckDerivedToBaseConversion(
12451 NewClassTy, OldClassTy,
12452 diag::err_covariant_return_inaccessible_base,
12453 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12454 New->getLocation(), New->getReturnTypeSourceRange(),
12455 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012456 // FIXME: this note won't trigger for delayed access control
12457 // diagnostics, and it's impossible to get an undelayed error
12458 // here from access control during the original parse because
12459 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012460 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12461 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012462 return true;
12463 }
12464 }
Mike Stump11289f42009-09-09 15:08:12 +000012465
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012466 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012467 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012468 Diag(New->getLocation(),
12469 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012470 << New->getDeclName() << NewTy << OldTy
12471 << New->getReturnTypeSourceRange();
12472 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12473 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012474 return true;
12475 };
Mike Stump11289f42009-09-09 15:08:12 +000012476
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012477
12478 // The new class type must have the same or less qualifiers as the old type.
12479 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12480 Diag(New->getLocation(),
12481 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012482 << New->getDeclName() << NewTy << OldTy
12483 << New->getReturnTypeSourceRange();
12484 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12485 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012486 return true;
12487 };
Mike Stump11289f42009-09-09 15:08:12 +000012488
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012489 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012490}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012491
Douglas Gregor21920e372009-12-01 17:24:26 +000012492/// \brief Mark the given method pure.
12493///
12494/// \param Method the method to be marked pure.
12495///
12496/// \param InitRange the source range that covers the "0" initializer.
12497bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012498 SourceLocation EndLoc = InitRange.getEnd();
12499 if (EndLoc.isValid())
12500 Method->setRangeEnd(EndLoc);
12501
Douglas Gregor21920e372009-12-01 17:24:26 +000012502 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12503 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012504 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012505 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012506
12507 if (!Method->isInvalidDecl())
12508 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12509 << Method->getDeclName() << InitRange;
12510 return true;
12511}
12512
Douglas Gregor926410d2012-02-21 02:22:07 +000012513/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012514static bool isStaticDataMember(const Decl *D) {
12515 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12516 return Var->isStaticDataMember();
12517
12518 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012519}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012520
John McCall1f4ee7b2009-12-19 09:28:58 +000012521/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12522/// an initializer for the out-of-line declaration 'Dcl'. The scope
12523/// is a fresh scope pushed for just this purpose.
12524///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012525/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12526/// static data member of class X, names should be looked up in the scope of
12527/// class X.
John McCall48871652010-08-21 09:40:31 +000012528void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012529 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012530 if (!D || D->isInvalidDecl())
12531 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012532
Richard Smitha2302242013-12-05 07:51:02 +000012533 // We will always have a nested name specifier here, but this declaration
12534 // might not be out of line if the specifier names the current namespace:
12535 // extern int n;
12536 // int ::n = 0;
12537 if (D->isOutOfLine())
12538 EnterDeclaratorContext(S, D->getDeclContext());
12539
Douglas Gregor926410d2012-02-21 02:22:07 +000012540 // If we are parsing the initializer for a static data member, push a
12541 // new expression evaluation context that is associated with this static
12542 // data member.
12543 if (isStaticDataMember(D))
12544 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012545}
12546
12547/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012548/// initializer for the out-of-line declaration 'D'.
12549void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012550 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012551 if (!D || D->isInvalidDecl())
12552 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012553
Douglas Gregor926410d2012-02-21 02:22:07 +000012554 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012555 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012556
Richard Smitha2302242013-12-05 07:51:02 +000012557 if (D->isOutOfLine())
12558 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012559}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012560
12561/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12562/// C++ if/switch/while/for statement.
12563/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012564DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012565 // C++ 6.4p2:
12566 // The declarator shall not specify a function or an array.
12567 // The type-specifier-seq shall not contain typedef and shall not declare a
12568 // new class or enumeration.
12569 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12570 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012571
12572 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012573 if (!Dcl)
12574 return true;
12575
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012576 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12577 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012578 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012579 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012580 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012581
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012582 return Dcl;
12583}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012584
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012585void Sema::LoadExternalVTableUses() {
12586 if (!ExternalSource)
12587 return;
12588
12589 SmallVector<ExternalVTableUse, 4> VTables;
12590 ExternalSource->ReadUsedVTables(VTables);
12591 SmallVector<VTableUse, 4> NewUses;
12592 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12593 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12594 = VTablesUsed.find(VTables[I].Record);
12595 // Even if a definition wasn't required before, it may be required now.
12596 if (Pos != VTablesUsed.end()) {
12597 if (!Pos->second && VTables[I].DefinitionRequired)
12598 Pos->second = true;
12599 continue;
12600 }
12601
12602 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12603 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12604 }
12605
12606 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12607}
12608
Douglas Gregor88d292c2010-05-13 16:44:06 +000012609void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12610 bool DefinitionRequired) {
12611 // Ignore any vtable uses in unevaluated operands or for classes that do
12612 // not have a vtable.
12613 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012614 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012615 return;
12616
Douglas Gregor88d292c2010-05-13 16:44:06 +000012617 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012618 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012619 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12620 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12621 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12622 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012623 // If we already had an entry, check to see if we are promoting this vtable
12624 // to required a definition. If so, we need to reappend to the VTableUses
12625 // list, since we may have already processed the first entry.
12626 if (DefinitionRequired && !Pos.first->second) {
12627 Pos.first->second = true;
12628 } else {
12629 // Otherwise, we can early exit.
12630 return;
12631 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012632 } else {
12633 // The Microsoft ABI requires that we perform the destructor body
12634 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12635 // the deleting destructor is emitted with the vtable, not with the
12636 // destructor definition as in the Itanium ABI.
12637 // If it has a definition, we do the check at that point instead.
12638 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12639 Class->hasUserDeclaredDestructor() &&
12640 !Class->getDestructor()->isDefined() &&
12641 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012642 CXXDestructorDecl *DD = Class->getDestructor();
12643 ContextRAII SavedContext(*this, DD);
12644 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012645 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012646 }
12647
12648 // Local classes need to have their virtual members marked
12649 // immediately. For all other classes, we mark their virtual members
12650 // at the end of the translation unit.
12651 if (Class->isLocalClass())
12652 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012653 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012654 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012655}
12656
Douglas Gregor88d292c2010-05-13 16:44:06 +000012657bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012658 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012659 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012660 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012661
Douglas Gregor88d292c2010-05-13 16:44:06 +000012662 // Note: The VTableUses vector could grow as a result of marking
12663 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012664 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012665 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012666 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012667 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012668 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012669 if (!Class)
12670 continue;
12671
12672 SourceLocation Loc = VTableUses[I].second;
12673
Richard Smithd3b5c9082012-07-27 04:22:15 +000012674 bool DefineVTable = true;
12675
Douglas Gregor88d292c2010-05-13 16:44:06 +000012676 // If this class has a key function, but that key function is
12677 // defined in another translation unit, we don't need to emit the
12678 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012679 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012680 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012681 // The key function is in another translation unit.
12682 DefineVTable = false;
12683 TemplateSpecializationKind TSK =
12684 KeyFunction->getTemplateSpecializationKind();
12685 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12686 TSK != TSK_ImplicitInstantiation &&
12687 "Instantiations don't have key functions");
12688 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012689 } else if (!KeyFunction) {
12690 // If we have a class with no key function that is the subject
12691 // of an explicit instantiation declaration, suppress the
12692 // vtable; it will live with the explicit instantiation
12693 // definition.
12694 bool IsExplicitInstantiationDeclaration
12695 = Class->getTemplateSpecializationKind()
12696 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012697 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012698 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012699 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012700 if (TSK == TSK_ExplicitInstantiationDeclaration)
12701 IsExplicitInstantiationDeclaration = true;
12702 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12703 IsExplicitInstantiationDeclaration = false;
12704 break;
12705 }
12706 }
12707
12708 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012709 DefineVTable = false;
12710 }
12711
12712 // The exception specifications for all virtual members may be needed even
12713 // if we are not providing an authoritative form of the vtable in this TU.
12714 // We may choose to emit it available_externally anyway.
12715 if (!DefineVTable) {
12716 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12717 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012718 }
12719
12720 // Mark all of the virtual members of this class as referenced, so
12721 // that we can build a vtable. Then, tell the AST consumer that a
12722 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012723 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012724 MarkVirtualMembersReferenced(Loc, Class);
12725 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12726 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12727
12728 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012729 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012730 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012731 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012732 if (!KeyFunction ||
12733 (KeyFunction->hasBody(KeyFunctionDef) &&
12734 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012735 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12736 TSK_ExplicitInstantiationDefinition
12737 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12738 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012739 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012740 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012741 VTableUses.clear();
12742
Douglas Gregor97509692011-04-22 22:25:37 +000012743 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012744}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012745
Richard Smithd3b5c9082012-07-27 04:22:15 +000012746void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12747 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012748 for (const auto *I : RD->methods())
12749 if (I->isVirtual() && !I->isPure())
12750 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012751}
12752
Rafael Espindola5b334082010-03-26 00:36:59 +000012753void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12754 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012755 // Mark all functions which will appear in RD's vtable as used.
12756 CXXFinalOverriderMap FinalOverriders;
12757 RD->getFinalOverriders(FinalOverriders);
12758 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12759 E = FinalOverriders.end();
12760 I != E; ++I) {
12761 for (OverridingMethods::const_iterator OI = I->second.begin(),
12762 OE = I->second.end();
12763 OI != OE; ++OI) {
12764 assert(OI->second.size() > 0 && "no final overrider");
12765 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012766
Richard Smith4ff9ff92012-07-07 06:59:51 +000012767 // C++ [basic.def.odr]p2:
12768 // [...] A virtual member function is used if it is not pure. [...]
12769 if (!Overrider->isPure())
12770 MarkFunctionReferenced(Loc, Overrider);
12771 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012772 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012773
12774 // Only classes that have virtual bases need a VTT.
12775 if (RD->getNumVBases() == 0)
12776 return;
12777
Aaron Ballman574705e2014-03-13 15:41:46 +000012778 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012779 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012780 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012781 if (Base->getNumVBases() == 0)
12782 continue;
12783 MarkVirtualMembersReferenced(Loc, Base);
12784 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012785}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012786
12787/// SetIvarInitializers - This routine builds initialization ASTs for the
12788/// Objective-C implementation whose ivars need be initialized.
12789void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012790 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012791 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012792 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012793 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012794 CollectIvarsToConstructOrDestruct(OID, ivars);
12795 if (ivars.empty())
12796 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012797 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012798 for (unsigned i = 0; i < ivars.size(); i++) {
12799 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012800 if (Field->isInvalidDecl())
12801 continue;
12802
Alexis Hunt1d792652011-01-08 20:30:50 +000012803 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012804 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12805 InitializationKind InitKind =
12806 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012807
12808 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12809 ExprResult MemberInit =
12810 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012811 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012812 // Note, MemberInit could actually come back empty if no initialization
12813 // is required (e.g., because it would call a trivial default constructor)
12814 if (!MemberInit.get() || MemberInit.isInvalid())
12815 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012816
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012817 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012818 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12819 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012820 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012821 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012822 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012823
12824 // Be sure that the destructor is accessible and is marked as referenced.
12825 if (const RecordType *RecordTy
12826 = Context.getBaseElementType(Field->getType())
12827 ->getAs<RecordType>()) {
12828 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012829 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012830 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012831 CheckDestructorAccess(Field->getLocation(), Destructor,
12832 PDiag(diag::err_access_dtor_ivar)
12833 << Context.getBaseElementType(Field->getType()));
12834 }
12835 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012836 }
12837 ObjCImplementation->setIvarInitializers(Context,
12838 AllToInit.data(), AllToInit.size());
12839 }
12840}
Alexis Hunt6118d662011-05-04 05:57:24 +000012841
Alexis Hunt27a761d2011-05-04 23:29:54 +000012842static
12843void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12844 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12845 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12846 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12847 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012848 if (Ctor->isInvalidDecl())
12849 return;
12850
Richard Smith802c4b72012-08-23 06:16:52 +000012851 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12852
12853 // Target may not be determinable yet, for instance if this is a dependent
12854 // call in an uninstantiated template.
12855 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012856 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012857 (void)Target->hasBody(FNTarget);
12858 Target = const_cast<CXXConstructorDecl*>(
12859 cast_or_null<CXXConstructorDecl>(FNTarget));
12860 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012861
12862 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12863 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012864 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012865
12866 if (!Current.insert(Canonical))
12867 return;
12868
12869 // We know that beyond here, we aren't chaining into a cycle.
12870 if (!Target || !Target->isDelegatingConstructor() ||
12871 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012872 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012873 Current.clear();
12874 // We've hit a cycle.
12875 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12876 Current.count(TCanonical)) {
12877 // If we haven't diagnosed this cycle yet, do so now.
12878 if (!Invalid.count(TCanonical)) {
12879 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012880 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012881 << Ctor;
12882
Richard Smith802c4b72012-08-23 06:16:52 +000012883 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012884 if (TCanonical != Canonical)
12885 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12886
12887 CXXConstructorDecl *C = Target;
12888 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012889 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012890 (void)C->getTargetConstructor()->hasBody(FNTarget);
12891 assert(FNTarget && "Ctor cycle through bodiless function");
12892
Richard Smith802c4b72012-08-23 06:16:52 +000012893 C = const_cast<CXXConstructorDecl*>(
12894 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012895 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12896 }
12897 }
12898
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012899 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012900 Current.clear();
12901 } else {
12902 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12903 }
12904}
12905
12906
Alexis Hunt6118d662011-05-04 05:57:24 +000012907void Sema::CheckDelegatingCtorCycles() {
12908 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12909
Douglas Gregorbae31202011-07-27 21:57:17 +000012910 for (DelegatingCtorDeclsType::iterator
12911 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012912 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012913 I != E; ++I)
12914 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012915
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012916 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12917 CE = Invalid.end();
12918 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012919 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012920}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012921
Douglas Gregor3024f072012-04-16 07:05:22 +000012922namespace {
12923 /// \brief AST visitor that finds references to the 'this' expression.
12924 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12925 Sema &S;
12926
12927 public:
12928 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12929
12930 bool VisitCXXThisExpr(CXXThisExpr *E) {
12931 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12932 << E->isImplicit();
12933 return false;
12934 }
12935 };
12936}
12937
12938bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12939 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12940 if (!TSInfo)
12941 return false;
12942
12943 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012944 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012945 if (!ProtoTL)
12946 return false;
12947
12948 // C++11 [expr.prim.general]p3:
12949 // [The expression this] shall not appear before the optional
12950 // cv-qualifier-seq and it shall not appear within the declaration of a
12951 // static member function (although its type and value category are defined
12952 // within a static member function as they are within a non-static member
12953 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012954 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012955 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012956 FindCXXThisExpr Finder(*this);
12957
12958 // If the return type came after the cv-qualifier-seq, check it now.
12959 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012960 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012961 return true;
12962
12963 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012964 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12965 return true;
12966
12967 return checkThisInStaticMemberFunctionAttributes(Method);
12968}
12969
12970bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12971 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12972 if (!TSInfo)
12973 return false;
12974
12975 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012976 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012977 if (!ProtoTL)
12978 return false;
12979
David Blaikie6adc78e2013-02-18 22:06:02 +000012980 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012981 FindCXXThisExpr Finder(*this);
12982
Douglas Gregor3024f072012-04-16 07:05:22 +000012983 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012984 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012985 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012986 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012987 case EST_DynamicNone:
12988 case EST_MSAny:
12989 case EST_None:
12990 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012991
Douglas Gregor3024f072012-04-16 07:05:22 +000012992 case EST_ComputedNoexcept:
12993 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12994 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012995
Douglas Gregor3024f072012-04-16 07:05:22 +000012996 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012997 for (const auto &E : Proto->exceptions()) {
12998 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012999 return true;
13000 }
13001 break;
13002 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013003
13004 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013005}
13006
13007bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13008 FindCXXThisExpr Finder(*this);
13009
13010 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013011 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013012 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013013 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013014 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013015 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013016 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013017 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013018 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013019 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013020 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013021 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013022 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013023 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013024 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013025 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013026 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013027 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013028 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013029 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013030 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013031 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013032 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013033 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013034 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013035 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013036 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013037 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013038 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013039 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013040 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013041
13042 if (Arg && !Finder.TraverseStmt(Arg))
13043 return true;
13044
13045 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13046 if (!Finder.TraverseStmt(Args[I]))
13047 return true;
13048 }
13049 }
13050
13051 return false;
13052}
13053
Richard Smith4ff12382014-09-17 23:57:05 +000013054void Sema::checkExceptionSpecification(
13055 bool IsTopLevel, ExceptionSpecificationType EST,
13056 ArrayRef<ParsedType> DynamicExceptions,
13057 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13058 SmallVectorImpl<QualType> &Exceptions,
13059 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013060 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013061 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013062 if (EST == EST_Dynamic) {
13063 Exceptions.reserve(DynamicExceptions.size());
13064 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13065 // FIXME: Preserve type source info.
13066 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13067
Richard Smith4ff12382014-09-17 23:57:05 +000013068 if (IsTopLevel) {
13069 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13070 collectUnexpandedParameterPacks(ET, Unexpanded);
13071 if (!Unexpanded.empty()) {
13072 DiagnoseUnexpandedParameterPacks(
13073 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13074 Unexpanded);
13075 continue;
13076 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013077 }
13078
13079 // Check that the type is valid for an exception spec, and
13080 // drop it if not.
13081 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13082 Exceptions.push_back(ET);
13083 }
Richard Smith8acb4282014-07-31 21:57:55 +000013084 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013085 return;
13086 }
Richard Smith8acb4282014-07-31 21:57:55 +000013087
Douglas Gregor433e0532012-04-16 18:27:27 +000013088 if (EST == EST_ComputedNoexcept) {
13089 // If an error occurred, there's no expression here.
13090 if (NoexceptExpr) {
13091 assert((NoexceptExpr->isTypeDependent() ||
13092 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13093 Context.BoolTy) &&
13094 "Parser should have made sure that the expression is boolean");
Richard Smith4ff12382014-09-17 23:57:05 +000013095 if (IsTopLevel && NoexceptExpr &&
13096 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013097 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013098 return;
13099 }
Richard Smith8acb4282014-07-31 21:57:55 +000013100
Douglas Gregor433e0532012-04-16 18:27:27 +000013101 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013102 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013103 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013104 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013105 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013106 }
13107 return;
13108 }
13109}
13110
John McCall5e77d762013-04-16 07:28:30 +000013111/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13112///
13113MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13114 SourceLocation DeclStart,
13115 Declarator &D, Expr *BitWidth,
13116 InClassInitStyle InitStyle,
13117 AccessSpecifier AS,
13118 AttributeList *MSPropertyAttr) {
13119 IdentifierInfo *II = D.getIdentifier();
13120 if (!II) {
13121 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013122 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013123 }
13124 SourceLocation Loc = D.getIdentifierLoc();
13125
13126 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13127 QualType T = TInfo->getType();
13128 if (getLangOpts().CPlusPlus) {
13129 CheckExtraCXXDefaultArguments(D);
13130
13131 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13132 UPPC_DataMemberType)) {
13133 D.setInvalidType();
13134 T = Context.IntTy;
13135 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13136 }
13137 }
13138
13139 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13140
13141 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13142 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13143 diag::err_invalid_thread)
13144 << DeclSpec::getSpecifierName(TSCS);
13145
13146 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013147 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013148 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13149 LookupName(Previous, S);
13150 switch (Previous.getResultKind()) {
13151 case LookupResult::Found:
13152 case LookupResult::FoundUnresolvedValue:
13153 PrevDecl = Previous.getAsSingle<NamedDecl>();
13154 break;
13155
13156 case LookupResult::FoundOverloaded:
13157 PrevDecl = Previous.getRepresentativeDecl();
13158 break;
13159
13160 case LookupResult::NotFound:
13161 case LookupResult::NotFoundInCurrentInstantiation:
13162 case LookupResult::Ambiguous:
13163 break;
13164 }
13165
13166 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13167 // Maybe we will complain about the shadowed template parameter.
13168 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13169 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013170 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013171 }
13172
13173 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013174 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013175
13176 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013177 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013178 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13179 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013180 ProcessDeclAttributes(TUScope, NewPD, D);
13181 NewPD->setAccess(AS);
13182
13183 if (NewPD->isInvalidDecl())
13184 Record->setInvalidDecl();
13185
13186 if (D.getDeclSpec().isModulePrivateSpecified())
13187 NewPD->setModulePrivate();
13188
13189 if (NewPD->isInvalidDecl() && PrevDecl) {
13190 // Don't introduce NewFD into scope; there's already something
13191 // with the same name in the same scope.
13192 } else if (II) {
13193 PushOnScopeChains(NewPD, S);
13194 } else
13195 Record->addDecl(NewPD);
13196
13197 return NewPD;
13198}