blob: adbcafe4339d36e07388c09a72ca1f93bc7cee19 [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)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000356 OpaqueValueExpr(EqualLoc,
357 Param->getType().getNonReferenceType(),
358 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000359}
360
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Alp Tokerc5350722014-02-26 22:27:52 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
386 ++argIdx) {
387 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000389 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000393 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000394 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000398 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemer502b0ed2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Toppere4794282012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner199abbc2008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000443 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloye9430032012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
Richard Smith541b38b2013-09-20 01:15:31 +0000451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
Richard Smith5971e8c2014-08-27 22:31:34 +0000454 DeclContext *ScopeDC = New->isLocalExternDecl()
455 ? New->getLexicalDeclContext()
456 : New->getDeclContext();
457 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000458 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
Richard Smith5971e8c2014-08-27 22:31:34 +0000463 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
464 // If only one of these is a local function declaration, then they are
465 // declared in different scopes, even though isDeclInScope may think
466 // they're in the same scope. (If both are local, the scope check is
467 // sufficent, and if neither is local, then they are in the same scope.)
468 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000469
470 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000471
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000472 unsigned DiagDefaultParamID =
473 diag::err_param_default_argument_redefinition;
474
475 // MSVC accepts that default parameters be redefined for member functions
476 // of template class. The new default parameter's value is ignored.
477 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000478 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000479 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
480 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000481 // Merge the old default argument into the new parameter.
482 NewParam->setHasInheritedDefaultArg();
483 if (OldParam->hasUninstantiatedDefaultArg())
484 NewParam->setUninstantiatedDefaultArg(
485 OldParam->getUninstantiatedDefaultArg());
486 else
487 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000488 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000489 Invalid = false;
490 }
491 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492
Francois Pichet8cb243a2011-04-10 04:58:30 +0000493 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
494 // hint here. Alternatively, we could walk the type-source information
495 // for NewParam to find the last source location in the type... but it
496 // isn't worth the effort right now. This is the kind of test case that
497 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000498 // int f(int);
499 // void g(int (*fp)(int) = f);
500 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000501 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000502 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000503
504 // Look for the function declaration where the default argument was
505 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000506 for (FunctionDecl *Older = Old->getPreviousDecl();
507 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000508 if (!Older->getParamDecl(p)->hasDefaultArg())
509 break;
510
511 OldParam = Older->getParamDecl(p);
512 }
513
514 Diag(OldParam->getLocation(), diag::note_previous_definition)
515 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000516 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000517 // Merge the old default argument into the new parameter.
518 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000519 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000520 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000521 if (OldParam->hasUninstantiatedDefaultArg())
522 NewParam->setUninstantiatedDefaultArg(
523 OldParam->getUninstantiatedDefaultArg());
524 else
John McCalle61b02b2010-05-04 01:53:42 +0000525 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000526 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000527 if (New->getDescribedFunctionTemplate()) {
528 // Paragraph 4, quoted above, only applies to non-template functions.
529 Diag(NewParam->getLocation(),
530 diag::err_param_default_argument_template_redecl)
531 << NewParam->getDefaultArgRange();
532 Diag(Old->getLocation(), diag::note_template_prev_declaration)
533 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000534 } else if (New->getTemplateSpecializationKind()
535 != TSK_ImplicitInstantiation &&
536 New->getTemplateSpecializationKind() != TSK_Undeclared) {
537 // C++ [temp.expr.spec]p21:
538 // Default function arguments shall not be specified in a declaration
539 // or a definition for one of the following explicit specializations:
540 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000541 // - the explicit specialization of a member function template;
542 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000543 // template where the class template specialization to which the
544 // member function specialization belongs is implicitly
545 // instantiated.
546 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
547 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
548 << New->getDeclName()
549 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000550 } else if (New->getDeclContext()->isDependentContext()) {
551 // C++ [dcl.fct.default]p6 (DR217):
552 // Default arguments for a member function of a class template shall
553 // be specified on the initial declaration of the member function
554 // within the class template.
555 //
556 // Reading the tea leaves a bit in DR217 and its reference to DR205
557 // leads me to the conclusion that one cannot add default function
558 // arguments for an out-of-line definition of a member function of a
559 // dependent type.
560 int WhichKind = 2;
561 if (CXXRecordDecl *Record
562 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
563 if (Record->getDescribedClassTemplate())
564 WhichKind = 0;
565 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
566 WhichKind = 1;
567 else
568 WhichKind = 2;
569 }
570
571 Diag(NewParam->getLocation(),
572 diag::err_param_default_argument_member_template_redecl)
573 << WhichKind
574 << NewParam->getDefaultArgRange();
575 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000576 }
577 }
578
Richard Smith58c3cc12012-11-28 03:45:24 +0000579 // DR1344: If a default argument is added outside a class definition and that
580 // default argument makes the function a special member function, the program
581 // is ill-formed. This can only happen for constructors.
582 if (isa<CXXConstructorDecl>(New) &&
583 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
584 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
585 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
586 if (NewSM != OldSM) {
587 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
588 assert(NewParam->hasDefaultArg());
589 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
590 << NewParam->getDefaultArgRange() << NewSM;
591 Diag(Old->getLocation(), diag::note_previous_declaration);
592 }
593 }
594
David Majnemeree4f4022014-03-30 06:44:54 +0000595 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000596 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000597 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000598 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000599 if (New->isConstexpr() != Old->isConstexpr()) {
600 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
601 << New << New->isConstexpr();
602 Diag(Old->getLocation(), diag::note_previous_declaration);
603 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000604 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
605 // C++11 [dcl.fcn.spec]p4:
606 // If the definition of a function appears in a translation unit before its
607 // first declaration as inline, the program is ill-formed.
608 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
609 Diag(Def->getLocation(), diag::note_previous_definition);
610 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000611 }
612
David Majnemer502b0ed2013-06-25 23:09:30 +0000613 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000614 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000615 // the only declaration of the function or function template in the
616 // translation unit.
617 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
618 functionDeclHasDefaultArgument(Old)) {
619 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
620 Diag(Old->getLocation(), diag::note_previous_declaration);
621 Invalid = true;
622 }
623
Douglas Gregorf40863c2010-02-12 07:32:17 +0000624 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000625 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000626
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000627 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000628}
629
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000630/// \brief Merge the exception specifications of two variable declarations.
631///
632/// This is called when there's a redeclaration of a VarDecl. The function
633/// checks if the redeclaration might have an exception specification and
634/// validates compatibility and merges the specs if necessary.
635void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
636 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000638 return;
639
640 assert(Context.hasSameType(New->getType(), Old->getType()) &&
641 "Should only be called if types are otherwise the same.");
642
643 QualType NewType = New->getType();
644 QualType OldType = Old->getType();
645
646 // We're only interested in pointers and references to functions, as well
647 // as pointers to member functions.
648 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
649 NewType = R->getPointeeType();
650 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
651 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
652 NewType = P->getPointeeType();
653 OldType = OldType->getAs<PointerType>()->getPointeeType();
654 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
655 NewType = M->getPointeeType();
656 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
657 }
658
659 if (!NewType->isFunctionProtoType())
660 return;
661
662 // There's lots of special cases for functions. For function pointers, system
663 // libraries are hopefully not as broken so that we don't need these
664 // workarounds.
665 if (CheckEquivalentExceptionSpec(
666 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
667 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
668 New->setInvalidDecl();
669 }
670}
671
Chris Lattner199abbc2008-04-08 05:04:30 +0000672/// CheckCXXDefaultArguments - Verify that the default arguments for a
673/// function declaration are well-formed according to C++
674/// [dcl.fct.default].
675void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
676 unsigned NumParams = FD->getNumParams();
677 unsigned p;
678
679 // Find first parameter with a default argument
680 for (p = 0; p < NumParams; ++p) {
681 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000682 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000683 break;
684 }
685
686 // C++ [dcl.fct.default]p4:
687 // In a given function declaration, all parameters
688 // subsequent to a parameter with a default argument shall
689 // have default arguments supplied in this or previous
690 // declarations. A default argument shall not be redefined
691 // by a later declaration (not even to the same value).
692 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000693 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000694 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000695 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000696 if (Param->isInvalidDecl())
697 /* We already complained about this parameter. */;
698 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000699 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000700 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000701 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000702 else
Mike Stump11289f42009-09-09 15:08:12 +0000703 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000704 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000705
Chris Lattner199abbc2008-04-08 05:04:30 +0000706 LastMissingDefaultArg = p;
707 }
708 }
709
710 if (LastMissingDefaultArg > 0) {
711 // Some default arguments were missing. Clear out all of the
712 // default arguments up to (and including) the last missing
713 // default argument, so that we leave the function parameters
714 // in a semantically valid state.
715 for (p = 0; p <= LastMissingDefaultArg; ++p) {
716 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000717 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000718 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000719 }
720 }
721 }
722}
Douglas Gregor556877c2008-04-13 21:30:24 +0000723
Richard Smitheb3c10c2011-10-01 02:31:28 +0000724// CheckConstexprParameterTypes - Check whether a function's parameter types
725// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000726// diagnostic and return false.
727static bool CheckConstexprParameterTypes(Sema &SemaRef,
728 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000729 unsigned ArgIndex = 0;
730 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000731 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
732 e = FT->param_type_end();
733 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000734 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
735 SourceLocation ParamLoc = PD->getLocation();
736 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000737 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000738 diag::err_constexpr_non_literal_param,
739 ArgIndex+1, PD->getSourceRange(),
740 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000741 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000742 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000743 return true;
744}
745
746/// \brief Get diagnostic %select index for tag kind for
747/// record diagnostic message.
748/// WARNING: Indexes apply to particular diagnostics only!
749///
750/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000751static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000752 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000753 case TTK_Struct: return 0;
754 case TTK_Interface: return 1;
755 case TTK_Class: return 2;
756 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000757 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000758}
759
760// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
761// the requirements of a constexpr function definition or a constexpr
762// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000763// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000764//
Richard Smith3607ffe2012-02-13 03:54:03 +0000765// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
766bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000767 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
768 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000769 // C++11 [dcl.constexpr]p4:
770 // The definition of a constexpr constructor shall satisfy the following
771 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000772 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000773 const CXXRecordDecl *RD = MD->getParent();
774 if (RD->getNumVBases()) {
775 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
776 << isa<CXXConstructorDecl>(NewFD)
777 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000778 for (const auto &I : RD->vbases())
779 Diag(I.getLocStart(),
780 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 return false;
782 }
Richard Smith7971b692012-01-13 04:54:00 +0000783 }
784
785 if (!isa<CXXConstructorDecl>(NewFD)) {
786 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787 // The definition of a constexpr function shall satisfy the following
788 // constraints:
789 // - it shall not be virtual;
790 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
791 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000792 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793
Richard Smith3607ffe2012-02-13 03:54:03 +0000794 // If it's not obvious why this function is virtual, find an overridden
795 // function which uses the 'virtual' keyword.
796 const CXXMethodDecl *WrittenVirtual = Method;
797 while (!WrittenVirtual->isVirtualAsWritten())
798 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
799 if (WrittenVirtual != Method)
800 Diag(WrittenVirtual->getLocation(),
801 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 return false;
803 }
804
805 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000806 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000807 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000809 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000810 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 }
812
Richard Smith7971b692012-01-13 04:54:00 +0000813 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000814 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000815 return false;
816
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817 return true;
818}
819
820/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000821/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822///
Richard Smithd9f663b2013-04-22 15:31:51 +0000823/// \return true if the body is OK (maybe only as an extension), false if we
824/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000825static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000826 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
827 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000828 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
829 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000830 for (const auto *DclIt : DS->decls()) {
831 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 case Decl::StaticAssert:
833 case Decl::Using:
834 case Decl::UsingShadow:
835 case Decl::UsingDirective:
836 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000837 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000838 // - static_assert-declarations
839 // - using-declarations,
840 // - using-directives,
841 continue;
842
843 case Decl::Typedef:
844 case Decl::TypeAlias: {
845 // - typedef declarations and alias-declarations that do not define
846 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000847 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000848 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
849 // Don't allow variably-modified types in constexpr functions.
850 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
851 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
852 << TL.getSourceRange() << TL.getType()
853 << isa<CXXConstructorDecl>(Dcl);
854 return false;
855 }
856 continue;
857 }
858
859 case Decl::Enum:
860 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000861 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000862 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000863 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000864 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000865 ? diag::warn_cxx11_compat_constexpr_type_definition
866 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000867 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000868 continue;
869
Richard Smithd9f663b2013-04-22 15:31:51 +0000870 case Decl::EnumConstant:
871 case Decl::IndirectField:
872 case Decl::ParmVar:
873 // These can only appear with other declarations which are banned in
874 // C++11 and permitted in C++1y, so ignore them.
875 continue;
876
877 case Decl::Var: {
878 // C++1y [dcl.constexpr]p3 allows anything except:
879 // a definition of a variable of non-literal type or of static or
880 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000881 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000882 if (VD->isThisDeclarationADefinition()) {
883 if (VD->isStaticLocal()) {
884 SemaRef.Diag(VD->getLocation(),
885 diag::err_constexpr_local_var_static)
886 << isa<CXXConstructorDecl>(Dcl)
887 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
888 return false;
889 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000890 if (!VD->getType()->isDependentType() &&
891 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000892 VD->getLocation(), VD->getType(),
893 diag::err_constexpr_local_var_non_literal_type,
894 isa<CXXConstructorDecl>(Dcl)))
895 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000896 if (!VD->getType()->isDependentType() &&
897 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000898 SemaRef.Diag(VD->getLocation(),
899 diag::err_constexpr_local_var_no_init)
900 << isa<CXXConstructorDecl>(Dcl);
901 return false;
902 }
903 }
904 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000905 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000906 ? diag::warn_cxx11_compat_constexpr_local_var
907 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000908 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000909 continue;
910 }
911
912 case Decl::NamespaceAlias:
913 case Decl::Function:
914 // These are disallowed in C++11 and permitted in C++1y. Allow them
915 // everywhere as an extension.
916 if (!Cxx1yLoc.isValid())
917 Cxx1yLoc = DS->getLocStart();
918 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000919
920 default:
921 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
922 << isa<CXXConstructorDecl>(Dcl);
923 return false;
924 }
925 }
926
927 return true;
928}
929
930/// Check that the given field is initialized within a constexpr constructor.
931///
932/// \param Dcl The constexpr constructor being checked.
933/// \param Field The field being checked. This may be a member of an anonymous
934/// struct or union nested within the class being checked.
935/// \param Inits All declarations, including anonymous struct/union members and
936/// indirect members, for which any initialization was provided.
937/// \param Diagnosed Set to true if an error is produced.
938static void CheckConstexprCtorInitializer(Sema &SemaRef,
939 const FunctionDecl *Dcl,
940 FieldDecl *Field,
941 llvm::SmallSet<Decl*, 16> &Inits,
942 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000943 if (Field->isInvalidDecl())
944 return;
945
Douglas Gregor556e5862011-10-10 17:22:13 +0000946 if (Field->isUnnamedBitfield())
947 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000948
Richard Smithab44d5b2013-12-10 08:25:00 +0000949 // Anonymous unions with no variant members and empty anonymous structs do not
950 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
951 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000952 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000953 (Field->getType()->isUnionType()
954 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
955 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000956 return;
957
Richard Smitheb3c10c2011-10-01 02:31:28 +0000958 if (!Inits.count(Field)) {
959 if (!Diagnosed) {
960 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
961 Diagnosed = true;
962 }
963 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
964 } else if (Field->isAnonymousStructOrUnion()) {
965 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000966 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000967 // If an anonymous union contains an anonymous struct of which any member
968 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000969 if (!RD->isUnion() || Inits.count(I))
970 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000971 }
972}
973
Richard Smithd9f663b2013-04-22 15:31:51 +0000974/// Check the provided statement is allowed in a constexpr function
975/// definition.
976static bool
977CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000978 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000979 SourceLocation &Cxx1yLoc) {
980 // - its function-body shall be [...] a compound-statement that contains only
981 switch (S->getStmtClass()) {
982 case Stmt::NullStmtClass:
983 // - null statements,
984 return true;
985
986 case Stmt::DeclStmtClass:
987 // - static_assert-declarations
988 // - using-declarations,
989 // - using-directives,
990 // - typedef declarations and alias-declarations that do not define
991 // classes or enumerations,
992 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
993 return false;
994 return true;
995
996 case Stmt::ReturnStmtClass:
997 // - and exactly one return statement;
998 if (isa<CXXConstructorDecl>(Dcl)) {
999 // C++1y allows return statements in constexpr constructors.
1000 if (!Cxx1yLoc.isValid())
1001 Cxx1yLoc = S->getLocStart();
1002 return true;
1003 }
1004
1005 ReturnStmts.push_back(S->getLocStart());
1006 return true;
1007
1008 case Stmt::CompoundStmtClass: {
1009 // C++1y allows compound-statements.
1010 if (!Cxx1yLoc.isValid())
1011 Cxx1yLoc = S->getLocStart();
1012
1013 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001014 for (auto *BodyIt : CompStmt->body()) {
1015 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001016 Cxx1yLoc))
1017 return false;
1018 }
1019 return true;
1020 }
1021
1022 case Stmt::AttributedStmtClass:
1023 if (!Cxx1yLoc.isValid())
1024 Cxx1yLoc = S->getLocStart();
1025 return true;
1026
1027 case Stmt::IfStmtClass: {
1028 // C++1y allows if-statements.
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031
1032 IfStmt *If = cast<IfStmt>(S);
1033 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1034 Cxx1yLoc))
1035 return false;
1036 if (If->getElse() &&
1037 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1038 Cxx1yLoc))
1039 return false;
1040 return true;
1041 }
1042
1043 case Stmt::WhileStmtClass:
1044 case Stmt::DoStmtClass:
1045 case Stmt::ForStmtClass:
1046 case Stmt::CXXForRangeStmtClass:
1047 case Stmt::ContinueStmtClass:
1048 // C++1y allows all of these. We don't allow them as extensions in C++11,
1049 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001050 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001051 break;
1052 if (!Cxx1yLoc.isValid())
1053 Cxx1yLoc = S->getLocStart();
1054 for (Stmt::child_range Children = S->children(); Children; ++Children)
1055 if (*Children &&
1056 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1057 Cxx1yLoc))
1058 return false;
1059 return true;
1060
1061 case Stmt::SwitchStmtClass:
1062 case Stmt::CaseStmtClass:
1063 case Stmt::DefaultStmtClass:
1064 case Stmt::BreakStmtClass:
1065 // C++1y allows switch-statements, and since they don't need variable
1066 // mutation, we can reasonably allow them in C++11 as an extension.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1069 for (Stmt::child_range Children = S->children(); Children; ++Children)
1070 if (*Children &&
1071 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1072 Cxx1yLoc))
1073 return false;
1074 return true;
1075
1076 default:
1077 if (!isa<Expr>(S))
1078 break;
1079
1080 // C++1y allows expression-statements.
1081 if (!Cxx1yLoc.isValid())
1082 Cxx1yLoc = S->getLocStart();
1083 return true;
1084 }
1085
1086 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1087 << isa<CXXConstructorDecl>(Dcl);
1088 return false;
1089}
1090
Richard Smitheb3c10c2011-10-01 02:31:28 +00001091/// Check the body for the given constexpr function declaration only contains
1092/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1093///
1094/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001095bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001097 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001098 // The definition of a constexpr function shall satisfy the following
1099 // constraints: [...]
1100 // - its function-body shall be = delete, = default, or a
1101 // compound-statement
1102 //
Richard Smith74388b42012-02-04 00:33:54 +00001103 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 // In the definition of a constexpr constructor, [...]
1105 // - its function-body shall not be a function-try-block;
1106 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1107 << isa<CXXConstructorDecl>(Dcl);
1108 return false;
1109 }
1110
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001111 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001112
1113 // - its function-body shall be [...] a compound-statement that contains only
1114 // [... list of cases ...]
1115 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1116 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001117 for (auto *BodyIt : CompBody->body()) {
1118 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001119 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001120 }
1121
Richard Smithd9f663b2013-04-22 15:31:51 +00001122 if (Cxx1yLoc.isValid())
1123 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001124 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001125 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1126 : diag::ext_constexpr_body_invalid_stmt)
1127 << isa<CXXConstructorDecl>(Dcl);
1128
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129 if (const CXXConstructorDecl *Constructor
1130 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1131 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001132 // DR1359:
1133 // - every non-variant non-static data member and base class sub-object
1134 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001135 // DR1460:
1136 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001137 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001139 if (Constructor->getNumCtorInitializers() == 0 &&
1140 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001141 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1142 return false;
1143 }
Richard Smithf368fb42011-10-10 16:38:04 +00001144 } else if (!Constructor->isDependentContext() &&
1145 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001146 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1147
1148 // Skip detailed checking if we have enough initializers, and we would
1149 // allow at most one initializer per member.
1150 bool AnyAnonStructUnionMembers = false;
1151 unsigned Fields = 0;
1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001154 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 AnyAnonStructUnionMembers = true;
1156 break;
1157 }
1158 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001159 // DR1460:
1160 // - if the class is a union-like class, but is not a union, for each of
1161 // its anonymous union members having variant members, exactly one of
1162 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 if (AnyAnonStructUnionMembers ||
1164 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1165 // Check initialization of non-static data members. Base classes are
1166 // always initialized so do not need to be checked. Dependent bases
1167 // might not have initializers in the member initializer list.
1168 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001169 for (const auto *I: Constructor->inits()) {
1170 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001172 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001173 Inits.insert(ID->chain_begin(), ID->chain_end());
1174 }
1175
1176 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001177 for (auto *I : RD->fields())
1178 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001179 if (Diagnosed)
1180 return false;
1181 }
1182 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001183 } else {
1184 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001185 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001186 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001187 // otherwise if there's no return statement, the function cannot
1188 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001189 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001190 (Dcl->getReturnType()->isVoidType() ||
1191 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001192 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001193 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1194 : diag::err_constexpr_body_no_return);
1195 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 }
1197 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001198 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001199 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001200 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1201 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001202 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1203 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001204 }
1205 }
1206
Richard Smith74388b42012-02-04 00:33:54 +00001207 // C++11 [dcl.constexpr]p5:
1208 // if no function argument values exist such that the function invocation
1209 // substitution would produce a constant expression, the program is
1210 // ill-formed; no diagnostic required.
1211 // C++11 [dcl.constexpr]p3:
1212 // - every constructor call and implicit conversion used in initializing the
1213 // return value shall be one of those allowed in a constant expression.
1214 // C++11 [dcl.constexpr]p4:
1215 // - every constructor involved in initializing non-static data members and
1216 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001217 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001218 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001219 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001220 << isa<CXXConstructorDecl>(Dcl);
1221 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1222 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001223 // Don't return false here: we allow this for compatibility in
1224 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001225 }
1226
Richard Smitheb3c10c2011-10-01 02:31:28 +00001227 return true;
1228}
1229
Douglas Gregor61956c42008-10-31 09:07:45 +00001230/// isCurrentClassName - Determine whether the identifier II is the
1231/// name of the class type currently being defined. In the case of
1232/// nested classes, this will only return true if II is the name of
1233/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001234bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1235 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001236 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001237
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001238 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001239 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001240 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001241 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1242 } else
1243 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1244
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001245 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001246 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001247 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001248}
1249
Richard Smithfb8b7b92013-10-15 00:00:26 +00001250/// \brief Determine whether the identifier II is a typo for the name of
1251/// the class type currently being defined. If so, update it to the identifier
1252/// that should have been used.
1253bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1254 assert(getLangOpts().CPlusPlus && "No class names in C!");
1255
1256 if (!getLangOpts().SpellChecking)
1257 return false;
1258
1259 CXXRecordDecl *CurDecl;
1260 if (SS && SS->isSet() && !SS->isInvalid()) {
1261 DeclContext *DC = computeDeclContext(*SS, true);
1262 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1263 } else
1264 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1265
1266 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1267 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1268 < II->getLength()) {
1269 II = CurDecl->getIdentifier();
1270 return true;
1271 }
1272
1273 return false;
1274}
1275
Douglas Gregordc974572012-11-10 07:24:09 +00001276/// \brief Determine whether the given class is a base class of the given
1277/// class, including looking at dependent bases.
1278static bool findCircularInheritance(const CXXRecordDecl *Class,
1279 const CXXRecordDecl *Current) {
1280 SmallVector<const CXXRecordDecl*, 8> Queue;
1281
1282 Class = Class->getCanonicalDecl();
1283 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001284 for (const auto &I : Current->bases()) {
1285 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001286 if (!Base)
1287 continue;
1288
1289 Base = Base->getDefinition();
1290 if (!Base)
1291 continue;
1292
1293 if (Base->getCanonicalDecl() == Class)
1294 return true;
1295
1296 Queue.push_back(Base);
1297 }
1298
1299 if (Queue.empty())
1300 return false;
1301
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001302 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001303 }
1304
1305 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001306}
1307
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001308/// \brief Perform propagation of DLL attributes from a derived class to a
1309/// templated base class for MS compatibility.
1310static void propagateDLLAttrToBaseClassTemplate(
1311 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1312 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1313 if (getDLLAttr(
1314 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1315 // If the base class template has a DLL attribute, don't try to change it.
1316 return;
1317 }
1318
1319 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1320 // If the base class is not already specialized, we can do the propagation.
1321 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1322 NewAttr->setInherited(true);
1323 BaseTemplateSpec->addAttr(NewAttr);
1324 return;
1325 }
1326
1327 bool DifferentAttribute = false;
1328 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1329 if (!SpecializationAttr->isInherited()) {
1330 // The template has previously been specialized or instantiated with an
1331 // explicit attribute. We should not try to change it.
1332 return;
1333 }
1334 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1335 // The specialization already has the right attribute.
1336 return;
1337 }
1338 DifferentAttribute = true;
1339 }
1340
1341 // The template was previously instantiated or explicitly specialized without
1342 // a dll attribute, or the template was previously instantiated with a
1343 // different inherited attribute. It's too late for us to change the
1344 // attribute, so warn that this is unsupported.
1345 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1346 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1347 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1348 if (BaseTemplateSpec->isExplicitSpecialization()) {
1349 S.Diag(BaseTemplateSpec->getLocation(),
1350 diag::note_template_class_explicit_specialization_was_here)
1351 << BaseTemplateSpec;
1352 } else {
1353 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1354 diag::note_template_class_instantiation_was_here)
1355 << BaseTemplateSpec;
1356 }
1357}
1358
Mike Stump11289f42009-09-09 15:08:12 +00001359/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001360///
1361/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1362/// and returns NULL otherwise.
1363CXXBaseSpecifier *
1364Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1365 SourceRange SpecifierRange,
1366 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001367 TypeSourceInfo *TInfo,
1368 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001369 QualType BaseType = TInfo->getType();
1370
Douglas Gregor463421d2009-03-03 04:44:36 +00001371 // C++ [class.union]p1:
1372 // A union shall not have base classes.
1373 if (Class->isUnion()) {
1374 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1375 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001376 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 }
1378
Douglas Gregor752a5952011-01-03 22:36:02 +00001379 if (EllipsisLoc.isValid() &&
1380 !TInfo->getType()->containsUnexpandedParameterPack()) {
1381 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1382 << TInfo->getTypeLoc().getSourceRange();
1383 EllipsisLoc = SourceLocation();
1384 }
Douglas Gregor62004702012-11-10 01:18:17 +00001385
1386 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1387
1388 if (BaseType->isDependentType()) {
1389 // Make sure that we don't have circular inheritance among our dependent
1390 // bases. For non-dependent bases, the check for completeness below handles
1391 // this.
1392 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1393 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1394 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001395 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001396 Diag(BaseLoc, diag::err_circular_inheritance)
1397 << BaseType << Context.getTypeDeclType(Class);
1398
1399 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1400 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1401 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001402
1403 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001404 }
1405 }
1406
Mike Stump11289f42009-09-09 15:08:12 +00001407 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001408 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001409 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001410 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001411
1412 // Base specifiers must be record types.
1413 if (!BaseType->isRecordType()) {
1414 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001416 }
1417
1418 // C++ [class.union]p1:
1419 // A union shall not be used as a base class.
1420 if (BaseType->isUnionType()) {
1421 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001423 }
1424
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001425 // For the MS ABI, propagate DLL attributes to base class templates.
1426 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1427 if (Attr *ClassAttr = getDLLAttr(Class)) {
1428 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1429 BaseType->getAsCXXRecordDecl())) {
1430 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1431 BaseTemplate, BaseLoc);
1432 }
1433 }
1434 }
1435
Douglas Gregor463421d2009-03-03 04:44:36 +00001436 // C++ [class.derived]p2:
1437 // The class-name in a base-specifier shall not be an incompletely
1438 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001439 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001440 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001441 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001442 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001443 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001444
Eli Friedmanc96d4962009-08-15 21:55:26 +00001445 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001446 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001447 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001448 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001449 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001450 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001451 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001452
David Majnemer9b1754d2013-11-02 12:00:36 +00001453 // A class which contains a flexible array member is not suitable for use as a
1454 // base class:
1455 // - If the layout determines that a base comes before another base,
1456 // the flexible array member would index into the subsequent base.
1457 // - If the layout determines that base comes before the derived class,
1458 // the flexible array member would index into the derived class.
1459 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1460 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1461 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001462 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001463 }
1464
Anders Carlsson65c76d32011-03-25 14:55:14 +00001465 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001466 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001467 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001468 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001469 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001470 << CXXBaseDecl->getDeclName()
1471 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001472 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1473 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001474 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001475 }
1476
John McCall3696dcb2010-08-17 07:23:57 +00001477 if (BaseDecl->isInvalidDecl())
1478 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001479
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001480 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001481 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001482 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001483 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001484}
1485
Douglas Gregor556877c2008-04-13 21:30:24 +00001486/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1487/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001488/// example:
1489/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001490/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001491BaseResult
John McCall48871652010-08-21 09:40:31 +00001492Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001493 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001494 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001495 ParsedType basetype, SourceLocation BaseLoc,
1496 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001497 if (!classdecl)
1498 return true;
1499
Douglas Gregorc40290e2009-03-09 23:48:35 +00001500 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001501 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001502 if (!Class)
1503 return true;
1504
David Majnemer5ef4fe72014-06-13 06:43:46 +00001505 // We haven't yet attached the base specifiers.
1506 Class->setIsParsingBaseSpecifiers();
1507
Richard Smith4c96e992013-02-19 23:47:15 +00001508 // We do not support any C++11 attributes on base-specifiers yet.
1509 // Diagnose any attributes we see.
1510 if (!Attributes.empty()) {
1511 for (AttributeList *Attr = Attributes.getList(); Attr;
1512 Attr = Attr->getNext()) {
1513 if (Attr->isInvalid() ||
1514 Attr->getKind() == AttributeList::IgnoredAttribute)
1515 continue;
1516 Diag(Attr->getLoc(),
1517 Attr->getKind() == AttributeList::UnknownAttribute
1518 ? diag::warn_unknown_attribute_ignored
1519 : diag::err_base_specifier_attribute)
1520 << Attr->getName();
1521 }
1522 }
1523
Craig Topperc3ec1492014-05-26 06:22:03 +00001524 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001525 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001526
Douglas Gregor752a5952011-01-03 22:36:02 +00001527 if (EllipsisLoc.isInvalid() &&
1528 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001529 UPPC_BaseType))
1530 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001531
Douglas Gregor463421d2009-03-03 04:44:36 +00001532 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001533 Virtual, Access, TInfo,
1534 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001535 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001536 else
1537 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001538
Douglas Gregor463421d2009-03-03 04:44:36 +00001539 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001540}
Douglas Gregor556877c2008-04-13 21:30:24 +00001541
Douglas Gregor463421d2009-03-03 04:44:36 +00001542/// \brief Performs the actual work of attaching the given base class
1543/// specifiers to a C++ class.
1544bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1545 unsigned NumBases) {
1546 if (NumBases == 0)
1547 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001548
1549 // Used to keep track of which base types we have already seen, so
1550 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001551 // that the key is always the unqualified canonical type of the base
1552 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001553 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1554
1555 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001556 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001557 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001558 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001559 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001560 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001561 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001562
1563 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1564 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001565 // C++ [class.mi]p3:
1566 // A class shall not be specified as a direct base class of a
1567 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001568 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001569 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001570 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001571 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001572
1573 // Delete the duplicate base class specifier; we're going to
1574 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001575 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001576
1577 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001578 } else {
1579 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001580 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001581 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001582 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1583 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1584 if (Class->isInterface() &&
1585 (!RD->isInterface() ||
1586 KnownBase->getAccessSpecifier() != AS_public)) {
1587 // The Microsoft extension __interface does not permit bases that
1588 // are not themselves public interfaces.
1589 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1590 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1591 << RD->getSourceRange();
1592 Invalid = true;
1593 }
1594 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001595 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001596 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001597 }
1598 }
1599
1600 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001601 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001602
1603 // Delete the remaining (good) base class specifiers, since their
1604 // data has been copied into the CXXRecordDecl.
1605 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001606 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001607
1608 return Invalid;
1609}
1610
1611/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1612/// class, after checking whether there are any duplicate base
1613/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001614void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001615 unsigned NumBases) {
1616 if (!ClassDecl || !Bases || !NumBases)
1617 return;
1618
1619 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001620 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001621}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001622
Douglas Gregor36d1b142009-10-06 17:59:45 +00001623/// \brief Determine whether the type \p Derived is a C++ class that is
1624/// derived from the type \p Base.
1625bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001626 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001627 return false;
John McCalle78aac42010-03-10 03:28:59 +00001628
Douglas Gregor45bb4832013-03-26 23:36:30 +00001629 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001630 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001631 return false;
1632
Douglas Gregor45bb4832013-03-26 23:36:30 +00001633 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001634 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001635 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001636
1637 // If either the base or the derived type is invalid, don't try to
1638 // check whether one is derived from the other.
1639 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1640 return false;
1641
John McCall67da35c2010-02-04 22:26:26 +00001642 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1643 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644}
1645
1646/// \brief Determine whether the type \p Derived is a C++ class that is
1647/// derived from the type \p Base.
1648bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001649 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001650 return false;
1651
Douglas Gregor45bb4832013-03-26 23:36:30 +00001652 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001653 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 return false;
1655
Douglas Gregor45bb4832013-03-26 23:36:30 +00001656 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001657 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001658 return false;
1659
Douglas Gregor36d1b142009-10-06 17:59:45 +00001660 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1661}
1662
Anders Carlssona70cff62010-04-24 19:06:50 +00001663void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001664 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001665 assert(BasePathArray.empty() && "Base path array must be empty!");
1666 assert(Paths.isRecordingPaths() && "Must record paths!");
1667
1668 const CXXBasePath &Path = Paths.front();
1669
1670 // We first go backward and check if we have a virtual base.
1671 // FIXME: It would be better if CXXBasePath had the base specifier for
1672 // the nearest virtual base.
1673 unsigned Start = 0;
1674 for (unsigned I = Path.size(); I != 0; --I) {
1675 if (Path[I - 1].Base->isVirtual()) {
1676 Start = I - 1;
1677 break;
1678 }
1679 }
1680
1681 // Now add all bases.
1682 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001683 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001684}
1685
Douglas Gregor88d292c2010-05-13 16:44:06 +00001686/// \brief Determine whether the given base path includes a virtual
1687/// base class.
John McCallcf142162010-08-07 06:22:56 +00001688bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1689 for (CXXCastPath::const_iterator B = BasePath.begin(),
1690 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001691 B != BEnd; ++B)
1692 if ((*B)->isVirtual())
1693 return true;
1694
1695 return false;
1696}
1697
Douglas Gregor36d1b142009-10-06 17:59:45 +00001698/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1699/// conversion (where Derived and Base are class types) is
1700/// well-formed, meaning that the conversion is unambiguous (and
1701/// that all of the base classes are accessible). Returns true
1702/// and emits a diagnostic if the code is ill-formed, returns false
1703/// otherwise. Loc is the location where this routine should point to
1704/// if there is an error, and Range is the source range to highlight
1705/// if there is an error.
1706bool
1707Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001708 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709 unsigned AmbigiousBaseConvID,
1710 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001711 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001712 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001713 // First, determine whether the path from Derived to Base is
1714 // ambiguous. This is slightly more expensive than checking whether
1715 // the Derived to Base conversion exists, because here we need to
1716 // explore multiple paths to determine if there is an ambiguity.
1717 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1718 /*DetectVirtual=*/false);
1719 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1720 assert(DerivationOkay &&
1721 "Can only be used with a derived-to-base conversion");
1722 (void)DerivationOkay;
1723
1724 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001725 if (InaccessibleBaseID) {
1726 // Check that the base class can be accessed.
1727 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1728 InaccessibleBaseID)) {
1729 case AR_inaccessible:
1730 return true;
1731 case AR_accessible:
1732 case AR_dependent:
1733 case AR_delayed:
1734 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001735 }
John McCall5b0829a2010-02-10 09:31:12 +00001736 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001737
1738 // Build a base path if necessary.
1739 if (BasePath)
1740 BuildBasePathArray(Paths, *BasePath);
1741 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001742 }
1743
David Majnemer626032f2013-06-22 06:43:58 +00001744 if (AmbigiousBaseConvID) {
1745 // We know that the derived-to-base conversion is ambiguous, and
1746 // we're going to produce a diagnostic. Perform the derived-to-base
1747 // search just one more time to compute all of the possible paths so
1748 // that we can print them out. This is more expensive than any of
1749 // the previous derived-to-base checks we've done, but at this point
1750 // performance isn't as much of an issue.
1751 Paths.clear();
1752 Paths.setRecordingPaths(true);
1753 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1754 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1755 (void)StillOkay;
1756
1757 // Build up a textual representation of the ambiguous paths, e.g.,
1758 // D -> B -> A, that will be used to illustrate the ambiguous
1759 // conversions in the diagnostic. We only print one of the paths
1760 // to each base class subobject.
1761 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1762
1763 Diag(Loc, AmbigiousBaseConvID)
1764 << Derived << Base << PathDisplayStr << Range << Name;
1765 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001766 return true;
1767}
1768
1769bool
1770Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001771 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001772 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001773 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001774 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001775 IgnoreAccess ? 0
1776 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001777 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001778 Loc, Range, DeclarationName(),
1779 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001780}
1781
1782
1783/// @brief Builds a string representing ambiguous paths from a
1784/// specific derived class to different subobjects of the same base
1785/// class.
1786///
1787/// This function builds a string that can be used in error messages
1788/// to show the different paths that one can take through the
1789/// inheritance hierarchy to go from the derived class to different
1790/// subobjects of a base class. The result looks something like this:
1791/// @code
1792/// struct D -> struct B -> struct A
1793/// struct D -> struct C -> struct A
1794/// @endcode
1795std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1796 std::string PathDisplayStr;
1797 std::set<unsigned> DisplayedPaths;
1798 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1799 Path != Paths.end(); ++Path) {
1800 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1801 // We haven't displayed a path to this particular base
1802 // class subobject yet.
1803 PathDisplayStr += "\n ";
1804 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1805 for (CXXBasePath::const_iterator Element = Path->begin();
1806 Element != Path->end(); ++Element)
1807 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1808 }
1809 }
1810
1811 return PathDisplayStr;
1812}
1813
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001814//===----------------------------------------------------------------------===//
1815// C++ class member Handling
1816//===----------------------------------------------------------------------===//
1817
Abramo Bagnarad7340582010-06-05 05:09:32 +00001818/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001819bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1820 SourceLocation ASLoc,
1821 SourceLocation ColonLoc,
1822 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001823 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001824 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001825 ASLoc, ColonLoc);
1826 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001827 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001828}
1829
Richard Smith18f07db2012-08-06 03:25:17 +00001830/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001831void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001832 if (D->isInvalidDecl())
1833 return;
1834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001835 // We only care about "override" and "final" declarations.
1836 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1837 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001838
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001839 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001840
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001841 // We can't check dependent instance methods.
1842 if (MD && MD->isInstance() &&
1843 (MD->getParent()->hasAnyDependentBases() ||
1844 MD->getType()->isDependentType()))
1845 return;
1846
1847 if (MD && !MD->isVirtual()) {
1848 // If we have a non-virtual method, check if if hides a virtual method.
1849 // (In that case, it's most likely the method has the wrong type.)
1850 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1851 FindHiddenVirtualMethods(MD, OverloadedMethods);
1852
1853 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001854 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1855 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001856 diag::override_keyword_hides_virtual_member_function)
1857 << "override" << (OverloadedMethods.size() > 1);
1858 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001859 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001860 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001861 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1862 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001863 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001864 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1865 MD->setInvalidDecl();
1866 return;
1867 }
1868 // Fall through into the general case diagnostic.
1869 // FIXME: We might want to attempt typo correction here.
1870 }
1871
1872 if (!MD || !MD->isVirtual()) {
1873 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1874 Diag(OA->getLocation(),
1875 diag::override_keyword_only_allowed_on_virtual_member_functions)
1876 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1877 D->dropAttr<OverrideAttr>();
1878 }
1879 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1880 Diag(FA->getLocation(),
1881 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001882 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1883 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001884 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001885 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001886 return;
1887 }
Richard Smith18f07db2012-08-06 03:25:17 +00001888
Richard Smith18f07db2012-08-06 03:25:17 +00001889 // C++11 [class.virtual]p5:
1890 // If a virtual function is marked with the virt-specifier override and
1891 // does not override a member function of a base class, the program is
1892 // ill-formed.
1893 bool HasOverriddenMethods =
1894 MD->begin_overridden_methods() != MD->end_overridden_methods();
1895 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1896 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1897 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001898}
1899
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001900void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1901 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1902 return;
1903 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1904 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1905 isa<CXXDestructorDecl>(MD))
1906 return;
1907
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001908 if (MD->getLocation().isMacroID()) {
1909 SourceLocation MacroLoc = getSourceManager().getSpellingLoc(MD->getLocation());
1910 if (getSourceManager().isInSystemHeader(MacroLoc))
1911 return;
1912 }
1913
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001914 if (MD->size_overridden_methods() > 0) {
1915 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1916 << MD->getDeclName();
1917 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1918 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1919 }
1920}
1921
Richard Smith18f07db2012-08-06 03:25:17 +00001922/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001923/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001924/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001925bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1926 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001927 FinalAttr *FA = Old->getAttr<FinalAttr>();
1928 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001929 return false;
1930
1931 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001932 << New->getDeclName()
1933 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001934 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1935 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001936}
1937
Daniel Jasper0baec5492012-06-06 08:32:04 +00001938static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001939 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1940 // FIXME: Destruction of ObjC lifetime types has side-effects.
1941 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1942 return !RD->isCompleteDefinition() ||
1943 !RD->hasTrivialDefaultConstructor() ||
1944 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001945 return false;
1946}
1947
John McCall5e77d762013-04-16 07:28:30 +00001948static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001949 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001950 if (it->isDeclspecPropertyAttribute())
1951 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001953}
1954
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001955/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1956/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001957/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001958/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1959/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001960NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001961Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001962 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001963 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001964 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001965 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001966 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1967 DeclarationName Name = NameInfo.getName();
1968 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001969
1970 // For anonymous bitfields, the location should point to the type.
1971 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001972 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001973
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001974 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001975
John McCallb1cd7da2010-06-04 08:34:12 +00001976 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001977 assert(!DS.isFriendSpecified());
1978
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001979 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001980
John McCalldb632ac2012-09-25 07:32:39 +00001981 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1982 // The Microsoft extension __interface only permits public member functions
1983 // and prohibits constructors, destructors, operators, non-public member
1984 // functions, static methods and data members.
1985 unsigned InvalidDecl;
1986 bool ShowDeclName = true;
1987 if (!isFunc)
1988 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1989 else if (AS != AS_public)
1990 InvalidDecl = 2;
1991 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1992 InvalidDecl = 3;
1993 else switch (Name.getNameKind()) {
1994 case DeclarationName::CXXConstructorName:
1995 InvalidDecl = 4;
1996 ShowDeclName = false;
1997 break;
1998
1999 case DeclarationName::CXXDestructorName:
2000 InvalidDecl = 5;
2001 ShowDeclName = false;
2002 break;
2003
2004 case DeclarationName::CXXOperatorName:
2005 case DeclarationName::CXXConversionFunctionName:
2006 InvalidDecl = 6;
2007 break;
2008
2009 default:
2010 InvalidDecl = 0;
2011 break;
2012 }
2013
2014 if (InvalidDecl) {
2015 if (ShowDeclName)
2016 Diag(Loc, diag::err_invalid_member_in_interface)
2017 << (InvalidDecl-1) << Name;
2018 else
2019 Diag(Loc, diag::err_invalid_member_in_interface)
2020 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002021 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002022 }
2023 }
2024
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002025 // C++ 9.2p6: A member shall not be declared to have automatic storage
2026 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002027 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2028 // data members and cannot be applied to names declared const or static,
2029 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002030 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002031 case DeclSpec::SCS_unspecified:
2032 case DeclSpec::SCS_typedef:
2033 case DeclSpec::SCS_static:
2034 break;
2035 case DeclSpec::SCS_mutable:
2036 if (isFunc) {
2037 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002038
Richard Smithb4a9e862013-04-12 22:46:28 +00002039 // FIXME: It would be nicer if the keyword was ignored only for this
2040 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002041 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002042 }
2043 break;
2044 default:
2045 Diag(DS.getStorageClassSpecLoc(),
2046 diag::err_storageclass_invalid_for_member);
2047 D.getMutableDeclSpec().ClearStorageClassSpecs();
2048 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002049 }
2050
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002051 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2052 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002053 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002054
David Blaikie35506f82013-01-30 01:22:18 +00002055 if (DS.isConstexprSpecified() && isInstField) {
2056 SemaDiagnosticBuilder B =
2057 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2058 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2059 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002060 B << 0 << 0;
2061 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2062 B << FixItHint::CreateRemoval(ConstexprLoc);
2063 else {
2064 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2065 D.getMutableDeclSpec().ClearConstexprSpec();
2066 const char *PrevSpec;
2067 unsigned DiagID;
2068 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2069 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2070 (void)Failed;
2071 assert(!Failed && "Making a constexpr member const shouldn't fail");
2072 }
David Blaikie35506f82013-01-30 01:22:18 +00002073 } else {
2074 B << 1;
2075 const char *PrevSpec;
2076 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002077 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002078 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2079 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002080 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002081 "This is the only DeclSpec that should fail to be applied");
2082 B << 1;
2083 } else {
2084 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2085 isInstField = false;
2086 }
2087 }
2088 }
2089
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002090 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002091 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002092 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002093
2094 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002095 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002096 Diag(Loc, diag::err_bad_variable_name)
2097 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002098 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002099 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002100
Benjamin Kramer365082d2012-05-19 16:34:46 +00002101 IdentifierInfo *II = Name.getAsIdentifierInfo();
2102
Douglas Gregor7c26c042011-09-21 14:40:46 +00002103 // Member field could not be with "template" keyword.
2104 // So TemplateParameterLists should be empty in this case.
2105 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002106 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002107 if (TemplateParams->size()) {
2108 // There is no such thing as a member field template.
2109 Diag(D.getIdentifierLoc(), diag::err_template_member)
2110 << II
2111 << SourceRange(TemplateParams->getTemplateLoc(),
2112 TemplateParams->getRAngleLoc());
2113 } else {
2114 // There is an extraneous 'template<>' for this member.
2115 Diag(TemplateParams->getTemplateLoc(),
2116 diag::err_template_member_noparams)
2117 << II
2118 << SourceRange(TemplateParams->getTemplateLoc(),
2119 TemplateParams->getRAngleLoc());
2120 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002121 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002122 }
2123
Douglas Gregora007d362010-10-13 22:19:53 +00002124 if (SS.isSet() && !SS.isInvalid()) {
2125 // The user provided a superfluous scope specifier inside a class
2126 // definition:
2127 //
2128 // class X {
2129 // int X::member;
2130 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002131 if (DeclContext *DC = computeDeclContext(SS, false))
2132 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002133 else
2134 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2135 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002136
Douglas Gregora007d362010-10-13 22:19:53 +00002137 SS.clear();
2138 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002139
John McCall5e77d762013-04-16 07:28:30 +00002140 AttributeList *MSPropertyAttr =
2141 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002142 if (MSPropertyAttr) {
2143 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2144 BitWidth, InitStyle, AS, MSPropertyAttr);
2145 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002146 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002147 isInstField = false;
2148 } else {
2149 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2150 BitWidth, InitStyle, AS);
2151 assert(Member && "HandleField never returns null");
2152 }
2153 } else {
2154 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2155
2156 Member = HandleDeclarator(S, D, TemplateParameterLists);
2157 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002158 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002159
2160 // Non-instance-fields can't have a bitfield.
2161 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002162 if (Member->isInvalidDecl()) {
2163 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002164 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002165 // C++ 9.6p3: A bit-field shall not be a static member.
2166 // "static member 'A' cannot be a bit-field"
2167 Diag(Loc, diag::err_static_not_bitfield)
2168 << Name << BitWidth->getSourceRange();
2169 } else if (isa<TypedefDecl>(Member)) {
2170 // "typedef member 'x' cannot be a bit-field"
2171 Diag(Loc, diag::err_typedef_not_bitfield)
2172 << Name << BitWidth->getSourceRange();
2173 } else {
2174 // A function typedef ("typedef int f(); f a;").
2175 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2176 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002177 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002178 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002179 }
Mike Stump11289f42009-09-09 15:08:12 +00002180
Craig Topperc3ec1492014-05-26 06:22:03 +00002181 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002182 Member->setInvalidDecl();
2183 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002184
2185 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002186
Larisse Voufo39a1e502013-08-06 01:03:05 +00002187 // If we have declared a member function template or static data member
2188 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002189 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2190 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002191 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2192 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002193 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002194
Richard Smith18f07db2012-08-06 03:25:17 +00002195 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002196 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002197 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002198 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2199 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002200
Douglas Gregorf2f08062011-03-08 17:10:18 +00002201 if (VS.getLastLocation().isValid()) {
2202 // Update the end location of a method that has a virt-specifiers.
2203 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2204 MD->setRangeEnd(VS.getLastLocation());
2205 }
Richard Smith18f07db2012-08-06 03:25:17 +00002206
Anders Carlssonc87f8612011-01-20 06:29:02 +00002207 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002208
Douglas Gregor92751d42008-11-17 22:58:34 +00002209 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002210
Daniel Jasper0baec5492012-06-06 08:32:04 +00002211 if (isInstField) {
2212 FieldDecl *FD = cast<FieldDecl>(Member);
2213 FieldCollector->Add(FD);
2214
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002215 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002216 // Remember all explicit private FieldDecls that have a name, no side
2217 // effects and are not part of a dependent type declaration.
2218 if (!FD->isImplicit() && FD->getDeclName() &&
2219 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002220 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002221 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002222 !InitializationHasSideEffects(*FD))
2223 UnusedPrivateFields.insert(FD);
2224 }
2225 }
2226
John McCall48871652010-08-21 09:40:31 +00002227 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002228}
2229
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002230namespace {
2231 class UninitializedFieldVisitor
2232 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2233 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002234 // List of Decls to generate a warning on. Also remove Decls that become
2235 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002236 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu8d08a272014-08-28 03:23:47 +00002237 // Vector of decls to be removed from the Decl set prior to visiting the
2238 // nodes. These Decls may have been initialized in the prior initializer.
2239 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002240 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002241 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002242 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002243 // InitList is true, special case initialization of FieldDecls matching
2244 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002245 bool InitList;
2246 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002247 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2248
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002249 public:
2250 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002251 UninitializedFieldVisitor(Sema &S,
Richard Trieu8d08a272014-08-28 03:23:47 +00002252 llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002253 : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr),
2254 InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002255
Richard Trieufa1d0a72014-10-17 20:56:10 +00002256 // Returns true if the use of ME is not an uninitialized use.
2257 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2258 bool CheckReferenceOnly) {
2259 llvm::SmallVector<FieldDecl*, 4> Fields;
2260 bool ReferenceField = false;
2261 while (ME) {
2262 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2263 if (!FD)
2264 return false;
2265 Fields.push_back(FD);
2266 if (FD->getType()->isReferenceType())
2267 ReferenceField = true;
2268 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2269 }
2270
2271 // Binding a reference to an unintialized field is not an
2272 // uninitialized use.
2273 if (CheckReferenceOnly && !ReferenceField)
2274 return true;
2275
2276 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2277 // Discard the first field since it is the field decl that is being
2278 // initialized.
2279 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2280 UsedFieldIndex.push_back((*I)->getFieldIndex());
2281 }
2282
2283 for (auto UsedIter = UsedFieldIndex.begin(),
2284 UsedEnd = UsedFieldIndex.end(),
2285 OrigIter = InitFieldIndex.begin(),
2286 OrigEnd = InitFieldIndex.end();
2287 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2288 if (*UsedIter < *OrigIter)
2289 return true;
2290 if (*UsedIter > *OrigIter)
2291 break;
2292 }
2293
2294 return false;
2295 }
2296
Richard Trieu2d779b92014-10-01 03:44:58 +00002297 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2298 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002299 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2300 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002301
Richard Trieu1bc22c12013-09-13 03:20:53 +00002302 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2303 // or union.
2304 MemberExpr *FieldME = ME;
2305
Richard Trieu2d779b92014-10-01 03:44:58 +00002306 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2307
Richard Trieu1bc22c12013-09-13 03:20:53 +00002308 Expr *Base = ME;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002309 while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002310
Richard Trieufa1d0a72014-10-17 20:56:10 +00002311 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002312 return;
2313
Richard Trieufa1d0a72014-10-17 20:56:10 +00002314 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002315 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002316 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002317
Richard Trieu2d779b92014-10-01 03:44:58 +00002318 if (!FieldME->getType().isPODType(S.Context))
2319 AllPODFields = false;
2320
Richard Trieufa1d0a72014-10-17 20:56:10 +00002321 Base = SubME->getBase()->IgnoreParenImpCasts();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002322 }
2323
Richard Trieufd687772013-09-16 20:46:50 +00002324 if (!isa<CXXThisExpr>(Base))
2325 return;
2326
Richard Trieu2d779b92014-10-01 03:44:58 +00002327 if (AddressOf && AllPODFields)
2328 return;
2329
Richard Trieu406e65c2013-09-20 03:03:06 +00002330 ValueDecl* FoundVD = FieldME->getMemberDecl();
2331
Richard Trieuef64e942013-10-25 00:56:00 +00002332 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002333 return;
2334
Richard Trieuef64e942013-10-25 00:56:00 +00002335 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002336
Richard Trieufa1d0a72014-10-17 20:56:10 +00002337 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2338 // Special checking for initializer lists.
2339 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2340 return;
2341 }
2342 } else {
2343 // Prevent double warnings on use of unbounded references.
2344 if (CheckReferenceOnly && !IsReference)
2345 return;
2346 }
Richard Trieuef64e942013-10-25 00:56:00 +00002347
2348 unsigned diag = IsReference
2349 ? diag::warn_reference_field_is_uninit
2350 : diag::warn_field_is_uninit;
2351 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2352 if (Constructor)
2353 S.Diag(Constructor->getLocation(),
2354 diag::note_uninit_in_this_constructor)
2355 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2356
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002357 }
2358
Richard Trieu2d779b92014-10-01 03:44:58 +00002359 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002360 E = E->IgnoreParens();
2361
2362 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002363 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2364 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002365 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002366 }
2367
2368 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002369 Visit(CO->getCond());
2370 HandleValue(CO->getTrueExpr(), AddressOf);
2371 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002372 return;
2373 }
2374
2375 if (BinaryConditionalOperator *BCO =
2376 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002377 Visit(BCO->getCond());
2378 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002379 return;
2380 }
2381
Richard Trieuabf6ec42014-08-27 22:15:10 +00002382 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002383 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002384 return;
2385 }
2386
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002387 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2388 switch (BO->getOpcode()) {
2389 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002390 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002391 case(BO_PtrMemD):
2392 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002393 HandleValue(BO->getLHS(), AddressOf);
2394 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002395 return;
2396 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002397 Visit(BO->getLHS());
2398 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002399 return;
2400 }
2401 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002402
2403 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002404 }
2405
Richard Trieufa1d0a72014-10-17 20:56:10 +00002406 void CheckInitListExpr(InitListExpr *ILE) {
2407 InitFieldIndex.push_back(0);
2408 for (auto Child : ILE->children()) {
2409 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2410 CheckInitListExpr(SubList);
2411 } else {
2412 Visit(Child);
2413 }
2414 ++InitFieldIndex.back();
2415 }
2416 InitFieldIndex.pop_back();
2417 }
2418
Richard Trieu8d08a272014-08-28 03:23:47 +00002419 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2420 FieldDecl *Field) {
2421 // Remove Decls that may have been initialized in the previous
2422 // initializer.
2423 for (ValueDecl* VD : DeclsToRemove)
2424 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002425 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002426
Richard Trieu8d08a272014-08-28 03:23:47 +00002427 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002428 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2429
2430 if (ILE && Field) {
2431 InitList = true;
2432 InitListFieldDecl = Field;
2433 InitFieldIndex.clear();
2434 CheckInitListExpr(ILE);
2435 } else {
2436 InitList = false;
2437 Visit(E);
2438 }
2439
Richard Trieu8d08a272014-08-28 03:23:47 +00002440 if (Field)
2441 Decls.erase(Field);
2442 }
2443
Richard Trieu1bc22c12013-09-13 03:20:53 +00002444 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002445 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002446 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002447 }
2448
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002449 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002450 if (E->getCastKind() == CK_LValueToRValue) {
2451 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2452 return;
2453 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002454
2455 Inherited::VisitImplicitCastExpr(E);
2456 }
2457
Richard Trieu1bc22c12013-09-13 03:20:53 +00002458 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002459 if (E->getConstructor()->isCopyConstructor()) {
2460 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002461 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2462 if (ILE->getNumInits() == 1)
2463 ArgExpr = ILE->getInit(0);
2464 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2465 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002466 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002467 HandleValue(ArgExpr, false /*AddressOf*/);
2468 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002469 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002470 Inherited::VisitCXXConstructExpr(E);
2471 }
2472
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002473 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2474 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002475 if (isa<MemberExpr>(Callee)) {
2476 HandleValue(Callee, false /*AddressOf*/);
2477 return;
2478 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002479
2480 Inherited::VisitCXXMemberCallExpr(E);
2481 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002482
Richard Trieu11fd0792014-08-26 04:30:55 +00002483 void VisitCallExpr(CallExpr *E) {
2484 // Treat std::move as a use.
2485 if (E->getNumArgs() == 1) {
2486 if (FunctionDecl *FD = E->getDirectCallee()) {
2487 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002488 HandleValue(E->getArg(0), false /*AddressOf*/);
2489 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002490 }
2491 }
2492 }
2493
2494 Inherited::VisitCallExpr(E);
2495 }
2496
Richard Trieu406e65c2013-09-20 03:03:06 +00002497 void VisitBinaryOperator(BinaryOperator *E) {
2498 // If a field assignment is detected, remove the field from the
2499 // uninitiailized field set.
2500 if (E->getOpcode() == BO_Assign)
2501 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2502 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002503 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002504 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002505
Richard Trieu52b8b602014-09-25 01:15:40 +00002506 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002507 HandleValue(E->getLHS(), false /*AddressOf*/);
2508 Visit(E->getRHS());
2509 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002510 }
2511
Richard Trieu406e65c2013-09-20 03:03:06 +00002512 Inherited::VisitBinaryOperator(E);
2513 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002514
2515 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002516 if (E->isIncrementDecrementOp()) {
2517 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2518 return;
2519 }
2520 if (E->getOpcode() == UO_AddrOf) {
2521 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2522 HandleValue(ME->getBase(), true /*AddressOf*/);
2523 return;
2524 }
2525 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002526
2527 Inherited::VisitUnaryOperator(E);
2528 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002529 };
Richard Trieuef64e942013-10-25 00:56:00 +00002530
2531 // Diagnose value-uses of fields to initialize themselves, e.g.
2532 // foo(foo)
2533 // where foo is not also a parameter to the constructor.
2534 // Also diagnose across field uninitialized use such as
2535 // x(y), y(x)
2536 // TODO: implement -Wuninitialized and fold this into that framework.
2537 static void DiagnoseUninitializedFields(
2538 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2539
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002540 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2541 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002542 return;
2543 }
2544
2545 if (Constructor->isInvalidDecl())
2546 return;
2547
2548 const CXXRecordDecl *RD = Constructor->getParent();
2549
Richard Trieu353a4b42014-10-22 05:21:59 +00002550 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002551 return;
2552
Richard Trieuef64e942013-10-25 00:56:00 +00002553 // Holds fields that are uninitialized.
2554 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2555
2556 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002557 for (auto *I : RD->decls()) {
2558 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002559 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002560 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002561 UninitializedFields.insert(IFD->getAnonField());
2562 }
2563 }
2564
Richard Trieu8d08a272014-08-28 03:23:47 +00002565 if (UninitializedFields.empty())
2566 return;
2567
2568 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2569 UninitializedFields);
2570
Aaron Ballman0ad78302014-03-13 17:34:31 +00002571 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002572 if (UninitializedFields.empty())
2573 break;
2574
Aaron Ballman0ad78302014-03-13 17:34:31 +00002575 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002576 if (!InitExpr)
2577 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002578
Richard Trieu8d08a272014-08-28 03:23:47 +00002579 if (CXXDefaultInitExpr *Default =
2580 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2581 InitExpr = Default->getExpr();
2582 if (!InitExpr)
2583 continue;
2584 // In class initializers will point to the constructor.
2585 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2586 FieldInit->getAnyMember());
2587 } else {
2588 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2589 FieldInit->getAnyMember());
2590 }
Richard Trieuef64e942013-10-25 00:56:00 +00002591 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002592 }
2593} // namespace
2594
Richard Smith74108172014-01-17 03:11:34 +00002595/// \brief Enter a new C++ default initializer scope. After calling this, the
2596/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2597/// parsing or instantiating the initializer failed.
2598void Sema::ActOnStartCXXInClassMemberInitializer() {
2599 // Create a synthetic function scope to represent the call to the constructor
2600 // that notionally surrounds a use of this initializer.
2601 PushFunctionScope();
2602}
2603
2604/// \brief This is invoked after parsing an in-class initializer for a
2605/// non-static C++ class member, and after instantiating an in-class initializer
2606/// in a class template. Such actions are deferred until the class is complete.
2607void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2608 SourceLocation InitLoc,
2609 Expr *InitExpr) {
2610 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002611 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002612
Richard Smith938f40b2011-06-11 17:19:42 +00002613 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002614 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2615 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002616
2617 if (!InitExpr) {
2618 FD->setInvalidDecl();
2619 FD->removeInClassInitializer();
2620 return;
2621 }
2622
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002623 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2624 FD->setInvalidDecl();
2625 FD->removeInClassInitializer();
2626 return;
2627 }
2628
Richard Smith938f40b2011-06-11 17:19:42 +00002629 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002630 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002631 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002632 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002633 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002634 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002635 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2636 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002637 if (Init.isInvalid()) {
2638 FD->setInvalidDecl();
2639 return;
2640 }
Richard Smith938f40b2011-06-11 17:19:42 +00002641 }
2642
Richard Smith945f8d32013-01-14 22:39:08 +00002643 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002644 // The initialization of each base and member constitutes a
2645 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002646 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002647 if (Init.isInvalid()) {
2648 FD->setInvalidDecl();
2649 return;
2650 }
2651
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002652 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002653
2654 FD->setInClassInitializer(InitExpr);
2655}
2656
Douglas Gregor15e77a22009-12-31 09:10:24 +00002657/// \brief Find the direct and/or virtual base specifiers that
2658/// correspond to the given base type, for use in base initialization
2659/// within a constructor.
2660static bool FindBaseInitializer(Sema &SemaRef,
2661 CXXRecordDecl *ClassDecl,
2662 QualType BaseType,
2663 const CXXBaseSpecifier *&DirectBaseSpec,
2664 const CXXBaseSpecifier *&VirtualBaseSpec) {
2665 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002666 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002667 for (const auto &Base : ClassDecl->bases()) {
2668 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002669 // We found a direct base of this type. That's what we're
2670 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002671 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002672 break;
2673 }
2674 }
2675
2676 // Check for a virtual base class.
2677 // FIXME: We might be able to short-circuit this if we know in advance that
2678 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002679 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002680 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2681 // We haven't found a base yet; search the class hierarchy for a
2682 // virtual base class.
2683 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2684 /*DetectVirtual=*/false);
2685 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2686 BaseType, Paths)) {
2687 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2688 Path != Paths.end(); ++Path) {
2689 if (Path->back().Base->isVirtual()) {
2690 VirtualBaseSpec = Path->back().Base;
2691 break;
2692 }
2693 }
2694 }
2695 }
2696
2697 return DirectBaseSpec || VirtualBaseSpec;
2698}
2699
Sebastian Redla74948d2011-09-24 17:48:25 +00002700/// \brief Handle a C++ member initializer using braced-init-list syntax.
2701MemInitResult
2702Sema::ActOnMemInitializer(Decl *ConstructorD,
2703 Scope *S,
2704 CXXScopeSpec &SS,
2705 IdentifierInfo *MemberOrBase,
2706 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002707 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002708 SourceLocation IdLoc,
2709 Expr *InitList,
2710 SourceLocation EllipsisLoc) {
2711 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002712 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002713 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002714}
2715
2716/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002717MemInitResult
John McCall48871652010-08-21 09:40:31 +00002718Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002719 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002720 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002721 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002722 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002723 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002724 SourceLocation IdLoc,
2725 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002726 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002727 SourceLocation RParenLoc,
2728 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002729 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002730 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002731 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002732 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002733}
2734
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002735namespace {
2736
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002737// Callback to only accept typo corrections that can be a valid C++ member
2738// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002739class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002740public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002741 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2742 : ClassDecl(ClassDecl) {}
2743
Craig Toppera798a9d2014-03-02 09:32:10 +00002744 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002745 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2746 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2747 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002748 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002749 }
2750 return false;
2751 }
2752
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002753private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002754 CXXRecordDecl *ClassDecl;
2755};
2756
2757}
2758
Sebastian Redla74948d2011-09-24 17:48:25 +00002759/// \brief Handle a C++ member initializer.
2760MemInitResult
2761Sema::BuildMemInitializer(Decl *ConstructorD,
2762 Scope *S,
2763 CXXScopeSpec &SS,
2764 IdentifierInfo *MemberOrBase,
2765 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002766 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002767 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002768 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002769 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002770 if (!ConstructorD)
2771 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002772
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002773 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002774
2775 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002776 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002777 if (!Constructor) {
2778 // The user wrote a constructor initializer on a function that is
2779 // not a C++ constructor. Ignore the error for now, because we may
2780 // have more member initializers coming; we'll diagnose it just
2781 // once in ActOnMemInitializers.
2782 return true;
2783 }
2784
2785 CXXRecordDecl *ClassDecl = Constructor->getParent();
2786
2787 // C++ [class.base.init]p2:
2788 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002789 // constructor's class and, if not found in that scope, are looked
2790 // up in the scope containing the constructor's definition.
2791 // [Note: if the constructor's class contains a member with the
2792 // same name as a direct or virtual base class of the class, a
2793 // mem-initializer-id naming the member or base class and composed
2794 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002795 // mem-initializer-id for the hidden base class may be specified
2796 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002797 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002798 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002799 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002800 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002801 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002802 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002803 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2804 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002805 if (EllipsisLoc.isValid())
2806 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002807 << MemberOrBase
2808 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002809
Sebastian Redla9351792012-02-11 23:51:47 +00002810 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002811 }
Francois Pichetd583da02010-12-04 09:14:42 +00002812 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002813 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002814 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002815 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002816 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002817
2818 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002819 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002820 } else if (DS.getTypeSpecType() == TST_decltype) {
2821 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002822 } else {
2823 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2824 LookupParsedName(R, S, &SS);
2825
2826 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2827 if (!TyD) {
2828 if (R.isAmbiguous()) return true;
2829
John McCallda6841b2010-04-09 19:01:14 +00002830 // We don't want access-control diagnostics here.
2831 R.suppressDiagnostics();
2832
Douglas Gregora3b624a2010-01-19 06:46:48 +00002833 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2834 bool NotUnknownSpecialization = false;
2835 DeclContext *DC = computeDeclContext(SS, false);
2836 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2837 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2838
2839 if (!NotUnknownSpecialization) {
2840 // When the scope specifier can refer to a member of an unknown
2841 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002842 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2843 SS.getWithLocInContext(Context),
2844 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002845 if (BaseType.isNull())
2846 return true;
2847
Douglas Gregora3b624a2010-01-19 06:46:48 +00002848 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002849 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002850 }
2851 }
2852
Douglas Gregor15e77a22009-12-31 09:10:24 +00002853 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002854 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002855 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002856 (Corr = CorrectTypo(
2857 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2858 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2859 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002860 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002861 // We have found a non-static data member with a similar
2862 // name to what was typed; complain and initialize that
2863 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002864 diagnoseTypo(Corr,
2865 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2866 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002867 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002868 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002869 const CXXBaseSpecifier *DirectBaseSpec;
2870 const CXXBaseSpecifier *VirtualBaseSpec;
2871 if (FindBaseInitializer(*this, ClassDecl,
2872 Context.getTypeDeclType(Type),
2873 DirectBaseSpec, VirtualBaseSpec)) {
2874 // We have found a direct or virtual base class with a
2875 // similar name to what was typed; complain and initialize
2876 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002877 diagnoseTypo(Corr,
2878 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2879 << MemberOrBase << false,
2880 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002881
Richard Smithf9b15102013-08-17 00:46:16 +00002882 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2883 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002884 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002885 diag::note_base_class_specified_here)
2886 << BaseSpec->getType()
2887 << BaseSpec->getSourceRange();
2888
Douglas Gregor15e77a22009-12-31 09:10:24 +00002889 TyD = Type;
2890 }
2891 }
2892 }
2893
Douglas Gregora3b624a2010-01-19 06:46:48 +00002894 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002895 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002896 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002897 return true;
2898 }
John McCallb5a0d312009-12-21 10:41:20 +00002899 }
2900
Douglas Gregora3b624a2010-01-19 06:46:48 +00002901 if (BaseType.isNull()) {
2902 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002903 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002904 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002905 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2906 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002907 }
2908 }
Mike Stump11289f42009-09-09 15:08:12 +00002909
John McCallbcd03502009-12-07 02:54:59 +00002910 if (!TInfo)
2911 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002912
Sebastian Redla9351792012-02-11 23:51:47 +00002913 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002914}
2915
Chandler Carruth599deef2011-09-03 01:14:15 +00002916/// Checks a member initializer expression for cases where reference (or
2917/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002918static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2919 Expr *Init,
2920 SourceLocation IdLoc) {
2921 QualType MemberTy = Member->getType();
2922
2923 // We only handle pointers and references currently.
2924 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2925 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2926 return;
2927
2928 const bool IsPointer = MemberTy->isPointerType();
2929 if (IsPointer) {
2930 if (const UnaryOperator *Op
2931 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2932 // The only case we're worried about with pointers requires taking the
2933 // address.
2934 if (Op->getOpcode() != UO_AddrOf)
2935 return;
2936
2937 Init = Op->getSubExpr();
2938 } else {
2939 // We only handle address-of expression initializers for pointers.
2940 return;
2941 }
2942 }
2943
Richard Smithe3b28bc2013-06-12 21:51:50 +00002944 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002945 // We only warn when referring to a non-reference parameter declaration.
2946 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2947 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002948 return;
2949
2950 S.Diag(Init->getExprLoc(),
2951 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2952 : diag::warn_bind_ref_member_to_parameter)
2953 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002954 } else {
2955 // Other initializers are fine.
2956 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002957 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002958
2959 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2960 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002961}
2962
John McCallfaf5fb42010-08-26 23:41:50 +00002963MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002964Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002965 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002966 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2967 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2968 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002969 "Member must be a FieldDecl or IndirectFieldDecl");
2970
Sebastian Redla9351792012-02-11 23:51:47 +00002971 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002972 return true;
2973
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002974 if (Member->isInvalidDecl())
2975 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002976
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002977 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002978 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002979 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002980 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002981 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002982 } else {
2983 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002984 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002985 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002986
Sebastian Redla9351792012-02-11 23:51:47 +00002987 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002988
Sebastian Redla9351792012-02-11 23:51:47 +00002989 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002990 // Can't check initialization for a member of dependent type or when
2991 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002992 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002993 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002994 bool InitList = false;
2995 if (isa<InitListExpr>(Init)) {
2996 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002997 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002998 }
2999
Chandler Carruthd44c3102010-12-06 09:23:57 +00003000 // Initialize the member.
3001 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003002 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3003 : InitializedEntity::InitializeMember(IndirectMember,
3004 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003005 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003006 InitList ? InitializationKind::CreateDirectList(IdLoc)
3007 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3008 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003009
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003010 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003011 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3012 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003013 if (MemberInit.isInvalid())
3014 return true;
3015
Richard Smith736a9472013-06-12 20:42:33 +00003016 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3017
Richard Smith945f8d32013-01-14 22:39:08 +00003018 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003019 // The initialization of each base and member constitutes a
3020 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003021 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003022 if (MemberInit.isInvalid())
3023 return true;
3024
Richard Smithd59b8322012-12-19 01:39:02 +00003025 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003026 }
3027
Chandler Carruthd44c3102010-12-06 09:23:57 +00003028 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003029 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3030 InitRange.getBegin(), Init,
3031 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003032 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003033 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3034 InitRange.getBegin(), Init,
3035 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003036 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003037}
3038
John McCallfaf5fb42010-08-26 23:41:50 +00003039MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003040Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003041 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003042 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003043 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003044 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003045 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003046 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003047
Sebastian Redl0501c632012-02-12 16:37:36 +00003048 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003049 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003050 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3051 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003052 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003053 }
3054
Sebastian Redla9351792012-02-11 23:51:47 +00003055 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003056 // Initialize the object.
3057 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3058 QualType(ClassDecl->getTypeForDecl(), 0));
3059 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003060 InitList ? InitializationKind::CreateDirectList(NameLoc)
3061 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3062 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003063 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003064 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003065 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003066 if (DelegationInit.isInvalid())
3067 return true;
3068
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003069 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3070 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003071
Richard Smith945f8d32013-01-14 22:39:08 +00003072 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003073 // The initialization of each base and member constitutes a
3074 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003075 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3076 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003077 if (DelegationInit.isInvalid())
3078 return true;
3079
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003080 // If we are in a dependent context, template instantiation will
3081 // perform this type-checking again. Just save the arguments that we
3082 // received in a ParenListExpr.
3083 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3084 // of the information that we have about the base
3085 // initializer. However, deconstructing the ASTs is a dicey process,
3086 // and this approach is far more likely to get the corner cases right.
3087 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003088 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003089
Sebastian Redla9351792012-02-11 23:51:47 +00003090 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003091 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003092 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003093}
3094
3095MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003096Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003097 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003098 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003099 SourceLocation BaseLoc
3100 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003101
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003102 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3103 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3104 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3105
3106 // C++ [class.base.init]p2:
3107 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003108 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003109 // of that class, the mem-initializer is ill-formed. A
3110 // mem-initializer-list can initialize a base class using any
3111 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003112 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003113
Sebastian Redla9351792012-02-11 23:51:47 +00003114 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003115 if (EllipsisLoc.isValid()) {
3116 // This is a pack expansion.
3117 if (!BaseType->containsUnexpandedParameterPack()) {
3118 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003119 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003120
Douglas Gregor44e7df62011-01-04 00:32:56 +00003121 EllipsisLoc = SourceLocation();
3122 }
3123 } else {
3124 // Check for any unexpanded parameter packs.
3125 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3126 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003127
Sebastian Redla9351792012-02-11 23:51:47 +00003128 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003129 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003130 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003131
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003132 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003133 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3134 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003135 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003136 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3137 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003138 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003139
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003140 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3141 VirtualBaseSpec);
3142
3143 // C++ [base.class.init]p2:
3144 // Unless the mem-initializer-id names a nonstatic data member of the
3145 // constructor's class or a direct or virtual base of that class, the
3146 // mem-initializer is ill-formed.
3147 if (!DirectBaseSpec && !VirtualBaseSpec) {
3148 // If the class has any dependent bases, then it's possible that
3149 // one of those types will resolve to the same type as
3150 // BaseType. Therefore, just treat this as a dependent base
3151 // class initialization. FIXME: Should we try to check the
3152 // initialization anyway? It seems odd.
3153 if (ClassDecl->hasAnyDependentBases())
3154 Dependent = true;
3155 else
3156 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3157 << BaseType << Context.getTypeDeclType(ClassDecl)
3158 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3159 }
3160 }
3161
3162 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003163 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003164
Sebastian Redla74948d2011-09-24 17:48:25 +00003165 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3166 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003167 InitRange.getBegin(), Init,
3168 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003169 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003170
3171 // C++ [base.class.init]p2:
3172 // If a mem-initializer-id is ambiguous because it designates both
3173 // a direct non-virtual base class and an inherited virtual base
3174 // class, the mem-initializer is ill-formed.
3175 if (DirectBaseSpec && VirtualBaseSpec)
3176 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003177 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003178
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003179 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003180 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003181 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003182
3183 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003184 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003185 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003186 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003187 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003188 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003189 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003190
3191 InitializedEntity BaseEntity =
3192 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3193 InitializationKind Kind =
3194 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3195 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3196 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003197 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003198 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003199 if (BaseInit.isInvalid())
3200 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003201
Richard Smith945f8d32013-01-14 22:39:08 +00003202 // C++11 [class.base.init]p7:
3203 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003204 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003205 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003206 if (BaseInit.isInvalid())
3207 return true;
3208
3209 // If we are in a dependent context, template instantiation will
3210 // perform this type-checking again. Just save the arguments that we
3211 // received in a ParenListExpr.
3212 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3213 // of the information that we have about the base
3214 // initializer. However, deconstructing the ASTs is a dicey process,
3215 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003216 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003217 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003218
Alexis Hunt1d792652011-01-08 20:30:50 +00003219 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003220 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003221 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003222 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003223 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003224}
3225
Sebastian Redl22653ba2011-08-30 19:58:05 +00003226// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003227static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3228 if (T.isNull()) T = E->getType();
3229 QualType TargetType = SemaRef.BuildReferenceType(
3230 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003231 SourceLocation ExprLoc = E->getLocStart();
3232 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3233 TargetType, ExprLoc);
3234
3235 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3236 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003237 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003238}
3239
Anders Carlsson1b00e242010-04-23 03:10:23 +00003240/// ImplicitInitializerKind - How an implicit base or member initializer should
3241/// initialize its base or member.
3242enum ImplicitInitializerKind {
3243 IIK_Default,
3244 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003245 IIK_Move,
3246 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003247};
3248
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003249static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003250BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003251 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003252 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003253 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003254 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003255 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003256 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3257 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003258
John McCalldadc5752010-08-24 06:29:42 +00003259 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003260
3261 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003262 case IIK_Inherit: {
3263 const CXXRecordDecl *Inherited =
3264 Constructor->getInheritedConstructor()->getParent();
3265 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3266 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3267 // C++11 [class.inhctor]p8:
3268 // Each expression in the expression-list is of the form
3269 // static_cast<T&&>(p), where p is the name of the corresponding
3270 // constructor parameter and T is the declared type of p.
3271 SmallVector<Expr*, 16> Args;
3272 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3273 ParmVarDecl *PD = Constructor->getParamDecl(I);
3274 ExprResult ArgExpr =
3275 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3276 VK_LValue, SourceLocation());
3277 if (ArgExpr.isInvalid())
3278 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003279 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003280 }
3281
3282 InitializationKind InitKind = InitializationKind::CreateDirect(
3283 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003284 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003285 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3286 break;
3287 }
3288 }
3289 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003290 case IIK_Default: {
3291 InitializationKind InitKind
3292 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003293 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3294 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003295 break;
3296 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003297
Sebastian Redl22653ba2011-08-30 19:58:05 +00003298 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003299 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003300 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003301 ParmVarDecl *Param = Constructor->getParamDecl(0);
3302 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003303
Anders Carlsson1b00e242010-04-23 03:10:23 +00003304 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003305 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003306 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003307 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003309
Eli Friedmanfa0df832012-02-02 03:46:19 +00003310 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3311
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003312 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003313 QualType ArgTy =
3314 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3315 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003316
Sebastian Redl22653ba2011-08-30 19:58:05 +00003317 if (Moving) {
3318 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3319 }
3320
John McCallcf142162010-08-07 06:22:56 +00003321 CXXCastPath BasePath;
3322 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003323 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3324 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003325 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003326 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003327
Anders Carlsson1b00e242010-04-23 03:10:23 +00003328 InitializationKind InitKind
3329 = InitializationKind::CreateDirect(Constructor->getLocation(),
3330 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003331 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3332 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003333 break;
3334 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003335 }
John McCallb268a282010-08-23 23:25:46 +00003336
Douglas Gregora40433a2010-12-07 00:41:46 +00003337 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003338 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003339 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003340
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003341 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003342 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003343 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3344 SourceLocation()),
3345 BaseSpec->isVirtual(),
3346 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003347 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003348 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003349 SourceLocation());
3350
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003351 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003352}
3353
Sebastian Redl22653ba2011-08-30 19:58:05 +00003354static bool RefersToRValueRef(Expr *MemRef) {
3355 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3356 return Referenced->getType()->isRValueReferenceType();
3357}
3358
Anders Carlsson3c1db572010-04-23 02:15:47 +00003359static bool
3360BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003361 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003362 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003363 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003364 if (Field->isInvalidDecl())
3365 return true;
3366
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003367 SourceLocation Loc = Constructor->getLocation();
3368
Sebastian Redl22653ba2011-08-30 19:58:05 +00003369 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3370 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003371 ParmVarDecl *Param = Constructor->getParamDecl(0);
3372 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003373
3374 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003375 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3376 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003377
Anders Carlsson423f5d82010-04-23 16:04:08 +00003378 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003379 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003380 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003381 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003382
Eli Friedmanfa0df832012-02-02 03:46:19 +00003383 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3384
Sebastian Redl22653ba2011-08-30 19:58:05 +00003385 if (Moving) {
3386 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3387 }
3388
Douglas Gregor94f9a482010-05-05 05:51:00 +00003389 // Build a reference to this field within the parameter.
3390 CXXScopeSpec SS;
3391 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3392 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003393 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3394 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003395 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003396 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003397 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003398 ParamType, Loc,
3399 /*IsArrow=*/false,
3400 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003401 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003402 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003403 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003404 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003405 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003406 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003407
3408 // C++11 [class.copy]p15:
3409 // - if a member m has rvalue reference type T&&, it is direct-initialized
3410 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003411 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003412 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003413 }
3414
Douglas Gregor94f9a482010-05-05 05:51:00 +00003415 // When the field we are copying is an array, create index variables for
3416 // each dimension of the array. We use these index variables to subscript
3417 // the source array, and other clients (e.g., CodeGen) will perform the
3418 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003419 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003420 QualType BaseType = Field->getType();
3421 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003422 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003423 while (const ConstantArrayType *Array
3424 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003425 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003426 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003427 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003428 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003429 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003430 llvm::raw_svector_ostream OS(Str);
3431 OS << "__i" << IndexVariables.size();
3432 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3433 }
3434 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003435 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003436 IterationVarName, SizeType,
3437 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003438 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003439 IndexVariables.push_back(IterationVar);
3440
3441 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003442 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003443 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003444 assert(!IterationVarRef.isInvalid() &&
3445 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003446 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003447 assert(!IterationVarRef.isInvalid() &&
3448 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003449
Douglas Gregor94f9a482010-05-05 05:51:00 +00003450 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003451 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3452 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003453 Loc);
3454 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003455 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003456
Douglas Gregor94f9a482010-05-05 05:51:00 +00003457 BaseType = Array->getElementType();
3458 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003459
3460 // The array subscript expression is an lvalue, which is wrong for moving.
3461 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003462 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003463
Douglas Gregor94f9a482010-05-05 05:51:00 +00003464 // Construct the entity that we will be initializing. For an array, this
3465 // will be first element in the array, which may require several levels
3466 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003467 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003468 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003469 if (Indirect)
3470 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3471 else
3472 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003473 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3474 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3475 0,
3476 Entities.back()));
3477
3478 // Direct-initialize to use the copy constructor.
3479 InitializationKind InitKind =
3480 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3481
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003482 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003483 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003484
John McCalldadc5752010-08-24 06:29:42 +00003485 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003486 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003487 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003488 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003489 if (MemberInit.isInvalid())
3490 return true;
3491
Douglas Gregor493627b2011-08-10 15:22:55 +00003492 if (Indirect) {
3493 assert(IndexVariables.size() == 0 &&
3494 "Indirect field improperly initialized");
3495 CXXMemberInit
3496 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3497 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003498 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003499 Loc);
3500 } else
3501 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003502 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003503 Loc,
3504 IndexVariables.data(),
3505 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003506 return false;
3507 }
3508
Richard Smithc2bc61b2013-03-18 21:12:30 +00003509 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3510 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003511
Anders Carlsson3c1db572010-04-23 02:15:47 +00003512 QualType FieldBaseElementType =
3513 SemaRef.Context.getBaseElementType(Field->getType());
3514
Anders Carlsson3c1db572010-04-23 02:15:47 +00003515 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003516 InitializedEntity InitEntity
3517 = Indirect? InitializedEntity::InitializeMember(Indirect)
3518 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003519 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003520 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003521
3522 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3523 ExprResult MemberInit =
3524 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003525
Douglas Gregora40433a2010-12-07 00:41:46 +00003526 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003527 if (MemberInit.isInvalid())
3528 return true;
3529
Douglas Gregor493627b2011-08-10 15:22:55 +00003530 if (Indirect)
3531 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3532 Indirect, Loc,
3533 Loc,
3534 MemberInit.get(),
3535 Loc);
3536 else
3537 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3538 Field, Loc, Loc,
3539 MemberInit.get(),
3540 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003541 return false;
3542 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003543
Alexis Hunt8b455182011-05-17 00:19:05 +00003544 if (!Field->getParent()->isUnion()) {
3545 if (FieldBaseElementType->isReferenceType()) {
3546 SemaRef.Diag(Constructor->getLocation(),
3547 diag::err_uninitialized_member_in_ctor)
3548 << (int)Constructor->isImplicit()
3549 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3550 << 0 << Field->getDeclName();
3551 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3552 return true;
3553 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003554
Alexis Hunt8b455182011-05-17 00:19:05 +00003555 if (FieldBaseElementType.isConstQualified()) {
3556 SemaRef.Diag(Constructor->getLocation(),
3557 diag::err_uninitialized_member_in_ctor)
3558 << (int)Constructor->isImplicit()
3559 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3560 << 1 << Field->getDeclName();
3561 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3562 return true;
3563 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003564 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003565
David Blaikiebbafb8a2012-03-11 07:00:24 +00003566 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003567 FieldBaseElementType->isObjCRetainableType() &&
3568 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3569 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003570 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003571 // Default-initialize Objective-C pointers to NULL.
3572 CXXMemberInit
3573 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3574 Loc, Loc,
3575 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3576 Loc);
3577 return false;
3578 }
3579
Anders Carlsson3c1db572010-04-23 02:15:47 +00003580 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003581 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003582 return false;
3583}
John McCallbc83b3f2010-05-20 23:23:51 +00003584
3585namespace {
3586struct BaseAndFieldInfo {
3587 Sema &S;
3588 CXXConstructorDecl *Ctor;
3589 bool AnyErrorsInInits;
3590 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003591 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003592 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003593 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003594
3595 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3596 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003597 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3598 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003599 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003600 else if (Generated && Ctor->isMoveConstructor())
3601 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003602 else if (Ctor->getInheritedConstructor())
3603 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003604 else
3605 IIK = IIK_Default;
3606 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003607
3608 bool isImplicitCopyOrMove() const {
3609 switch (IIK) {
3610 case IIK_Copy:
3611 case IIK_Move:
3612 return true;
3613
3614 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003615 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003616 return false;
3617 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003618
3619 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003620 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003621
3622 bool addFieldInitializer(CXXCtorInitializer *Init) {
3623 AllToInit.push_back(Init);
3624
3625 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003626 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003627 S.UnusedPrivateFields.remove(Init->getAnyMember());
3628
3629 return false;
3630 }
John McCallbc83b3f2010-05-20 23:23:51 +00003631
Richard Smithab44d5b2013-12-10 08:25:00 +00003632 bool isInactiveUnionMember(FieldDecl *Field) {
3633 RecordDecl *Record = Field->getParent();
3634 if (!Record->isUnion())
3635 return false;
3636
Richard Smith8d183852013-12-10 20:56:03 +00003637 if (FieldDecl *Active =
3638 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003639 return Active != Field->getCanonicalDecl();
3640
3641 // In an implicit copy or move constructor, ignore any in-class initializer.
3642 if (isImplicitCopyOrMove())
3643 return true;
3644
3645 // If there's no explicit initialization, the field is active only if it
3646 // has an in-class initializer...
3647 if (Field->hasInClassInitializer())
3648 return false;
3649 // ... or it's an anonymous struct or union whose class has an in-class
3650 // initializer.
3651 if (!Field->isAnonymousStructOrUnion())
3652 return true;
3653 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3654 return !FieldRD->hasInClassInitializer();
3655 }
3656
3657 /// \brief Determine whether the given field is, or is within, a union member
3658 /// that is inactive (because there was an initializer given for a different
3659 /// member of the union, or because the union was not initialized at all).
3660 bool isWithinInactiveUnionMember(FieldDecl *Field,
3661 IndirectFieldDecl *Indirect) {
3662 if (!Indirect)
3663 return isInactiveUnionMember(Field);
3664
Aaron Ballman29c94602014-03-07 18:36:15 +00003665 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003666 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003667 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003668 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003669 }
3670 return false;
3671 }
3672};
Richard Smithc94ec842011-09-19 13:34:43 +00003673}
3674
Douglas Gregor10f939c2011-11-02 23:04:16 +00003675/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3676/// array type.
3677static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3678 if (T->isIncompleteArrayType())
3679 return true;
3680
3681 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3682 if (!ArrayT->getSize())
3683 return true;
3684
3685 T = ArrayT->getElementType();
3686 }
3687
3688 return false;
3689}
3690
Richard Smith938f40b2011-06-11 17:19:42 +00003691static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003692 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003693 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003694 if (Field->isInvalidDecl())
3695 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003696
Chandler Carruth139e9622010-06-30 02:59:29 +00003697 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003698 if (CXXCtorInitializer *Init =
3699 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003700 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003701
Richard Smithab44d5b2013-12-10 08:25:00 +00003702 // C++11 [class.base.init]p8:
3703 // if the entity is a non-static data member that has a
3704 // brace-or-equal-initializer and either
3705 // -- the constructor's class is a union and no other variant member of that
3706 // union is designated by a mem-initializer-id or
3707 // -- the constructor's class is not a union, and, if the entity is a member
3708 // of an anonymous union, no other member of that union is designated by
3709 // a mem-initializer-id,
3710 // the entity is initialized as specified in [dcl.init].
3711 //
3712 // We also apply the same rules to handle anonymous structs within anonymous
3713 // unions.
3714 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3715 return false;
3716
Douglas Gregor7db3e952011-11-28 20:03:15 +00003717 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003718 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3719 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003720 CXXCtorInitializer *Init;
3721 if (Indirect)
3722 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3723 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003724 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003725 SourceLocation());
3726 else
3727 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3728 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003729 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003730 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003731 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003732 }
3733
Douglas Gregor10f939c2011-11-02 23:04:16 +00003734 // Don't initialize incomplete or zero-length arrays.
3735 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3736 return false;
3737
John McCallbc83b3f2010-05-20 23:23:51 +00003738 // Don't try to build an implicit initializer if there were semantic
3739 // errors in any of the initializers (and therefore we might be
3740 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003741 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003742 return false;
3743
Craig Topperc3ec1492014-05-26 06:22:03 +00003744 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003745 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3746 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003747 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003748
Richard Smith0a8cfc72012-08-07 21:30:42 +00003749 if (!Init)
3750 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003751
Richard Smith0a8cfc72012-08-07 21:30:42 +00003752 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003753}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003754
3755bool
3756Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3757 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003758 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003759 Constructor->setNumCtorInitializers(1);
3760 CXXCtorInitializer **initializer =
3761 new (Context) CXXCtorInitializer*[1];
3762 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3763 Constructor->setCtorInitializers(initializer);
3764
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003765 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003766 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003767 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3768 }
3769
Alexis Hunte2622992011-05-05 00:05:47 +00003770 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003771
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003772 DiagnoseUninitializedFields(*this, Constructor);
3773
Alexis Hunt61bc1732011-05-01 07:04:31 +00003774 return false;
3775}
Douglas Gregor493627b2011-08-10 15:22:55 +00003776
David Blaikie3fc2f912013-01-17 05:26:25 +00003777bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3778 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003779 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003780 // Just store the initializers as written, they will be checked during
3781 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003782 if (!Initializers.empty()) {
3783 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003784 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003785 new (Context) CXXCtorInitializer*[Initializers.size()];
3786 memcpy(baseOrMemberInitializers, Initializers.data(),
3787 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003788 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003789 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003790
3791 // Let template instantiation know whether we had errors.
3792 if (AnyErrors)
3793 Constructor->setInvalidDecl();
3794
Anders Carlssondb0a9652010-04-02 06:26:44 +00003795 return false;
3796 }
3797
John McCallbc83b3f2010-05-20 23:23:51 +00003798 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003799
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003800 // We need to build the initializer AST according to order of construction
3801 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003802 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003803 if (!ClassDecl)
3804 return true;
3805
Eli Friedman9cf6b592009-11-09 19:20:36 +00003806 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003807
David Blaikie3fc2f912013-01-17 05:26:25 +00003808 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003809 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003810
Anders Carlssondb0a9652010-04-02 06:26:44 +00003811 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003812 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003813 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003814 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003815
3816 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003817 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003818 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003819 if (FD && FD->getParent()->isUnion())
3820 Info.ActiveUnionMember.insert(std::make_pair(
3821 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3822 }
3823 } else if (FieldDecl *FD = Member->getMember()) {
3824 if (FD->getParent()->isUnion())
3825 Info.ActiveUnionMember.insert(std::make_pair(
3826 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3827 }
3828 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003829 }
3830
Anders Carlsson43c64af2010-04-21 19:52:01 +00003831 // Keep track of the direct virtual bases.
3832 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003833 for (auto &I : ClassDecl->bases()) {
3834 if (I.isVirtual())
3835 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003836 }
3837
Anders Carlssondb0a9652010-04-02 06:26:44 +00003838 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003839 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003840 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003841 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003842 // [class.base.init]p7, per DR257:
3843 // A mem-initializer where the mem-initializer-id names a virtual base
3844 // class is ignored during execution of a constructor of any class that
3845 // is not the most derived class.
3846 if (ClassDecl->isAbstract()) {
3847 // FIXME: Provide a fixit to remove the base specifier. This requires
3848 // tracking the location of the associated comma for a base specifier.
3849 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003850 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003851 DiagnoseAbstractType(ClassDecl);
3852 }
3853
John McCallbc83b3f2010-05-20 23:23:51 +00003854 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003855 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3856 // [class.base.init]p8, per DR257:
3857 // If a given [...] base class is not named by a mem-initializer-id
3858 // [...] and the entity is not a virtual base class of an abstract
3859 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003860 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003861 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003862 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003863 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003864 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003865 HadError = true;
3866 continue;
3867 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003868
John McCallbc83b3f2010-05-20 23:23:51 +00003869 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003870 }
3871 }
Mike Stump11289f42009-09-09 15:08:12 +00003872
John McCallbc83b3f2010-05-20 23:23:51 +00003873 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003874 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003875 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003876 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003877 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003878
Alexis Hunt1d792652011-01-08 20:30:50 +00003879 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003880 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003881 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003882 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003883 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003884 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003885 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003886 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003887 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003888 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003889 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003890
John McCallbc83b3f2010-05-20 23:23:51 +00003891 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003892 }
3893 }
Mike Stump11289f42009-09-09 15:08:12 +00003894
John McCallbc83b3f2010-05-20 23:23:51 +00003895 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003896 for (auto *Mem : ClassDecl->decls()) {
3897 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003898 // C++ [class.bit]p2:
3899 // A declaration for a bit-field that omits the identifier declares an
3900 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3901 // initialized.
3902 if (F->isUnnamedBitfield())
3903 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003904
Sebastian Redl22653ba2011-08-30 19:58:05 +00003905 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003906 // handle anonymous struct/union fields based on their individual
3907 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003908 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003909 continue;
3910
3911 if (CollectFieldInitializer(*this, Info, F))
3912 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003913 continue;
3914 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003915
3916 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003917 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003918 continue;
3919
Aaron Ballman629afae2014-03-07 19:56:05 +00003920 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003921 if (F->getType()->isIncompleteArrayType()) {
3922 assert(ClassDecl->hasFlexibleArrayMember() &&
3923 "Incomplete array type is not valid");
3924 continue;
3925 }
3926
Douglas Gregor493627b2011-08-10 15:22:55 +00003927 // Initialize each field of an anonymous struct individually.
3928 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3929 HadError = true;
3930
3931 continue;
3932 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003933 }
Mike Stump11289f42009-09-09 15:08:12 +00003934
David Blaikie3fc2f912013-01-17 05:26:25 +00003935 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003936 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003937 Constructor->setNumCtorInitializers(NumInitializers);
3938 CXXCtorInitializer **baseOrMemberInitializers =
3939 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003940 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003941 NumInitializers * sizeof(CXXCtorInitializer*));
3942 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003943
John McCalla6309952010-03-16 21:39:52 +00003944 // Constructors implicitly reference the base and member
3945 // destructors.
3946 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3947 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003948 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003949
3950 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003951}
3952
David Blaikieb61b8152013-01-17 08:49:22 +00003953static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003954 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003955 const RecordDecl *RD = RT->getDecl();
3956 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003957 for (auto *Field : RD->fields())
3958 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003959 return;
3960 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003961 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003962 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003963}
3964
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003965static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3966 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003967}
3968
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003969static const void *GetKeyForMember(ASTContext &Context,
3970 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003971 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003972 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003973
Richard Smithcd45dbc2014-04-19 03:48:30 +00003974 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003975}
3976
David Blaikie3fc2f912013-01-17 05:26:25 +00003977static void DiagnoseBaseOrMemInitializerOrder(
3978 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3979 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003980 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003981 return;
Mike Stump11289f42009-09-09 15:08:12 +00003982
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003983 // Don't check initializers order unless the warning is enabled at the
3984 // location of at least one initializer.
3985 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003986 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003987 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003988 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3989 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003990 ShouldCheckOrder = true;
3991 break;
3992 }
3993 }
3994 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003995 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003996
John McCallbb7b6582010-04-10 07:37:23 +00003997 // Build the list of bases and members in the order that they'll
3998 // actually be initialized. The explicit initializers should be in
3999 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004000 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004001
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004002 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4003
John McCallbb7b6582010-04-10 07:37:23 +00004004 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004005 for (const auto &VBase : ClassDecl->vbases())
4006 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004007
John McCallbb7b6582010-04-10 07:37:23 +00004008 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004009 for (const auto &Base : ClassDecl->bases()) {
4010 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004011 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004012 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004013 }
Mike Stump11289f42009-09-09 15:08:12 +00004014
John McCallbb7b6582010-04-10 07:37:23 +00004015 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004016 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004017 if (Field->isUnnamedBitfield())
4018 continue;
4019
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004020 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004021 }
4022
John McCallbb7b6582010-04-10 07:37:23 +00004023 unsigned NumIdealInits = IdealInitKeys.size();
4024 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004025
Craig Topperc3ec1492014-05-26 06:22:03 +00004026 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004027 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004028 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004029 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004030
4031 // Scan forward to try to find this initializer in the idealized
4032 // initializers list.
4033 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4034 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004035 break;
John McCallbb7b6582010-04-10 07:37:23 +00004036
4037 // If we didn't find this initializer, it must be because we
4038 // scanned past it on a previous iteration. That can only
4039 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004040 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004041 Sema::SemaDiagnosticBuilder D =
4042 SemaRef.Diag(PrevInit->getSourceLocation(),
4043 diag::warn_initializer_out_of_order);
4044
Francois Pichetd583da02010-12-04 09:14:42 +00004045 if (PrevInit->isAnyMemberInitializer())
4046 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004047 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004048 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004049
Francois Pichetd583da02010-12-04 09:14:42 +00004050 if (Init->isAnyMemberInitializer())
4051 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004052 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004053 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004054
4055 // Move back to the initializer's location in the ideal list.
4056 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4057 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004058 break;
John McCallbb7b6582010-04-10 07:37:23 +00004059
4060 assert(IdealIndex != NumIdealInits &&
4061 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004062 }
John McCallbb7b6582010-04-10 07:37:23 +00004063
4064 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004065 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004066}
4067
John McCall23eebd92010-04-10 09:28:51 +00004068namespace {
4069bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004070 CXXCtorInitializer *Init,
4071 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004072 if (!PrevInit) {
4073 PrevInit = Init;
4074 return false;
4075 }
4076
Douglas Gregorea306a12013-03-25 23:28:23 +00004077 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004078 S.Diag(Init->getSourceLocation(),
4079 diag::err_multiple_mem_initialization)
4080 << Field->getDeclName()
4081 << Init->getSourceRange();
4082 else {
John McCall424cec92011-01-19 06:33:43 +00004083 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004084 assert(BaseClass && "neither field nor base");
4085 S.Diag(Init->getSourceLocation(),
4086 diag::err_multiple_base_initialization)
4087 << QualType(BaseClass, 0)
4088 << Init->getSourceRange();
4089 }
4090 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4091 << 0 << PrevInit->getSourceRange();
4092
4093 return true;
4094}
4095
Alexis Hunt1d792652011-01-08 20:30:50 +00004096typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004097typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4098
4099bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004100 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004101 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004102 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004103 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004104 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004105
4106 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004107 if (Parent->isUnion()) {
4108 UnionEntry &En = Unions[Parent];
4109 if (En.first && En.first != Child) {
4110 S.Diag(Init->getSourceLocation(),
4111 diag::err_multiple_mem_union_initialization)
4112 << Field->getDeclName()
4113 << Init->getSourceRange();
4114 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4115 << 0 << En.second->getSourceRange();
4116 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004117 }
4118 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004119 En.first = Child;
4120 En.second = Init;
4121 }
David Blaikie0f65d592011-11-17 06:01:57 +00004122 if (!Parent->isAnonymousStructOrUnion())
4123 return false;
John McCall23eebd92010-04-10 09:28:51 +00004124 }
4125
4126 Child = Parent;
4127 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004128 }
John McCall23eebd92010-04-10 09:28:51 +00004129
4130 return false;
4131}
4132}
4133
Anders Carlssone857b292010-04-02 03:37:03 +00004134/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004135void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004136 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004137 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004138 bool AnyErrors) {
4139 if (!ConstructorDecl)
4140 return;
4141
4142 AdjustDeclIfTemplate(ConstructorDecl);
4143
4144 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004145 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004146
4147 if (!Constructor) {
4148 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4149 return;
4150 }
4151
John McCall23eebd92010-04-10 09:28:51 +00004152 // Mapping for the duplicate initializers check.
4153 // For member initializers, this is keyed with a FieldDecl*.
4154 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004155 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004156
4157 // Mapping for the inconsistent anonymous-union initializers check.
4158 RedundantUnionMap MemberUnions;
4159
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004160 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004161 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004162 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004163
Abramo Bagnara341d7832010-05-26 18:09:23 +00004164 // Set the source order index.
4165 Init->setSourceOrder(i);
4166
Francois Pichetd583da02010-12-04 09:14:42 +00004167 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004168 const void *Key = GetKeyForMember(Context, Init);
4169 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004170 CheckRedundantUnionInit(*this, Init, MemberUnions))
4171 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004172 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004173 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004174 if (CheckRedundantInit(*this, Init, Members[Key]))
4175 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004176 } else {
4177 assert(Init->isDelegatingInitializer());
4178 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004179 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004180 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004181 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004182 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004183 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004184 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004185 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004186 // Return immediately as the initializer is set.
4187 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004188 }
Anders Carlssone857b292010-04-02 03:37:03 +00004189 }
4190
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004191 if (HadError)
4192 return;
4193
David Blaikie3fc2f912013-01-17 05:26:25 +00004194 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004195
David Blaikie3fc2f912013-01-17 05:26:25 +00004196 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004197
Richard Trieuef64e942013-10-25 00:56:00 +00004198 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004199}
4200
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004201void
John McCalla6309952010-03-16 21:39:52 +00004202Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4203 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004204 // Ignore dependent contexts. Also ignore unions, since their members never
4205 // have destructors implicitly called.
4206 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004207 return;
John McCall1064d7e2010-03-16 05:22:47 +00004208
4209 // FIXME: all the access-control diagnostics are positioned on the
4210 // field/base declaration. That's probably good; that said, the
4211 // user might reasonably want to know why the destructor is being
4212 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004213
Anders Carlssondee9a302009-11-17 04:44:12 +00004214 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004215 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004216 if (Field->isInvalidDecl())
4217 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004218
4219 // Don't destroy incomplete or zero-length arrays.
4220 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4221 continue;
4222
Anders Carlssondee9a302009-11-17 04:44:12 +00004223 QualType FieldType = Context.getBaseElementType(Field->getType());
4224
4225 const RecordType* RT = FieldType->getAs<RecordType>();
4226 if (!RT)
4227 continue;
4228
4229 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004230 if (FieldClassDecl->isInvalidDecl())
4231 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004232 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004233 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004234 // The destructor for an implicit anonymous union member is never invoked.
4235 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4236 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004237
Douglas Gregore71edda2010-07-01 22:47:18 +00004238 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004239 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004240 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004241 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004242 << Field->getDeclName()
4243 << FieldType);
4244
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004245 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004246 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004247 }
4248
John McCall1064d7e2010-03-16 05:22:47 +00004249 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4250
Anders Carlssondee9a302009-11-17 04:44:12 +00004251 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004252 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004253 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004254 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004255
4256 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004257 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004258 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004259
John McCall1064d7e2010-03-16 05:22:47 +00004260 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004261 // If our base class is invalid, we probably can't get its dtor anyway.
4262 if (BaseClassDecl->isInvalidDecl())
4263 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004264 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004265 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004266
Douglas Gregore71edda2010-07-01 22:47:18 +00004267 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004268 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004269
4270 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004271 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004272 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004273 << Base.getType()
4274 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004275 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004276
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004277 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004278 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004279 }
4280
4281 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004282 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004283 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004284 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004285
4286 // Ignore direct virtual bases.
4287 if (DirectVirtualBases.count(RT))
4288 continue;
4289
John McCall1064d7e2010-03-16 05:22:47 +00004290 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004291 // If our base class is invalid, we probably can't get its dtor anyway.
4292 if (BaseClassDecl->isInvalidDecl())
4293 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004294 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004295 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004296
Douglas Gregore71edda2010-07-01 22:47:18 +00004297 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004298 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004299 if (CheckDestructorAccess(
4300 ClassDecl->getLocation(), Dtor,
4301 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004302 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004303 Context.getTypeDeclType(ClassDecl)) ==
4304 AR_accessible) {
4305 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004306 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004307 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004308 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004309 }
John McCall1064d7e2010-03-16 05:22:47 +00004310
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004311 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004312 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004313 }
4314}
4315
John McCall48871652010-08-21 09:40:31 +00004316void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004317 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004318 return;
Mike Stump11289f42009-09-09 15:08:12 +00004319
Mike Stump11289f42009-09-09 15:08:12 +00004320 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004321 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004322 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004323 DiagnoseUninitializedFields(*this, Constructor);
4324 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004325}
4326
Mike Stump11289f42009-09-09 15:08:12 +00004327bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004328 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004329 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4330 unsigned DiagID;
4331 AbstractDiagSelID SelID;
4332
4333 public:
4334 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4335 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004336
Craig Toppera798a9d2014-03-02 09:32:10 +00004337 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004338 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004339 if (SelID == -1)
4340 S.Diag(Loc, DiagID) << T;
4341 else
4342 S.Diag(Loc, DiagID) << SelID << T;
4343 }
4344 } Diagnoser(DiagID, SelID);
4345
4346 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004347}
4348
Anders Carlssoneabf7702009-08-27 00:13:57 +00004349bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004350 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004351 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004352 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004353
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004354 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004355 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004356
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004357 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004358 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004359 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004360 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004361
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004362 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004363 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004364 }
Mike Stump11289f42009-09-09 15:08:12 +00004365
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004366 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004367 if (!RT)
4368 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004369
John McCall67da35c2010-02-04 22:26:26 +00004370 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004371
John McCall02db245d2010-08-18 09:41:07 +00004372 // We can't answer whether something is abstract until it has a
4373 // definition. If it's currently being defined, we'll walk back
4374 // over all the declarations when we have a full definition.
4375 const CXXRecordDecl *Def = RD->getDefinition();
4376 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004377 return false;
4378
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004379 if (!RD->isAbstract())
4380 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004381
Douglas Gregorae298422012-05-04 17:09:59 +00004382 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004383 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004384
John McCall02db245d2010-08-18 09:41:07 +00004385 return true;
4386}
4387
4388void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4389 // Check if we've already emitted the list of pure virtual functions
4390 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004391 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004392 return;
Mike Stump11289f42009-09-09 15:08:12 +00004393
Richard Smithbc46e432013-07-22 02:56:56 +00004394 // If the diagnostic is suppressed, don't emit the notes. We're only
4395 // going to emit them once, so try to attach them to a diagnostic we're
4396 // actually going to show.
4397 if (Diags.isLastDiagnosticIgnored())
4398 return;
4399
Douglas Gregor4165bd62010-03-23 23:47:56 +00004400 CXXFinalOverriderMap FinalOverriders;
4401 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004402
Anders Carlssona2f74f32010-06-03 01:00:02 +00004403 // Keep a set of seen pure methods so we won't diagnose the same method
4404 // more than once.
4405 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4406
Douglas Gregor4165bd62010-03-23 23:47:56 +00004407 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4408 MEnd = FinalOverriders.end();
4409 M != MEnd;
4410 ++M) {
4411 for (OverridingMethods::iterator SO = M->second.begin(),
4412 SOEnd = M->second.end();
4413 SO != SOEnd; ++SO) {
4414 // C++ [class.abstract]p4:
4415 // A class is abstract if it contains or inherits at least one
4416 // pure virtual function for which the final overrider is pure
4417 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004418
Douglas Gregor4165bd62010-03-23 23:47:56 +00004419 //
4420 if (SO->second.size() != 1)
4421 continue;
4422
4423 if (!SO->second.front().Method->isPure())
4424 continue;
4425
Anders Carlssona2f74f32010-06-03 01:00:02 +00004426 if (!SeenPureMethods.insert(SO->second.front().Method))
4427 continue;
4428
Douglas Gregor4165bd62010-03-23 23:47:56 +00004429 Diag(SO->second.front().Method->getLocation(),
4430 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004431 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004432 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004433 }
4434
4435 if (!PureVirtualClassDiagSet)
4436 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4437 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004438}
4439
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004440namespace {
John McCall02db245d2010-08-18 09:41:07 +00004441struct AbstractUsageInfo {
4442 Sema &S;
4443 CXXRecordDecl *Record;
4444 CanQualType AbstractType;
4445 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004446
John McCall02db245d2010-08-18 09:41:07 +00004447 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4448 : S(S), Record(Record),
4449 AbstractType(S.Context.getCanonicalType(
4450 S.Context.getTypeDeclType(Record))),
4451 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004452
John McCall02db245d2010-08-18 09:41:07 +00004453 void DiagnoseAbstractType() {
4454 if (Invalid) return;
4455 S.DiagnoseAbstractType(Record);
4456 Invalid = true;
4457 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004458
John McCall02db245d2010-08-18 09:41:07 +00004459 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4460};
4461
4462struct CheckAbstractUsage {
4463 AbstractUsageInfo &Info;
4464 const NamedDecl *Ctx;
4465
4466 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4467 : Info(Info), Ctx(Ctx) {}
4468
4469 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4470 switch (TL.getTypeLocClass()) {
4471#define ABSTRACT_TYPELOC(CLASS, PARENT)
4472#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004473 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004474#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004475 }
John McCall02db245d2010-08-18 09:41:07 +00004476 }
Mike Stump11289f42009-09-09 15:08:12 +00004477
John McCall02db245d2010-08-18 09:41:07 +00004478 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004479 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004480 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4481 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004482 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004483
4484 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004485 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004486 }
John McCall02db245d2010-08-18 09:41:07 +00004487 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004488
John McCall02db245d2010-08-18 09:41:07 +00004489 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4490 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4491 }
Mike Stump11289f42009-09-09 15:08:12 +00004492
John McCall02db245d2010-08-18 09:41:07 +00004493 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4494 // Visit the type parameters from a permissive context.
4495 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4496 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4497 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4498 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4499 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4500 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004501 }
John McCall02db245d2010-08-18 09:41:07 +00004502 }
Mike Stump11289f42009-09-09 15:08:12 +00004503
John McCall02db245d2010-08-18 09:41:07 +00004504 // Visit pointee types from a permissive context.
4505#define CheckPolymorphic(Type) \
4506 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4507 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4508 }
4509 CheckPolymorphic(PointerTypeLoc)
4510 CheckPolymorphic(ReferenceTypeLoc)
4511 CheckPolymorphic(MemberPointerTypeLoc)
4512 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004513 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004514
John McCall02db245d2010-08-18 09:41:07 +00004515 /// Handle all the types we haven't given a more specific
4516 /// implementation for above.
4517 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4518 // Every other kind of type that we haven't called out already
4519 // that has an inner type is either (1) sugar or (2) contains that
4520 // inner type in some way as a subobject.
4521 if (TypeLoc Next = TL.getNextTypeLoc())
4522 return Visit(Next, Sel);
4523
4524 // If there's no inner type and we're in a permissive context,
4525 // don't diagnose.
4526 if (Sel == Sema::AbstractNone) return;
4527
4528 // Check whether the type matches the abstract type.
4529 QualType T = TL.getType();
4530 if (T->isArrayType()) {
4531 Sel = Sema::AbstractArrayType;
4532 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004533 }
John McCall02db245d2010-08-18 09:41:07 +00004534 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4535 if (CT != Info.AbstractType) return;
4536
4537 // It matched; do some magic.
4538 if (Sel == Sema::AbstractArrayType) {
4539 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4540 << T << TL.getSourceRange();
4541 } else {
4542 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4543 << Sel << T << TL.getSourceRange();
4544 }
4545 Info.DiagnoseAbstractType();
4546 }
4547};
4548
4549void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4550 Sema::AbstractDiagSelID Sel) {
4551 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4552}
4553
4554}
4555
4556/// Check for invalid uses of an abstract type in a method declaration.
4557static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4558 CXXMethodDecl *MD) {
4559 // No need to do the check on definitions, which require that
4560 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004561 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004562 return;
4563
4564 // For safety's sake, just ignore it if we don't have type source
4565 // information. This should never happen for non-implicit methods,
4566 // but...
4567 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4568 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4569}
4570
4571/// Check for invalid uses of an abstract type within a class definition.
4572static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4573 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004574 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004575 if (D->isImplicit()) continue;
4576
4577 // Methods and method templates.
4578 if (isa<CXXMethodDecl>(D)) {
4579 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4580 } else if (isa<FunctionTemplateDecl>(D)) {
4581 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4582 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4583
4584 // Fields and static variables.
4585 } else if (isa<FieldDecl>(D)) {
4586 FieldDecl *FD = cast<FieldDecl>(D);
4587 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4588 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4589 } else if (isa<VarDecl>(D)) {
4590 VarDecl *VD = cast<VarDecl>(D);
4591 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4592 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4593
4594 // Nested classes and class templates.
4595 } else if (isa<CXXRecordDecl>(D)) {
4596 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4597 } else if (isa<ClassTemplateDecl>(D)) {
4598 CheckAbstractClassUsage(Info,
4599 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4600 }
4601 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004602}
4603
Hans Wennborg853ae942014-05-30 16:59:42 +00004604/// \brief Check class-level dllimport/dllexport attribute.
4605static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4606 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004607
4608 // MSVC inherits DLL attributes to partial class template specializations.
4609 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4610 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4611 if (Attr *TemplateAttr =
4612 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4613 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4614 A->setInherited(true);
4615 ClassAttr = A;
4616 }
4617 }
4618 }
4619
Hans Wennborg853ae942014-05-30 16:59:42 +00004620 if (!ClassAttr)
4621 return;
4622
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004623 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4624 !ClassAttr->isInherited()) {
4625 // Diagnose dll attributes on members of class with dll attribute.
4626 for (Decl *Member : Class->decls()) {
4627 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4628 continue;
4629 InheritableAttr *MemberAttr = getDLLAttr(Member);
4630 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4631 continue;
4632
4633 S.Diag(MemberAttr->getLocation(),
4634 diag::err_attribute_dll_member_of_dll_class)
4635 << MemberAttr << ClassAttr;
4636 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4637 Member->setInvalidDecl();
4638 }
4639 }
4640
4641 if (Class->getDescribedClassTemplate())
4642 // Don't inherit dll attribute until the template is instantiated.
4643 return;
4644
Hans Wennborg853ae942014-05-30 16:59:42 +00004645 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4646
4647 // Force declaration of implicit members so they can inherit the attribute.
4648 S.ForceDeclarationOfImplicitMembers(Class);
4649
4650 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4651 // seem to be true in practice?
4652
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004653 TemplateSpecializationKind TSK =
4654 Class->getTemplateSpecializationKind();
4655
Hans Wennborg853ae942014-05-30 16:59:42 +00004656 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004657 VarDecl *VD = dyn_cast<VarDecl>(Member);
4658 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4659
4660 // Only methods and static fields inherit the attributes.
4661 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004662 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004663
4664 // Don't process deleted methods.
4665 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004666 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004667
Hans Wennborge8ad3832014-06-11 22:44:39 +00004668 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4669 MD->isInlined()) {
4670 // Current MSVC versions don't export the move assignment operators, so
4671 // don't attempt to import them if we have a definition.
4672 continue;
4673 }
4674
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004675 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004676 auto *NewAttr =
4677 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4678 NewAttr->setInherited(true);
4679 Member->addAttr(NewAttr);
4680 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004681
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004682 if (MD && ClassExported) {
4683 if (MD->isUserProvided()) {
4684 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004685
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004686 // .. except for certain kinds of template specializations.
4687 if (TSK == TSK_ExplicitInstantiationDeclaration)
4688 continue;
4689 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4690 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004691
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004692 S.MarkFunctionReferenced(Class->getLocation(), MD);
4693 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4694 MD->isCopyAssignmentOperator() ||
4695 MD->isMoveAssignmentOperator()) {
4696 // Instantiate non-trivial or explicitly defaulted methods, and the
4697 // copy assignment / move assignment operators.
4698 S.MarkFunctionReferenced(Class->getLocation(), MD);
4699 // Resolve its exception specification; CodeGen needs it.
4700 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4701 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4702 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004703 }
4704 }
4705 }
4706}
4707
Douglas Gregorc99f1552009-12-03 18:33:45 +00004708/// \brief Perform semantic checks on a class definition that has been
4709/// completing, introducing implicitly-declared members, checking for
4710/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004711void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004712 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004713 return;
4714
John McCall02db245d2010-08-18 09:41:07 +00004715 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4716 AbstractUsageInfo Info(*this, Record);
4717 CheckAbstractClassUsage(Info, Record);
4718 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004719
4720 // If this is not an aggregate type and has no user-declared constructor,
4721 // complain about any non-static data members of reference or const scalar
4722 // type, since they will never get initializers.
4723 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004724 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4725 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004726 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004727 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004728 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004729 continue;
4730
Douglas Gregor454a5b62010-04-15 00:00:53 +00004731 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004732 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004733 if (!Complained) {
4734 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4735 << Record->getTagKind() << Record;
4736 Complained = true;
4737 }
4738
4739 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4740 << F->getType()->isReferenceType()
4741 << F->getDeclName();
4742 }
4743 }
4744 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004745
Anders Carlssone771e762011-01-25 18:08:22 +00004746 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004747 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004748
4749 if (Record->getIdentifier()) {
4750 // C++ [class.mem]p13:
4751 // If T is the name of a class, then each of the following shall have a
4752 // name different from T:
4753 // - every member of every anonymous union that is a member of class T.
4754 //
4755 // C++ [class.mem]p14:
4756 // In addition, if class T has a user-declared constructor (12.1), every
4757 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004758 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4759 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4760 ++I) {
4761 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004762 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4763 isa<IndirectFieldDecl>(D)) {
4764 Diag(D->getLocation(), diag::err_member_name_of_class)
4765 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004766 break;
4767 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004768 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004769 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004770
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004771 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004772 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004773 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004774 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4775 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004776 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4777 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4778 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004779
David Majnemera5433082013-10-18 00:33:31 +00004780 if (Record->isAbstract()) {
4781 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4782 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4783 << FA->isSpelledAsSealed();
4784 DiagnoseAbstractType(Record);
4785 }
David Blaikie348df502012-09-21 03:21:07 +00004786 }
4787
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004788 bool HasMethodWithOverrideControl = false,
4789 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004790 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004791 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004792 // See if a method overloads virtual methods in a base
4793 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004794 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004795 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004796 if (M->hasAttr<OverrideAttr>())
4797 HasMethodWithOverrideControl = true;
4798 else if (M->size_overridden_methods() > 0)
4799 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004800 // Check whether the explicitly-defaulted special members are valid.
4801 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004802 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004803
4804 // For an explicitly defaulted or deleted special member, we defer
4805 // determining triviality until the class is complete. That time is now!
4806 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004807 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004808 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004809 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004810
4811 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004812 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004813 }
4814 }
4815 }
4816 }
4817
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004818 if (HasMethodWithOverrideControl &&
4819 HasOverridingMethodWithoutOverrideControl) {
4820 // At least one method has the 'override' control declared.
4821 // Diagnose all other overridden methods which do not have 'override' specified on them.
4822 for (auto *M : Record->methods())
4823 DiagnoseAbsenceOfOverrideControl(M);
4824 }
Richard Smithbd305122012-12-11 01:14:52 +00004825 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4826 // function that is not a constructor declares that member function to be
4827 // const. [...] The class of which that function is a member shall be
4828 // a literal type.
4829 //
4830 // If the class has virtual bases, any constexpr members will already have
4831 // been diagnosed by the checks performed on the member declaration, so
4832 // suppress this (less useful) diagnostic.
4833 //
4834 // We delay this until we know whether an explicitly-defaulted (or deleted)
4835 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004836 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004837 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004838 for (const auto *M : Record->methods()) {
4839 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004840 switch (Record->getTemplateSpecializationKind()) {
4841 case TSK_ImplicitInstantiation:
4842 case TSK_ExplicitInstantiationDeclaration:
4843 case TSK_ExplicitInstantiationDefinition:
4844 // If a template instantiates to a non-literal type, but its members
4845 // instantiate to constexpr functions, the template is technically
4846 // ill-formed, but we allow it for sanity.
4847 continue;
4848
4849 case TSK_Undeclared:
4850 case TSK_ExplicitSpecialization:
4851 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4852 diag::err_constexpr_method_non_literal);
4853 break;
4854 }
4855
4856 // Only produce one error per class.
4857 break;
4858 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004859 }
4860 }
Sebastian Redl08905022011-02-05 19:23:19 +00004861
John McCall95833f32014-02-27 20:30:49 +00004862 // ms_struct is a request to use the same ABI rules as MSVC. Check
4863 // whether this class uses any C++ features that are implemented
4864 // completely differently in MSVC, and if so, emit a diagnostic.
4865 // That diagnostic defaults to an error, but we allow projects to
4866 // map it down to a warning (or ignore it). It's a fairly common
4867 // practice among users of the ms_struct pragma to mass-annotate
4868 // headers, sweeping up a bunch of types that the project doesn't
4869 // really rely on MSVC-compatible layout for. We must therefore
4870 // support "ms_struct except for C++ stuff" as a secondary ABI.
4871 if (Record->isMsStruct(Context) &&
4872 (Record->isPolymorphic() || Record->getNumBases())) {
4873 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004874 }
4875
Richard Smithc2bc61b2013-03-18 21:12:30 +00004876 // Declare inheriting constructors. We do this eagerly here because:
4877 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004878 // constructors from different classes.
4879 // - The lazy declaration of the other implicit constructors is so as to not
4880 // waste space and performance on classes that are not meant to be
4881 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004882 // have inheriting constructors.
4883 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004884
4885 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004886}
4887
Richard Smith41c35d62013-11-27 03:39:20 +00004888/// Look up the special member function that would be called by a special
4889/// member function for a subobject of class type.
4890///
4891/// \param Class The class type of the subobject.
4892/// \param CSM The kind of special member function.
4893/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4894/// \param ConstRHS True if this is a copy operation with a const object
4895/// on its RHS, that is, if the argument to the outer special member
4896/// function is 'const' and this is not a field marked 'mutable'.
4897static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4898 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4899 unsigned FieldQuals, bool ConstRHS) {
4900 unsigned LHSQuals = 0;
4901 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4902 LHSQuals = FieldQuals;
4903
4904 unsigned RHSQuals = FieldQuals;
4905 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4906 RHSQuals = 0;
4907 else if (ConstRHS)
4908 RHSQuals |= Qualifiers::Const;
4909
4910 return S.LookupSpecialMember(Class, CSM,
4911 RHSQuals & Qualifiers::Const,
4912 RHSQuals & Qualifiers::Volatile,
4913 false,
4914 LHSQuals & Qualifiers::Const,
4915 LHSQuals & Qualifiers::Volatile);
4916}
4917
Richard Smithb5800092012-06-10 05:43:50 +00004918/// Is the special member function which would be selected to perform the
4919/// specified operation on the specified class type a constexpr constructor?
4920static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4921 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004922 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004923 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004924 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004925 if (!SMOR || !SMOR->getMethod())
4926 // A constructor we wouldn't select can't be "involved in initializing"
4927 // anything.
4928 return true;
4929 return SMOR->getMethod()->isConstexpr();
4930}
4931
4932/// Determine whether the specified special member function would be constexpr
4933/// if it were implicitly defined.
4934static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4935 Sema::CXXSpecialMember CSM,
4936 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004937 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004938 return false;
4939
4940 // C++11 [dcl.constexpr]p4:
4941 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004942 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004943 switch (CSM) {
4944 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004945 // Since default constructor lookup is essentially trivial (and cannot
4946 // involve, for instance, template instantiation), we compute whether a
4947 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4948 //
4949 // This is important for performance; we need to know whether the default
4950 // constructor is constexpr to determine whether the type is a literal type.
4951 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4952
Richard Smithb5800092012-06-10 05:43:50 +00004953 case Sema::CXXCopyConstructor:
4954 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004955 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004956 break;
4957
4958 case Sema::CXXCopyAssignment:
4959 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004960 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00004961 return false;
4962 // In C++1y, we need to perform overload resolution.
4963 Ctor = false;
4964 break;
4965
Richard Smithb5800092012-06-10 05:43:50 +00004966 case Sema::CXXDestructor:
4967 case Sema::CXXInvalid:
4968 return false;
4969 }
4970
4971 // -- if the class is a non-empty union, or for each non-empty anonymous
4972 // union member of a non-union class, exactly one non-static data member
4973 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004974 //
4975 // If we squint, this is guaranteed, since exactly one non-static data member
4976 // will be initialized (if the constructor isn't deleted), we just don't know
4977 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004978 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004979 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004980
4981 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004982 if (Ctor && ClassDecl->getNumVBases())
4983 return false;
4984
4985 // C++1y [class.copy]p26:
4986 // -- [the class] is a literal type, and
4987 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004988 return false;
4989
4990 // -- every constructor involved in initializing [...] base class
4991 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004992 // -- the assignment operator selected to copy/move each direct base
4993 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004994 for (const auto &B : ClassDecl->bases()) {
4995 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004996 if (!BaseType) continue;
4997
4998 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004999 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005000 return false;
5001 }
5002
5003 // -- every constructor involved in initializing non-static data members
5004 // [...] shall be a constexpr constructor;
5005 // -- every non-static data member and base class sub-object shall be
5006 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005007 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005008 // thereof), the assignment operator selected to copy/move that member is
5009 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005010 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005011 if (F->isInvalidDecl())
5012 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005013 QualType BaseType = S.Context.getBaseElementType(F->getType());
5014 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005015 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005016 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5017 BaseType.getCVRQualifiers(),
5018 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005019 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005020 }
5021 }
5022
5023 // All OK, it's constexpr!
5024 return true;
5025}
5026
Richard Smithd3b5c9082012-07-27 04:22:15 +00005027static Sema::ImplicitExceptionSpecification
5028computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5029 switch (S.getSpecialMember(MD)) {
5030 case Sema::CXXDefaultConstructor:
5031 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5032 case Sema::CXXCopyConstructor:
5033 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5034 case Sema::CXXCopyAssignment:
5035 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5036 case Sema::CXXMoveConstructor:
5037 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5038 case Sema::CXXMoveAssignment:
5039 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5040 case Sema::CXXDestructor:
5041 return S.ComputeDefaultedDtorExceptionSpec(MD);
5042 case Sema::CXXInvalid:
5043 break;
5044 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005045 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5046 "only special members have implicit exception specs");
5047 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005048}
5049
Reid Kleckner78af0702013-08-27 23:08:25 +00005050static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5051 CXXMethodDecl *MD) {
5052 FunctionProtoType::ExtProtoInfo EPI;
5053
5054 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005055 EPI.ExceptionSpec.Type = EST_Unevaluated;
5056 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005057
5058 // Set the calling convention to the default for C++ instance methods.
5059 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5060 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5061 /*IsCXXMethod=*/true));
5062 return EPI;
5063}
5064
Richard Smithd3b5c9082012-07-27 04:22:15 +00005065void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5066 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5067 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5068 return;
5069
Richard Smith7f782272012-07-30 23:48:14 +00005070 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005071 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005072
Richard Smith7f782272012-07-30 23:48:14 +00005073 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005074 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005075
5076 // A user-provided destructor can be defined outside the class. When that
5077 // happens, be sure to update the exception specification on both
5078 // declarations.
5079 const FunctionProtoType *CanonicalFPT =
5080 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5081 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005082 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005083}
5084
Richard Smithb9e90b12012-05-15 04:39:51 +00005085void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5086 CXXRecordDecl *RD = MD->getParent();
5087 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005088
Richard Smithb9e90b12012-05-15 04:39:51 +00005089 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5090 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005091
5092 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005093 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005094 bool First = MD == MD->getCanonicalDecl();
5095
5096 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005097
5098 // C++11 [dcl.fct.def.default]p1:
5099 // A function that is explicitly defaulted shall
5100 // -- be a special member function (checked elsewhere),
5101 // -- have the same type (except for ref-qualifiers, and except that a
5102 // copy operation can take a non-const reference) as an implicit
5103 // declaration, and
5104 // -- not have default arguments.
5105 unsigned ExpectedParams = 1;
5106 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5107 ExpectedParams = 0;
5108 if (MD->getNumParams() != ExpectedParams) {
5109 // This also checks for default arguments: a copy or move constructor with a
5110 // default argument is classified as a default constructor, and assignment
5111 // operations and destructors can't have default arguments.
5112 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5113 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005114 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005115 } else if (MD->isVariadic()) {
5116 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5117 << CSM << MD->getSourceRange();
5118 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005119 }
5120
Richard Smithb9e90b12012-05-15 04:39:51 +00005121 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005122
Richard Smithb5800092012-06-10 05:43:50 +00005123 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005124 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005125 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005126 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005127 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005128
Richard Smithb9e90b12012-05-15 04:39:51 +00005129 QualType ReturnType = Context.VoidTy;
5130 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5131 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005132 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005133 QualType ExpectedReturnType =
5134 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5135 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5136 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5137 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5138 HadError = true;
5139 }
5140
5141 // A defaulted special member cannot have cv-qualifiers.
5142 if (Type->getTypeQuals()) {
5143 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005144 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005145 HadError = true;
5146 }
5147 }
5148
5149 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005150 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005151 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005152 if (ExpectedParams && ArgType->isReferenceType()) {
5153 // Argument must be reference to possibly-const T.
5154 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005155 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005156
5157 if (ReferentType.isVolatileQualified()) {
5158 Diag(MD->getLocation(),
5159 diag::err_defaulted_special_member_volatile_param) << CSM;
5160 HadError = true;
5161 }
5162
Richard Smithb5800092012-06-10 05:43:50 +00005163 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005164 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5165 Diag(MD->getLocation(),
5166 diag::err_defaulted_special_member_copy_const_param)
5167 << (CSM == CXXCopyAssignment);
5168 // FIXME: Explain why this special member can't be const.
5169 } else {
5170 Diag(MD->getLocation(),
5171 diag::err_defaulted_special_member_move_const_param)
5172 << (CSM == CXXMoveAssignment);
5173 }
5174 HadError = true;
5175 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005176 } else if (ExpectedParams) {
5177 // A copy assignment operator can take its argument by value, but a
5178 // defaulted one cannot.
5179 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005180 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005181 HadError = true;
5182 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005183
Richard Smithcc36f692011-12-22 02:22:31 +00005184 // C++11 [dcl.fct.def.default]p2:
5185 // An explicitly-defaulted function may be declared constexpr only if it
5186 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005187 // Do not apply this rule to members of class templates, since core issue 1358
5188 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005189 // functions which cannot be constexpr (for non-constructors in C++11 and for
5190 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005191 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5192 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005193 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005194 : isa<CXXConstructorDecl>(MD)) &&
5195 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005196 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5197 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005198 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005199 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005200 }
Richard Smithbd305122012-12-11 01:14:52 +00005201
Richard Smithcc36f692011-12-22 02:22:31 +00005202 // and may have an explicit exception-specification only if it is compatible
5203 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005204 if (Type->hasExceptionSpec()) {
5205 // Delay the check if this is the first declaration of the special member,
5206 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005207 if (First) {
5208 // If the exception specification needs to be instantiated, do so now,
5209 // before we clobber it with an EST_Unevaluated specification below.
5210 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5211 InstantiateExceptionSpec(MD->getLocStart(), MD);
5212 Type = MD->getType()->getAs<FunctionProtoType>();
5213 }
Richard Smithbd305122012-12-11 01:14:52 +00005214 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005215 } else
Richard Smithbd305122012-12-11 01:14:52 +00005216 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5217 }
Richard Smithcc36f692011-12-22 02:22:31 +00005218
5219 // If a function is explicitly defaulted on its first declaration,
5220 if (First) {
5221 // -- it is implicitly considered to be constexpr if the implicit
5222 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005223 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005224
Richard Smithb9e90b12012-05-15 04:39:51 +00005225 // -- it is implicitly considered to have the same exception-specification
5226 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005227 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005228 EPI.ExceptionSpec.Type = EST_Unevaluated;
5229 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005230 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005231 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005232 ExpectedParams),
5233 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005234 }
5235
Richard Smithb9e90b12012-05-15 04:39:51 +00005236 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005237 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005238 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005239 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005240 // C++11 [dcl.fct.def.default]p4:
5241 // [For a] user-provided explicitly-defaulted function [...] if such a
5242 // function is implicitly defined as deleted, the program is ill-formed.
5243 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005244 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005245 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005246 }
5247 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005248
Richard Smithb9e90b12012-05-15 04:39:51 +00005249 if (HadError)
5250 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005251}
5252
Richard Smithbd305122012-12-11 01:14:52 +00005253/// Check whether the exception specification provided for an
5254/// explicitly-defaulted special member matches the exception specification
5255/// that would have been generated for an implicit special member, per
5256/// C++11 [dcl.fct.def.default]p2.
5257void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5258 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5259 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005260 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5261 /*IsCXXMethod=*/true);
5262 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005263 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5264 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005265 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005266 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005267
5268 // Ensure that it matches.
5269 CheckEquivalentExceptionSpec(
5270 PDiag(diag::err_incorrect_defaulted_exception_spec)
5271 << getSpecialMember(MD), PDiag(),
5272 ImplicitType, SourceLocation(),
5273 SpecifiedType, MD->getLocation());
5274}
5275
Alp Tokerae3a9442013-10-18 05:54:19 +00005276void Sema::CheckDelayedMemberExceptionSpecs() {
5277 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5278 2> Checks;
5279 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005280
Alp Tokerae3a9442013-10-18 05:54:19 +00005281 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5282 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5283
5284 // Perform any deferred checking of exception specifications for virtual
5285 // destructors.
5286 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5287 const CXXDestructorDecl *Dtor = Checks[i].first;
5288 assert(!Dtor->getParent()->isDependentType() &&
5289 "Should not ever add destructors of templates into the list.");
5290 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5291 }
5292
5293 // Check that any explicitly-defaulted methods have exception specifications
5294 // compatible with their implicit exception specifications.
5295 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5296 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5297 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005298}
5299
Richard Smithd951a1d2012-02-18 02:02:13 +00005300namespace {
5301struct SpecialMemberDeletionInfo {
5302 Sema &S;
5303 CXXMethodDecl *MD;
5304 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005305 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005306
5307 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005308 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005309 SourceLocation Loc;
5310
5311 bool AllFieldsAreConst;
5312
5313 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005314 Sema::CXXSpecialMember CSM, bool Diagnose)
5315 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005316 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005317 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005318 AllFieldsAreConst(true) {
5319 switch (CSM) {
5320 case Sema::CXXDefaultConstructor:
5321 case Sema::CXXCopyConstructor:
5322 IsConstructor = true;
5323 break;
5324 case Sema::CXXMoveConstructor:
5325 IsConstructor = true;
5326 IsMove = true;
5327 break;
5328 case Sema::CXXCopyAssignment:
5329 IsAssignment = true;
5330 break;
5331 case Sema::CXXMoveAssignment:
5332 IsAssignment = true;
5333 IsMove = true;
5334 break;
5335 case Sema::CXXDestructor:
5336 break;
5337 case Sema::CXXInvalid:
5338 llvm_unreachable("invalid special member kind");
5339 }
5340
5341 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005342 if (const ReferenceType *RT =
5343 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5344 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005345 }
5346 }
5347
5348 bool inUnion() const { return MD->getParent()->isUnion(); }
5349
5350 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005351 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005352 unsigned Quals, bool IsMutable) {
5353 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5354 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005355 }
5356
Richard Smith852265f2012-03-30 20:53:28 +00005357 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005358
Richard Smith852265f2012-03-30 20:53:28 +00005359 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005360 bool shouldDeleteForField(FieldDecl *FD);
5361 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005362
Richard Smithaf136f82012-07-18 03:51:16 +00005363 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5364 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005365 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5366 Sema::SpecialMemberOverloadResult *SMOR,
5367 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005368
5369 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005370};
5371}
5372
John McCalld4274212012-04-09 20:53:23 +00005373/// Is the given special member inaccessible when used on the given
5374/// sub-object.
5375bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5376 CXXMethodDecl *target) {
5377 /// If we're operating on a base class, the object type is the
5378 /// type of this special member.
5379 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005380 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005381 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5382 objectTy = S.Context.getTypeDeclType(MD->getParent());
5383 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5384
5385 // If we're operating on a field, the object type is the type of the field.
5386 } else {
5387 objectTy = S.Context.getTypeDeclType(target->getParent());
5388 }
5389
5390 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5391}
5392
Richard Smith852265f2012-03-30 20:53:28 +00005393/// Check whether we should delete a special member due to the implicit
5394/// definition containing a call to a special member of a subobject.
5395bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5396 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5397 bool IsDtorCallInCtor) {
5398 CXXMethodDecl *Decl = SMOR->getMethod();
5399 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5400
5401 int DiagKind = -1;
5402
5403 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5404 DiagKind = !Decl ? 0 : 1;
5405 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5406 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005407 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005408 DiagKind = 3;
5409 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5410 !Decl->isTrivial()) {
5411 // A member of a union must have a trivial corresponding special member.
5412 // As a weird special case, a destructor call from a union's constructor
5413 // must be accessible and non-deleted, but need not be trivial. Such a
5414 // destructor is never actually called, but is semantically checked as
5415 // if it were.
5416 DiagKind = 4;
5417 }
5418
5419 if (DiagKind == -1)
5420 return false;
5421
5422 if (Diagnose) {
5423 if (Field) {
5424 S.Diag(Field->getLocation(),
5425 diag::note_deleted_special_member_class_subobject)
5426 << CSM << MD->getParent() << /*IsField*/true
5427 << Field << DiagKind << IsDtorCallInCtor;
5428 } else {
5429 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5430 S.Diag(Base->getLocStart(),
5431 diag::note_deleted_special_member_class_subobject)
5432 << CSM << MD->getParent() << /*IsField*/false
5433 << Base->getType() << DiagKind << IsDtorCallInCtor;
5434 }
5435
5436 if (DiagKind == 1)
5437 S.NoteDeletedFunction(Decl);
5438 // FIXME: Explain inaccessibility if DiagKind == 3.
5439 }
5440
5441 return true;
5442}
5443
Richard Smith921bd202012-02-26 09:11:52 +00005444/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005445/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005446bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005447 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005448 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005449 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005450
5451 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005452 // -- any direct or virtual base class, or non-static data member with no
5453 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005454 // either M has no default constructor or overload resolution as applied
5455 // to M's default constructor results in an ambiguity or in a function
5456 // that is deleted or inaccessible
5457 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5458 // -- a direct or virtual base class B that cannot be copied/moved because
5459 // overload resolution, as applied to B's corresponding special member,
5460 // results in an ambiguity or a function that is deleted or inaccessible
5461 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005462 // C++11 [class.dtor]p5:
5463 // -- any direct or virtual base class [...] has a type with a destructor
5464 // that is deleted or inaccessible
5465 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005466 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005467 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5468 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005469 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005470
Richard Smith852265f2012-03-30 20:53:28 +00005471 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5472 // -- any direct or virtual base class or non-static data member has a
5473 // type with a destructor that is deleted or inaccessible
5474 if (IsConstructor) {
5475 Sema::SpecialMemberOverloadResult *SMOR =
5476 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5477 false, false, false, false, false);
5478 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5479 return true;
5480 }
5481
Richard Smith921bd202012-02-26 09:11:52 +00005482 return false;
5483}
5484
5485/// Check whether we should delete a special member function due to the class
5486/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005487bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005488 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005489 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005490}
5491
5492/// Check whether we should delete a special member function due to the class
5493/// having a particular non-static data member.
5494bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5495 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5496 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5497
5498 if (CSM == Sema::CXXDefaultConstructor) {
5499 // For a default constructor, all references must be initialized in-class
5500 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005501 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5502 if (Diagnose)
5503 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5504 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005505 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005506 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005507 // C++11 [class.ctor]p5: any non-variant non-static data member of
5508 // const-qualified type (or array thereof) with no
5509 // brace-or-equal-initializer does not have a user-provided default
5510 // constructor.
5511 if (!inUnion() && FieldType.isConstQualified() &&
5512 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005513 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5514 if (Diagnose)
5515 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005516 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005517 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005518 }
5519
5520 if (inUnion() && !FieldType.isConstQualified())
5521 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005522 } else if (CSM == Sema::CXXCopyConstructor) {
5523 // For a copy constructor, data members must not be of rvalue reference
5524 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005525 if (FieldType->isRValueReferenceType()) {
5526 if (Diagnose)
5527 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5528 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005529 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005530 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005531 } else if (IsAssignment) {
5532 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005533 if (FieldType->isReferenceType()) {
5534 if (Diagnose)
5535 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5536 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005537 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005538 }
5539 if (!FieldRecord && FieldType.isConstQualified()) {
5540 // C++11 [class.copy]p23:
5541 // -- a non-static data member of const non-class type (or array thereof)
5542 if (Diagnose)
5543 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005544 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005545 return true;
5546 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005547 }
5548
5549 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005550 // Some additional restrictions exist on the variant members.
5551 if (!inUnion() && FieldRecord->isUnion() &&
5552 FieldRecord->isAnonymousStructOrUnion()) {
5553 bool AllVariantFieldsAreConst = true;
5554
Richard Smith5704fe82012-03-29 19:00:10 +00005555 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005556 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005557 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005558
5559 if (!UnionFieldType.isConstQualified())
5560 AllVariantFieldsAreConst = false;
5561
Richard Smith921bd202012-02-26 09:11:52 +00005562 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5563 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005564 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005565 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005566 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005567 }
5568
5569 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005570 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005571 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005572 if (Diagnose)
5573 S.Diag(FieldRecord->getLocation(),
5574 diag::note_deleted_default_ctor_all_const)
5575 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005576 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005577 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005578
Richard Smith5704fe82012-03-29 19:00:10 +00005579 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005580 // This is technically non-conformant, but sanity demands it.
5581 return false;
5582 }
5583
Richard Smithaf136f82012-07-18 03:51:16 +00005584 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5585 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005586 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005587 }
5588
5589 return false;
5590}
5591
5592/// C++11 [class.ctor] p5:
5593/// A defaulted default constructor for a class X is defined as deleted if
5594/// X is a union and all of its variant members are of const-qualified type.
5595bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005596 // This is a silly definition, because it gives an empty union a deleted
5597 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005598 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005599 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005600 if (Diagnose)
5601 S.Diag(MD->getParent()->getLocation(),
5602 diag::note_deleted_default_ctor_all_const)
5603 << MD->getParent() << /*not anonymous union*/0;
5604 return true;
5605 }
5606 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005607}
5608
5609/// Determine whether a defaulted special member function should be defined as
5610/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5611/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005612bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5613 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005614 if (MD->isInvalidDecl())
5615 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005616 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005617 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005618 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005619 return false;
5620
Richard Smithd951a1d2012-02-18 02:02:13 +00005621 // C++11 [expr.lambda.prim]p19:
5622 // The closure type associated with a lambda-expression has a
5623 // deleted (8.4.3) default constructor and a deleted copy
5624 // assignment operator.
5625 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005626 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5627 if (Diagnose)
5628 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005629 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005630 }
5631
Richard Smith6f1e2c62012-04-02 20:59:25 +00005632 // For an anonymous struct or union, the copy and assignment special members
5633 // will never be used, so skip the check. For an anonymous union declared at
5634 // namespace scope, the constructor and destructor are used.
5635 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5636 RD->isAnonymousStructOrUnion())
5637 return false;
5638
Richard Smith852265f2012-03-30 20:53:28 +00005639 // C++11 [class.copy]p7, p18:
5640 // If the class definition declares a move constructor or move assignment
5641 // operator, an implicitly declared copy constructor or copy assignment
5642 // operator is defined as deleted.
5643 if (MD->isImplicit() &&
5644 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005645 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005646
5647 // In Microsoft mode, a user-declared move only causes the deletion of the
5648 // corresponding copy operation, not both copy operations.
5649 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005650 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005651 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005652
5653 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005654 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005655 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005656 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005657 break;
5658 }
5659 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005660 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005661 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005662 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005663 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005664
5665 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005666 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005667 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005668 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005669 break;
5670 }
5671 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005672 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005673 }
5674
5675 if (UserDeclaredMove) {
5676 Diag(UserDeclaredMove->getLocation(),
5677 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005678 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005679 << UserDeclaredMove->isMoveAssignmentOperator();
5680 return true;
5681 }
5682 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005683
Richard Smith6f1e2c62012-04-02 20:59:25 +00005684 // Do access control from the special member function
5685 ContextRAII MethodContext(*this, MD);
5686
Richard Smith921bd202012-02-26 09:11:52 +00005687 // C++11 [class.dtor]p5:
5688 // -- for a virtual destructor, lookup of the non-array deallocation function
5689 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005690 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005691 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005692 DeclarationName Name =
5693 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5694 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005695 OperatorDelete, false)) {
5696 if (Diagnose)
5697 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005698 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005699 }
Richard Smith921bd202012-02-26 09:11:52 +00005700 }
5701
Richard Smith852265f2012-03-30 20:53:28 +00005702 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005703
Aaron Ballman574705e2014-03-13 15:41:46 +00005704 for (auto &BI : RD->bases())
5705 if (!BI.isVirtual() &&
5706 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005707 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005708
Richard Smithd1627032013-07-22 18:06:23 +00005709 // Per DR1611, do not consider virtual bases of constructors of abstract
5710 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005711 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005712 for (auto &BI : RD->vbases())
5713 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005714 return true;
5715 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005716
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005717 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005718 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005719 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005720 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005721
Richard Smithd951a1d2012-02-18 02:02:13 +00005722 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005723 return true;
5724
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005725 if (getLangOpts().CUDA) {
5726 // We should delete the special member in CUDA mode if target inference
5727 // failed.
5728 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5729 Diagnose);
5730 }
5731
Alexis Huntea6f0322011-05-11 22:34:38 +00005732 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005733}
5734
Richard Smith92f241f2012-12-08 02:53:02 +00005735/// Perform lookup for a special member of the specified kind, and determine
5736/// whether it is trivial. If the triviality can be determined without the
5737/// lookup, skip it. This is intended for use when determining whether a
5738/// special member of a containing object is trivial, and thus does not ever
5739/// perform overload resolution for default constructors.
5740///
5741/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5742/// member that was most likely to be intended to be trivial, if any.
5743static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5744 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005745 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005746 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005747 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005748
5749 switch (CSM) {
5750 case Sema::CXXInvalid:
5751 llvm_unreachable("not a special member");
5752
5753 case Sema::CXXDefaultConstructor:
5754 // C++11 [class.ctor]p5:
5755 // A default constructor is trivial if:
5756 // - all the [direct subobjects] have trivial default constructors
5757 //
5758 // Note, no overload resolution is performed in this case.
5759 if (RD->hasTrivialDefaultConstructor())
5760 return true;
5761
5762 if (Selected) {
5763 // If there's a default constructor which could have been trivial, dig it
5764 // out. Otherwise, if there's any user-provided default constructor, point
5765 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005766 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005767 if (RD->needsImplicitDefaultConstructor())
5768 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005769 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005770 if (!CI->isDefaultConstructor())
5771 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005772 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005773 if (!DefCtor->isUserProvided())
5774 break;
5775 }
5776
5777 *Selected = DefCtor;
5778 }
5779
5780 return false;
5781
5782 case Sema::CXXDestructor:
5783 // C++11 [class.dtor]p5:
5784 // A destructor is trivial if:
5785 // - all the direct [subobjects] have trivial destructors
5786 if (RD->hasTrivialDestructor())
5787 return true;
5788
5789 if (Selected) {
5790 if (RD->needsImplicitDestructor())
5791 S.DeclareImplicitDestructor(RD);
5792 *Selected = RD->getDestructor();
5793 }
5794
5795 return false;
5796
5797 case Sema::CXXCopyConstructor:
5798 // C++11 [class.copy]p12:
5799 // A copy constructor is trivial if:
5800 // - the constructor selected to copy each direct [subobject] is trivial
5801 if (RD->hasTrivialCopyConstructor()) {
5802 if (Quals == Qualifiers::Const)
5803 // We must either select the trivial copy constructor or reach an
5804 // ambiguity; no need to actually perform overload resolution.
5805 return true;
5806 } else if (!Selected) {
5807 return false;
5808 }
5809 // In C++98, we are not supposed to perform overload resolution here, but we
5810 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5811 // cases like B as having a non-trivial copy constructor:
5812 // struct A { template<typename T> A(T&); };
5813 // struct B { mutable A a; };
5814 goto NeedOverloadResolution;
5815
5816 case Sema::CXXCopyAssignment:
5817 // C++11 [class.copy]p25:
5818 // A copy assignment operator is trivial if:
5819 // - the assignment operator selected to copy each direct [subobject] is
5820 // trivial
5821 if (RD->hasTrivialCopyAssignment()) {
5822 if (Quals == Qualifiers::Const)
5823 return true;
5824 } else if (!Selected) {
5825 return false;
5826 }
5827 // In C++98, we are not supposed to perform overload resolution here, but we
5828 // treat that as a language defect.
5829 goto NeedOverloadResolution;
5830
5831 case Sema::CXXMoveConstructor:
5832 case Sema::CXXMoveAssignment:
5833 NeedOverloadResolution:
5834 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005835 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005836
5837 // The standard doesn't describe how to behave if the lookup is ambiguous.
5838 // We treat it as not making the member non-trivial, just like the standard
5839 // mandates for the default constructor. This should rarely matter, because
5840 // the member will also be deleted.
5841 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5842 return true;
5843
5844 if (!SMOR->getMethod()) {
5845 assert(SMOR->getKind() ==
5846 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5847 return false;
5848 }
5849
5850 // We deliberately don't check if we found a deleted special member. We're
5851 // not supposed to!
5852 if (Selected)
5853 *Selected = SMOR->getMethod();
5854 return SMOR->getMethod()->isTrivial();
5855 }
5856
5857 llvm_unreachable("unknown special method kind");
5858}
5859
Benjamin Kramer3e350262013-02-15 12:30:38 +00005860static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005861 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005862 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005863 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005864
5865 // Look for constructor templates.
5866 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5867 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5868 if (CXXConstructorDecl *CD =
5869 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5870 return CD;
5871 }
5872
Craig Topperc3ec1492014-05-26 06:22:03 +00005873 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005874}
5875
5876/// The kind of subobject we are checking for triviality. The values of this
5877/// enumeration are used in diagnostics.
5878enum TrivialSubobjectKind {
5879 /// The subobject is a base class.
5880 TSK_BaseClass,
5881 /// The subobject is a non-static data member.
5882 TSK_Field,
5883 /// The object is actually the complete object.
5884 TSK_CompleteObject
5885};
5886
5887/// Check whether the special member selected for a given type would be trivial.
5888static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005889 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005890 Sema::CXXSpecialMember CSM,
5891 TrivialSubobjectKind Kind,
5892 bool Diagnose) {
5893 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5894 if (!SubRD)
5895 return true;
5896
5897 CXXMethodDecl *Selected;
5898 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005899 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005900 return true;
5901
5902 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005903 if (ConstRHS)
5904 SubType.addConst();
5905
Richard Smith92f241f2012-12-08 02:53:02 +00005906 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5907 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5908 << Kind << SubType.getUnqualifiedType();
5909 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5910 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5911 } else if (!Selected)
5912 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5913 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5914 else if (Selected->isUserProvided()) {
5915 if (Kind == TSK_CompleteObject)
5916 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5917 << Kind << SubType.getUnqualifiedType() << CSM;
5918 else {
5919 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5920 << Kind << SubType.getUnqualifiedType() << CSM;
5921 S.Diag(Selected->getLocation(), diag::note_declared_at);
5922 }
5923 } else {
5924 if (Kind != TSK_CompleteObject)
5925 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5926 << Kind << SubType.getUnqualifiedType() << CSM;
5927
5928 // Explain why the defaulted or deleted special member isn't trivial.
5929 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5930 }
5931 }
5932
5933 return false;
5934}
5935
5936/// Check whether the members of a class type allow a special member to be
5937/// trivial.
5938static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5939 Sema::CXXSpecialMember CSM,
5940 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005941 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005942 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5943 continue;
5944
5945 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5946
5947 // Pretend anonymous struct or union members are members of this class.
5948 if (FI->isAnonymousStructOrUnion()) {
5949 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5950 CSM, ConstArg, Diagnose))
5951 return false;
5952 continue;
5953 }
5954
5955 // C++11 [class.ctor]p5:
5956 // A default constructor is trivial if [...]
5957 // -- no non-static data member of its class has a
5958 // brace-or-equal-initializer
5959 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5960 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005961 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005962 return false;
5963 }
5964
5965 // Objective C ARC 4.3.5:
5966 // [...] nontrivally ownership-qualified types are [...] not trivially
5967 // default constructible, copy constructible, move constructible, copy
5968 // assignable, move assignable, or destructible [...]
5969 if (S.getLangOpts().ObjCAutoRefCount &&
5970 FieldType.hasNonTrivialObjCLifetime()) {
5971 if (Diagnose)
5972 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5973 << RD << FieldType.getObjCLifetime();
5974 return false;
5975 }
5976
Richard Smith41c35d62013-11-27 03:39:20 +00005977 bool ConstRHS = ConstArg && !FI->isMutable();
5978 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5979 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005980 return false;
5981 }
5982
5983 return true;
5984}
5985
5986/// Diagnose why the specified class does not have a trivial special member of
5987/// the given kind.
5988void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5989 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005990
Richard Smith41c35d62013-11-27 03:39:20 +00005991 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5992 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005993 TSK_CompleteObject, /*Diagnose*/true);
5994}
5995
5996/// Determine whether a defaulted or deleted special member function is trivial,
5997/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5998/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5999bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6000 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006001 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6002
6003 CXXRecordDecl *RD = MD->getParent();
6004
6005 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006006
Richard Smith2002bfe2013-11-04 02:02:27 +00006007 // C++11 [class.copy]p12, p25: [DR1593]
6008 // A [special member] is trivial if [...] its parameter-type-list is
6009 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006010 switch (CSM) {
6011 case CXXDefaultConstructor:
6012 case CXXDestructor:
6013 // Trivial default constructors and destructors cannot have parameters.
6014 break;
6015
6016 case CXXCopyConstructor:
6017 case CXXCopyAssignment: {
6018 // Trivial copy operations always have const, non-volatile parameter types.
6019 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006020 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006021 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6022 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6023 if (Diagnose)
6024 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6025 << Param0->getSourceRange() << Param0->getType()
6026 << Context.getLValueReferenceType(
6027 Context.getRecordType(RD).withConst());
6028 return false;
6029 }
6030 break;
6031 }
6032
6033 case CXXMoveConstructor:
6034 case CXXMoveAssignment: {
6035 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006036 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006037 const RValueReferenceType *RT =
6038 Param0->getType()->getAs<RValueReferenceType>();
6039 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6040 if (Diagnose)
6041 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6042 << Param0->getSourceRange() << Param0->getType()
6043 << Context.getRValueReferenceType(Context.getRecordType(RD));
6044 return false;
6045 }
6046 break;
6047 }
6048
6049 case CXXInvalid:
6050 llvm_unreachable("not a special member");
6051 }
6052
Richard Smith92f241f2012-12-08 02:53:02 +00006053 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6054 if (Diagnose)
6055 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6056 diag::note_nontrivial_default_arg)
6057 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6058 return false;
6059 }
6060 if (MD->isVariadic()) {
6061 if (Diagnose)
6062 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6063 return false;
6064 }
6065
6066 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6067 // A copy/move [constructor or assignment operator] is trivial if
6068 // -- the [member] selected to copy/move each direct base class subobject
6069 // is trivial
6070 //
6071 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6072 // A [default constructor or destructor] is trivial if
6073 // -- all the direct base classes have trivial [default constructors or
6074 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006075 for (const auto &BI : RD->bases())
6076 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006077 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006078 return false;
6079
6080 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6081 // A copy/move [constructor or assignment operator] for a class X is
6082 // trivial if
6083 // -- for each non-static data member of X that is of class type (or array
6084 // thereof), the constructor selected to copy/move that member is
6085 // trivial
6086 //
6087 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6088 // A [default constructor or destructor] is trivial if
6089 // -- for all of the non-static data members of its class that are of class
6090 // type (or array thereof), each such class has a trivial [default
6091 // constructor or destructor]
6092 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6093 return false;
6094
6095 // C++11 [class.dtor]p5:
6096 // A destructor is trivial if [...]
6097 // -- the destructor is not virtual
6098 if (CSM == CXXDestructor && MD->isVirtual()) {
6099 if (Diagnose)
6100 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6101 return false;
6102 }
6103
6104 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6105 // A [special member] for class X is trivial if [...]
6106 // -- class X has no virtual functions and no virtual base classes
6107 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6108 if (!Diagnose)
6109 return false;
6110
6111 if (RD->getNumVBases()) {
6112 // Check for virtual bases. We already know that the corresponding
6113 // member in all bases is trivial, so vbases must all be direct.
6114 CXXBaseSpecifier &BS = *RD->vbases_begin();
6115 assert(BS.isVirtual());
6116 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6117 return false;
6118 }
6119
6120 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006121 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006122 if (MI->isVirtual()) {
6123 SourceLocation MLoc = MI->getLocStart();
6124 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6125 return false;
6126 }
6127 }
6128
6129 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6130 }
6131
6132 // Looks like it's trivial!
6133 return true;
6134}
6135
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006136/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006137namespace {
6138 struct FindHiddenVirtualMethodData {
6139 Sema *S;
6140 CXXMethodDecl *Method;
6141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006142 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006143 };
6144}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006145
David Blaikie282c92a2012-10-19 00:53:08 +00006146/// \brief Check whether any most overriden method from MD in Methods
6147static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006148 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006149 if (MD->size_overridden_methods() == 0)
6150 return Methods.count(MD->getCanonicalDecl());
6151 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6152 E = MD->end_overridden_methods();
6153 I != E; ++I)
6154 if (CheckMostOverridenMethods(*I, Methods))
6155 return true;
6156 return false;
6157}
6158
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006159/// \brief Member lookup function that determines whether a given C++
6160/// method overloads virtual methods in a base class without overriding any,
6161/// to be used with CXXRecordDecl::lookupInBases().
6162static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6163 CXXBasePath &Path,
6164 void *UserData) {
6165 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6166
6167 FindHiddenVirtualMethodData &Data
6168 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6169
6170 DeclarationName Name = Data.Method->getDeclName();
6171 assert(Name.getNameKind() == DeclarationName::Identifier);
6172
6173 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006174 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006175 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006176 !Path.Decls.empty();
6177 Path.Decls = Path.Decls.slice(1)) {
6178 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006179 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006180 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006181 foundSameNameMethod = true;
6182 // Interested only in hidden virtual methods.
6183 if (!MD->isVirtual())
6184 continue;
6185 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006186 // don't warn about the other overloaded methods. Clang deviates from GCC
6187 // by only diagnosing overloads of inherited virtual functions that do not
6188 // override any other virtual functions in the base. GCC's
6189 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6190 // function from a base class. These cases may be better served by a
6191 // warning (not specific to virtual functions) on call sites when the call
6192 // would select a different function from the base class, were it visible.
6193 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006194 if (!Data.S->IsOverload(Data.Method, MD, false))
6195 return true;
6196 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006197 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006198 overloadedMethods.push_back(MD);
6199 }
6200 }
6201
6202 if (foundSameNameMethod)
6203 Data.OverloadedMethods.append(overloadedMethods.begin(),
6204 overloadedMethods.end());
6205 return foundSameNameMethod;
6206}
6207
David Blaikie282c92a2012-10-19 00:53:08 +00006208/// \brief Add the most overriden methods from MD to Methods
6209static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006210 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006211 if (MD->size_overridden_methods() == 0)
6212 Methods.insert(MD->getCanonicalDecl());
6213 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6214 E = MD->end_overridden_methods();
6215 I != E; ++I)
6216 AddMostOverridenMethods(*I, Methods);
6217}
6218
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006219/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006220/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006221void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6222 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006223 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006224 return;
6225
6226 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6227 /*bool RecordPaths=*/false,
6228 /*bool DetectVirtual=*/false);
6229 FindHiddenVirtualMethodData Data;
6230 Data.Method = MD;
6231 Data.S = this;
6232
6233 // Keep the base methods that were overriden or introduced in the subclass
6234 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006235 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006236 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6237 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6238 NamedDecl *ND = *I;
6239 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006240 ND = shad->getTargetDecl();
6241 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6242 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006243 }
6244
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006245 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6246 OverloadedMethods = Data.OverloadedMethods;
6247}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006248
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006249void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6250 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6251 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6252 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6253 PartialDiagnostic PD = PDiag(
6254 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6255 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6256 Diag(overloadedMD->getLocation(), PD);
6257 }
6258}
6259
6260/// \brief Diagnose methods which overload virtual methods in a base class
6261/// without overriding any.
6262void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6263 if (MD->isInvalidDecl())
6264 return;
6265
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006266 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006267 return;
6268
6269 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6270 FindHiddenVirtualMethods(MD, OverloadedMethods);
6271 if (!OverloadedMethods.empty()) {
6272 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6273 << MD << (OverloadedMethods.size() > 1);
6274
6275 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006276 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006277}
6278
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006279void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006280 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006281 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006282 SourceLocation RBrac,
6283 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006284 if (!TagDecl)
6285 return;
Mike Stump11289f42009-09-09 15:08:12 +00006286
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006287 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006288
Rafael Espindola06e1b132012-07-12 04:32:30 +00006289 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6290 if (l->getKind() != AttributeList::AT_Visibility)
6291 continue;
6292 l->setInvalid();
6293 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6294 l->getName();
6295 }
6296
David Blaikie751c5582011-09-22 02:58:26 +00006297 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006298 // strict aliasing violation!
6299 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006300 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006301
Douglas Gregor0be31a22010-07-02 17:43:08 +00006302 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006303 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006304}
6305
Douglas Gregor05379422008-11-03 17:51:48 +00006306/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6307/// special functions, such as the default constructor, copy
6308/// constructor, or destructor, to the given C++ class (C++
6309/// [special]p1). This routine can only be executed just before the
6310/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006311void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006312 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006313 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006314
Richard Smith6b02d462012-12-08 08:32:28 +00006315 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006316 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006317
Richard Smith6b02d462012-12-08 08:32:28 +00006318 // If the properties or semantics of the copy constructor couldn't be
6319 // determined while the class was being declared, force a declaration
6320 // of it now.
6321 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6322 DeclareImplicitCopyConstructor(ClassDecl);
6323 }
6324
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006325 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006326 ++ASTContext::NumImplicitMoveConstructors;
6327
Richard Smith6b02d462012-12-08 08:32:28 +00006328 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6329 DeclareImplicitMoveConstructor(ClassDecl);
6330 }
6331
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006332 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6333 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006334
6335 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006336 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006337 // it shows up in the right place in the vtable and that we diagnose
6338 // problems with the implicit exception specification.
6339 if (ClassDecl->isDynamicClass() ||
6340 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006341 DeclareImplicitCopyAssignment(ClassDecl);
6342 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006343
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006344 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006345 ++ASTContext::NumImplicitMoveAssignmentOperators;
6346
6347 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006348 if (ClassDecl->isDynamicClass() ||
6349 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006350 DeclareImplicitMoveAssignment(ClassDecl);
6351 }
6352
Douglas Gregor7454c562010-07-02 20:37:36 +00006353 if (!ClassDecl->hasUserDeclaredDestructor()) {
6354 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006355
6356 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006357 // have to declare the destructor immediately. This ensures that, e.g., it
6358 // shows up in the right place in the vtable and that we diagnose problems
6359 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006360 if (ClassDecl->isDynamicClass() ||
6361 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006362 DeclareImplicitDestructor(ClassDecl);
6363 }
Douglas Gregor05379422008-11-03 17:51:48 +00006364}
6365
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006366unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006367 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006368 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006369
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006370 // The order of template parameters is not important here. All names
6371 // get added to the same scope.
6372 SmallVector<TemplateParameterList *, 4> ParameterLists;
6373
6374 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6375 D = TD->getTemplatedDecl();
6376
6377 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6378 ParameterLists.push_back(PSD->getTemplateParameters());
6379
6380 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6381 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6382 ParameterLists.push_back(DD->getTemplateParameterList(i));
6383
6384 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6385 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6386 ParameterLists.push_back(FTD->getTemplateParameters());
6387 }
6388 }
6389
6390 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6391 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6392 ParameterLists.push_back(TD->getTemplateParameterList(i));
6393
6394 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6395 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6396 ParameterLists.push_back(CTD->getTemplateParameters());
6397 }
6398 }
6399
6400 unsigned Count = 0;
6401 for (TemplateParameterList *Params : ParameterLists) {
6402 if (Params->size() > 0)
6403 // Ignore explicit specializations; they don't contribute to the template
6404 // depth.
6405 ++Count;
6406 for (NamedDecl *Param : *Params) {
6407 if (Param->getDeclName()) {
6408 S->AddDecl(Param);
6409 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006410 }
6411 }
6412 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006413
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006414 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006415}
6416
John McCall48871652010-08-21 09:40:31 +00006417void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006418 if (!RecordD) return;
6419 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006420 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006421 PushDeclContext(S, Record);
6422}
6423
John McCall48871652010-08-21 09:40:31 +00006424void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006425 if (!RecordD) return;
6426 PopDeclContext();
6427}
6428
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006429/// This is used to implement the constant expression evaluation part of the
6430/// attribute enable_if extension. There is nothing in standard C++ which would
6431/// require reentering parameters.
6432void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6433 if (!Param)
6434 return;
6435
6436 S->AddDecl(Param);
6437 if (Param->getDeclName())
6438 IdResolver.AddDecl(Param);
6439}
6440
Douglas Gregor4d87df52008-12-16 21:30:33 +00006441/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6442/// parsing a top-level (non-nested) C++ class, and we are now
6443/// parsing those parts of the given Method declaration that could
6444/// not be parsed earlier (C++ [class.mem]p2), such as default
6445/// arguments. This action should enter the scope of the given
6446/// Method declaration as if we had just parsed the qualified method
6447/// name. However, it should not bring the parameters into scope;
6448/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006449void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006450}
6451
6452/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6453/// C++ method declaration. We're (re-)introducing the given
6454/// function parameter into scope for use in parsing later parts of
6455/// the method declaration. For example, we could see an
6456/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006457void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006458 if (!ParamD)
6459 return;
Mike Stump11289f42009-09-09 15:08:12 +00006460
John McCall48871652010-08-21 09:40:31 +00006461 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006462
6463 // If this parameter has an unparsed default argument, clear it out
6464 // to make way for the parsed default argument.
6465 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006466 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006467
John McCall48871652010-08-21 09:40:31 +00006468 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006469 if (Param->getDeclName())
6470 IdResolver.AddDecl(Param);
6471}
6472
6473/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6474/// processing the delayed method declaration for Method. The method
6475/// declaration is now considered finished. There may be a separate
6476/// ActOnStartOfFunctionDef action later (not necessarily
6477/// immediately!) for this method, if it was also defined inside the
6478/// class body.
John McCall48871652010-08-21 09:40:31 +00006479void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006480 if (!MethodD)
6481 return;
Mike Stump11289f42009-09-09 15:08:12 +00006482
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006483 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006484
John McCall48871652010-08-21 09:40:31 +00006485 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006486
6487 // Now that we have our default arguments, check the constructor
6488 // again. It could produce additional diagnostics or affect whether
6489 // the class has implicitly-declared destructors, among other
6490 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6492 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006493
6494 // Check the default arguments, which we may have added.
6495 if (!Method->isInvalidDecl())
6496 CheckCXXDefaultArguments(Method);
6497}
6498
Douglas Gregor831c93f2008-11-05 20:51:48 +00006499/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006500/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006501/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006502/// emit diagnostics and set the invalid bit to true. In any case, the type
6503/// will be updated to reflect a well-formed type for the constructor and
6504/// returned.
6505QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006506 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006507 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006508
6509 // C++ [class.ctor]p3:
6510 // A constructor shall not be virtual (10.3) or static (9.4). A
6511 // constructor can be invoked for a const, volatile or const
6512 // volatile object. A constructor shall not be declared const,
6513 // volatile, or const volatile (9.3.2).
6514 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006515 if (!D.isInvalidType())
6516 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6517 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6518 << SourceRange(D.getIdentifierLoc());
6519 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006520 }
John McCall8e7d6562010-08-26 03:08:43 +00006521 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006522 if (!D.isInvalidType())
6523 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6524 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6525 << SourceRange(D.getIdentifierLoc());
6526 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006527 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006528 }
Mike Stump11289f42009-09-09 15:08:12 +00006529
David Majnemer03f705f2014-07-08 18:18:04 +00006530 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6531 diagnoseIgnoredQualifiers(
6532 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6533 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6534 D.getDeclSpec().getRestrictSpecLoc(),
6535 D.getDeclSpec().getAtomicSpecLoc());
6536 D.setInvalidType();
6537 }
6538
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006539 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006540 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006541 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006542 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6543 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006544 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006545 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6546 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006547 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006548 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6549 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006550 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006551 }
Mike Stump11289f42009-09-09 15:08:12 +00006552
Douglas Gregordb9d6642011-01-26 05:01:58 +00006553 // C++0x [class.ctor]p4:
6554 // A constructor shall not be declared with a ref-qualifier.
6555 if (FTI.hasRefQualifier()) {
6556 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6557 << FTI.RefQualifierIsLValueRef
6558 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6559 D.setInvalidType();
6560 }
6561
Douglas Gregor831c93f2008-11-05 20:51:48 +00006562 // Rebuild the function type "R" without any type qualifiers (in
6563 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006564 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006565 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006566 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006567 return R;
6568
6569 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6570 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006571 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006572
6573 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006574}
6575
Douglas Gregor4d87df52008-12-16 21:30:33 +00006576/// CheckConstructor - Checks a fully-formed constructor for
6577/// well-formedness, issuing any diagnostics required. Returns true if
6578/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006579void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006580 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006581 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6582 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006583 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006584
6585 // C++ [class.copy]p3:
6586 // A declaration of a constructor for a class X is ill-formed if
6587 // its first parameter is of type (optionally cv-qualified) X and
6588 // either there are no other parameters or else all other
6589 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006590 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006591 ((Constructor->getNumParams() == 1) ||
6592 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006593 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6594 Constructor->getTemplateSpecializationKind()
6595 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006596 QualType ParamType = Constructor->getParamDecl(0)->getType();
6597 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6598 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006599 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006600 const char *ConstRef
6601 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6602 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006603 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006604 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006605
6606 // FIXME: Rather that making the constructor invalid, we should endeavor
6607 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006608 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006609 }
6610 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006611}
6612
John McCalldeb646e2010-08-04 01:04:25 +00006613/// CheckDestructor - Checks a fully-formed destructor definition for
6614/// well-formedness, issuing any diagnostics required. Returns true
6615/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006616bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006617 CXXRecordDecl *RD = Destructor->getParent();
6618
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006619 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006620 SourceLocation Loc;
6621
6622 if (!Destructor->isImplicit())
6623 Loc = Destructor->getLocation();
6624 else
6625 Loc = RD->getLocation();
6626
6627 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006628 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006629 DeclarationName Name =
6630 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006631 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006632 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006633 // If there's no class-specific operator delete, look up the global
6634 // non-array delete.
6635 if (!OperatorDelete)
6636 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006637
Eli Friedmanfa0df832012-02-02 03:46:19 +00006638 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006639
6640 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006641 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006642
6643 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006644}
6645
Douglas Gregor831c93f2008-11-05 20:51:48 +00006646/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6647/// the well-formednes of the destructor declarator @p D with type @p
6648/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006649/// emit diagnostics and set the declarator to invalid. Even if this happens,
6650/// will be updated to reflect a well-formed type for the destructor and
6651/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006652QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006653 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006654 // C++ [class.dtor]p1:
6655 // [...] A typedef-name that names a class is a class-name
6656 // (7.1.3); however, a typedef-name that names a class shall not
6657 // be used as the identifier in the declarator for a destructor
6658 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006659 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006660 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006661 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006662 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006663 else if (const TemplateSpecializationType *TST =
6664 DeclaratorType->getAs<TemplateSpecializationType>())
6665 if (TST->isTypeAlias())
6666 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6667 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006668
6669 // C++ [class.dtor]p2:
6670 // A destructor is used to destroy objects of its class type. A
6671 // destructor takes no parameters, and no return type can be
6672 // specified for it (not even void). The address of a destructor
6673 // shall not be taken. A destructor shall not be static. A
6674 // destructor can be invoked for a const, volatile or const
6675 // volatile object. A destructor shall not be declared const,
6676 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006677 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006678 if (!D.isInvalidType())
6679 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6680 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006681 << SourceRange(D.getIdentifierLoc())
6682 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6683
John McCall8e7d6562010-08-26 03:08:43 +00006684 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006685 }
David Majnemer03f705f2014-07-08 18:18:04 +00006686 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006687 // Destructors don't have return types, but the parser will
6688 // happily parse something like:
6689 //
6690 // class X {
6691 // float ~X();
6692 // };
6693 //
6694 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006695 if (D.getDeclSpec().hasTypeSpecifier())
6696 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6697 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6698 << SourceRange(D.getIdentifierLoc());
6699 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6700 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6701 SourceLocation(),
6702 D.getDeclSpec().getConstSpecLoc(),
6703 D.getDeclSpec().getVolatileSpecLoc(),
6704 D.getDeclSpec().getRestrictSpecLoc(),
6705 D.getDeclSpec().getAtomicSpecLoc());
6706 D.setInvalidType();
6707 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006708 }
Mike Stump11289f42009-09-09 15:08:12 +00006709
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006710 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006711 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006712 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006713 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6714 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006715 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006716 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6717 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006718 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006719 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6720 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006721 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006722 }
6723
Douglas Gregordb9d6642011-01-26 05:01:58 +00006724 // C++0x [class.dtor]p2:
6725 // A destructor shall not be declared with a ref-qualifier.
6726 if (FTI.hasRefQualifier()) {
6727 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6728 << FTI.RefQualifierIsLValueRef
6729 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6730 D.setInvalidType();
6731 }
6732
Douglas Gregor831c93f2008-11-05 20:51:48 +00006733 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006734 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006735 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6736
6737 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006738 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006739 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006740 }
6741
Mike Stump11289f42009-09-09 15:08:12 +00006742 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006743 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006744 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006745 D.setInvalidType();
6746 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006747
6748 // Rebuild the function type "R" without any type qualifiers or
6749 // parameters (in case any of the errors above fired) and with
6750 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006751 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006752 if (!D.isInvalidType())
6753 return R;
6754
Douglas Gregor95755162010-07-01 05:10:53 +00006755 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006756 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6757 EPI.Variadic = false;
6758 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006759 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006760 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006761}
6762
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006763/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6764/// well-formednes of the conversion function declarator @p D with
6765/// type @p R. If there are any errors in the declarator, this routine
6766/// will emit diagnostics and return true. Otherwise, it will return
6767/// false. Either way, the type @p R will be updated to reflect a
6768/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006769void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006770 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006771 // C++ [class.conv.fct]p1:
6772 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006773 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006774 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006775 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006776 if (!D.isInvalidType())
6777 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006778 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6779 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006780 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006781 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006782 }
John McCall212fa2e2010-04-13 00:04:31 +00006783
6784 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6785
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006786 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006787 // Conversion functions don't have return types, but the parser will
6788 // happily parse something like:
6789 //
6790 // class X {
6791 // float operator bool();
6792 // };
6793 //
6794 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006795 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6796 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6797 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006798 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006799 }
6800
John McCall212fa2e2010-04-13 00:04:31 +00006801 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6802
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006803 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006804 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006805 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6806
6807 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006808 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006809 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006810 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006811 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006812 D.setInvalidType();
6813 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006814
John McCall212fa2e2010-04-13 00:04:31 +00006815 // Diagnose "&operator bool()" and other such nonsense. This
6816 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006817 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006818 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006819 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006820 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006821 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006822 }
6823
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006824 // C++ [class.conv.fct]p4:
6825 // The conversion-type-id shall not represent a function type nor
6826 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006827 if (ConvType->isArrayType()) {
6828 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6829 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006830 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006831 } else if (ConvType->isFunctionType()) {
6832 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6833 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006834 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006835 }
6836
6837 // Rebuild the function type "R" without any parameters (in case any
6838 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006839 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006840 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006841 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006842
Douglas Gregor5fb53972009-01-14 15:45:31 +00006843 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006844 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006845 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006846 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006847 diag::warn_cxx98_compat_explicit_conversion_functions :
6848 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006849 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006850}
6851
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006852/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6853/// the declaration of the given C++ conversion function. This routine
6854/// is responsible for recording the conversion function in the C++
6855/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006856Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006857 assert(Conversion && "Expected to receive a conversion function declaration");
6858
Douglas Gregor4287b372008-12-12 08:25:50 +00006859 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006860
6861 // Make sure we aren't redeclaring the conversion function.
6862 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006863
6864 // C++ [class.conv.fct]p1:
6865 // [...] A conversion function is never used to convert a
6866 // (possibly cv-qualified) object to the (possibly cv-qualified)
6867 // same object type (or a reference to it), to a (possibly
6868 // cv-qualified) base class of that type (or a reference to it),
6869 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006870 // FIXME: Suppress this warning if the conversion function ends up being a
6871 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006872 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006873 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006874 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006875 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006876 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6877 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006878 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006879 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006880 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6881 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006882 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006883 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006884 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006885 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006886 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006887 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006888 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006889 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006890 }
6891
Douglas Gregor457104e2010-09-29 04:25:11 +00006892 if (FunctionTemplateDecl *ConversionTemplate
6893 = Conversion->getDescribedFunctionTemplate())
6894 return ConversionTemplate;
6895
John McCall48871652010-08-21 09:40:31 +00006896 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006897}
6898
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006899//===----------------------------------------------------------------------===//
6900// Namespace Handling
6901//===----------------------------------------------------------------------===//
6902
Richard Smith45bb8852012-10-04 22:13:39 +00006903/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6904/// reopened.
6905static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6906 SourceLocation Loc,
6907 IdentifierInfo *II, bool *IsInline,
6908 NamespaceDecl *PrevNS) {
6909 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006910
Richard Smithf501cc32012-10-05 01:46:25 +00006911 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6912 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6913 // inline namespaces, with the intention of bringing names into namespace std.
6914 //
6915 // We support this just well enough to get that case working; this is not
6916 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006917 if (*IsInline && II && II->getName().startswith("__atomic") &&
6918 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006919 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006920 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6921 NS = NS->getPreviousDecl())
6922 NS->setInline(*IsInline);
6923 // Patch up the lookup table for the containing namespace. This isn't really
6924 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006925 for (auto *I : PrevNS->decls())
6926 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006927 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6928 return;
6929 }
6930
6931 if (PrevNS->isInline())
6932 // The user probably just forgot the 'inline', so suggest that it
6933 // be added back.
6934 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6935 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6936 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006937 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006938
6939 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6940 *IsInline = PrevNS->isInline();
6941}
John McCallb1be5232010-08-26 09:15:37 +00006942
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006943/// ActOnStartNamespaceDef - This is called at the start of a namespace
6944/// definition.
John McCall48871652010-08-21 09:40:31 +00006945Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006946 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006947 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006948 SourceLocation IdentLoc,
6949 IdentifierInfo *II,
6950 SourceLocation LBrace,
6951 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006952 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6953 // For anonymous namespace, take the location of the left brace.
6954 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006955 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006956 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006957 bool IsStd = false;
6958 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006959 Scope *DeclRegionScope = NamespcScope->getParent();
6960
Craig Topperc3ec1492014-05-26 06:22:03 +00006961 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006962 if (II) {
6963 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006964 // The identifier in an original-namespace-definition shall not
6965 // have been previously defined in the declarative region in
6966 // which the original-namespace-definition appears. The
6967 // identifier in an original-namespace-definition is the name of
6968 // the namespace. Subsequently in that declarative region, it is
6969 // treated as an original-namespace-name.
6970 //
6971 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006972 // look through using directives, just look for any ordinary names.
6973
6974 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006975 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6976 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006977 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006978 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6979 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6980 ++I) {
6981 if ((*I)->getIdentifierNamespace() & IDNS) {
6982 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006983 break;
6984 }
6985 }
6986
Douglas Gregore57e7522012-01-07 09:11:48 +00006987 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6988
6989 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006990 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006991 if (IsInline != PrevNS->isInline())
6992 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6993 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006994 } else if (PrevDecl) {
6995 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006996 Diag(Loc, diag::err_redefinition_different_kind)
6997 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006998 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006999 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007000 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007001 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007002 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007003 // This is the first "real" definition of the namespace "std", so update
7004 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007005 PrevNS = getStdNamespace();
7006 IsStd = true;
7007 AddToKnown = !IsInline;
7008 } else {
7009 // We've seen this namespace for the first time.
7010 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007011 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007012 } else {
John McCall4fa53422009-10-01 00:25:31 +00007013 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007014
7015 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007016 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007017 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007018 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007019 } else {
7020 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007021 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007022 }
7023
Richard Smith45bb8852012-10-04 22:13:39 +00007024 if (PrevNS && IsInline != PrevNS->isInline())
7025 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7026 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007027 }
7028
7029 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7030 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007031 if (IsInvalid)
7032 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007033
7034 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007035
Douglas Gregore57e7522012-01-07 09:11:48 +00007036 // FIXME: Should we be merging attributes?
7037 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007038 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007039
7040 if (IsStd)
7041 StdNamespace = Namespc;
7042 if (AddToKnown)
7043 KnownNamespaces[Namespc] = false;
7044
7045 if (II) {
7046 PushOnScopeChains(Namespc, DeclRegionScope);
7047 } else {
7048 // Link the anonymous namespace into its parent.
7049 DeclContext *Parent = CurContext->getRedeclContext();
7050 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7051 TU->setAnonymousNamespace(Namespc);
7052 } else {
7053 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007054 }
John McCall4fa53422009-10-01 00:25:31 +00007055
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007056 CurContext->addDecl(Namespc);
7057
John McCall4fa53422009-10-01 00:25:31 +00007058 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7059 // behaves as if it were replaced by
7060 // namespace unique { /* empty body */ }
7061 // using namespace unique;
7062 // namespace unique { namespace-body }
7063 // where all occurrences of 'unique' in a translation unit are
7064 // replaced by the same identifier and this identifier differs
7065 // from all other identifiers in the entire program.
7066
7067 // We just create the namespace with an empty name and then add an
7068 // implicit using declaration, just like the standard suggests.
7069 //
7070 // CodeGen enforces the "universally unique" aspect by giving all
7071 // declarations semantically contained within an anonymous
7072 // namespace internal linkage.
7073
Douglas Gregore57e7522012-01-07 09:11:48 +00007074 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007075 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007076 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007077 /* 'using' */ LBrace,
7078 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007079 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007080 /* identifier */ SourceLocation(),
7081 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007082 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007083 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007084 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007085 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007086 }
7087
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007088 ActOnDocumentableDecl(Namespc);
7089
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007090 // Although we could have an invalid decl (i.e. the namespace name is a
7091 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007092 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7093 // for the namespace has the declarations that showed up in that particular
7094 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007095 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007096 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007097}
7098
Sebastian Redla6602e92009-11-23 15:34:23 +00007099/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7100/// is a namespace alias, returns the namespace it points to.
7101static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7102 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7103 return AD->getNamespace();
7104 return dyn_cast_or_null<NamespaceDecl>(D);
7105}
7106
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007107/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7108/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007109void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007110 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7111 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007112 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007113 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007114 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007115 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007116}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007117
John McCall28a0cf72010-08-25 07:42:41 +00007118CXXRecordDecl *Sema::getStdBadAlloc() const {
7119 return cast_or_null<CXXRecordDecl>(
7120 StdBadAlloc.get(Context.getExternalSource()));
7121}
7122
7123NamespaceDecl *Sema::getStdNamespace() const {
7124 return cast_or_null<NamespaceDecl>(
7125 StdNamespace.get(Context.getExternalSource()));
7126}
7127
Douglas Gregorcdf87022010-06-29 17:53:46 +00007128/// \brief Retrieve the special "std" namespace, which may require us to
7129/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007130NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007131 if (!StdNamespace) {
7132 // The "std" namespace has not yet been defined, so build one implicitly.
7133 StdNamespace = NamespaceDecl::Create(Context,
7134 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007135 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007136 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007137 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007138 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007139 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007140 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007141
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007142 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007143}
7144
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007145bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007146 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007147 "Looking for std::initializer_list outside of C++.");
7148
7149 // We're looking for implicit instantiations of
7150 // template <typename E> class std::initializer_list.
7151
7152 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7153 return false;
7154
Craig Topperc3ec1492014-05-26 06:22:03 +00007155 ClassTemplateDecl *Template = nullptr;
7156 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007157
Sebastian Redl43144e72012-01-17 22:49:58 +00007158 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007159
Sebastian Redl43144e72012-01-17 22:49:58 +00007160 ClassTemplateSpecializationDecl *Specialization =
7161 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7162 if (!Specialization)
7163 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007164
Sebastian Redl43144e72012-01-17 22:49:58 +00007165 Template = Specialization->getSpecializedTemplate();
7166 Arguments = Specialization->getTemplateArgs().data();
7167 } else if (const TemplateSpecializationType *TST =
7168 Ty->getAs<TemplateSpecializationType>()) {
7169 Template = dyn_cast_or_null<ClassTemplateDecl>(
7170 TST->getTemplateName().getAsTemplateDecl());
7171 Arguments = TST->getArgs();
7172 }
7173 if (!Template)
7174 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007175
7176 if (!StdInitializerList) {
7177 // Haven't recognized std::initializer_list yet, maybe this is it.
7178 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7179 if (TemplateClass->getIdentifier() !=
7180 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007181 !getStdNamespace()->InEnclosingNamespaceSetOf(
7182 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007183 return false;
7184 // This is a template called std::initializer_list, but is it the right
7185 // template?
7186 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007187 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007188 return false;
7189 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7190 return false;
7191
7192 // It's the right template.
7193 StdInitializerList = Template;
7194 }
7195
7196 if (Template != StdInitializerList)
7197 return false;
7198
7199 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007200 if (Element)
7201 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007202 return true;
7203}
7204
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007205static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7206 NamespaceDecl *Std = S.getStdNamespace();
7207 if (!Std) {
7208 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007209 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007210 }
7211
7212 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7213 Loc, Sema::LookupOrdinaryName);
7214 if (!S.LookupQualifiedName(Result, Std)) {
7215 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007216 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007217 }
7218 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7219 if (!Template) {
7220 Result.suppressDiagnostics();
7221 // We found something weird. Complain about the first thing we found.
7222 NamedDecl *Found = *Result.begin();
7223 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007224 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007225 }
7226
7227 // We found some template called std::initializer_list. Now verify that it's
7228 // correct.
7229 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007230 if (Params->getMinRequiredArguments() != 1 ||
7231 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007232 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007233 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007234 }
7235
7236 return Template;
7237}
7238
7239QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7240 if (!StdInitializerList) {
7241 StdInitializerList = LookupStdInitializerList(*this, Loc);
7242 if (!StdInitializerList)
7243 return QualType();
7244 }
7245
7246 TemplateArgumentListInfo Args(Loc, Loc);
7247 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7248 Context.getTrivialTypeSourceInfo(Element,
7249 Loc)));
7250 return Context.getCanonicalType(
7251 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7252}
7253
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007254bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7255 // C++ [dcl.init.list]p2:
7256 // A constructor is an initializer-list constructor if its first parameter
7257 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7258 // std::initializer_list<E> for some type E, and either there are no other
7259 // parameters or else all other parameters have default arguments.
7260 if (Ctor->getNumParams() < 1 ||
7261 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7262 return false;
7263
7264 QualType ArgType = Ctor->getParamDecl(0)->getType();
7265 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7266 ArgType = RT->getPointeeType().getUnqualifiedType();
7267
Craig Topperc3ec1492014-05-26 06:22:03 +00007268 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007269}
7270
Douglas Gregora172e082011-03-26 22:25:30 +00007271/// \brief Determine whether a using statement is in a context where it will be
7272/// apply in all contexts.
7273static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7274 switch (CurContext->getDeclKind()) {
7275 case Decl::TranslationUnit:
7276 return true;
7277 case Decl::LinkageSpec:
7278 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7279 default:
7280 return false;
7281 }
7282}
7283
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007284namespace {
7285
7286// Callback to only accept typo corrections that are namespaces.
7287class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007288public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007289 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007290 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007291 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007292 return false;
7293 }
7294};
7295
7296}
7297
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007298static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7299 CXXScopeSpec &SS,
7300 SourceLocation IdentLoc,
7301 IdentifierInfo *Ident) {
7302 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007303 if (TypoCorrection Corrected =
7304 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7305 llvm::make_unique<NamespaceValidatorCCC>(),
7306 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007307 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007308 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7309 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007310 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007311 S.diagnoseTypo(Corrected,
7312 S.PDiag(diag::err_using_directive_member_suggest)
7313 << Ident << DC << DroppedSpecifier << SS.getRange(),
7314 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007315 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007316 S.diagnoseTypo(Corrected,
7317 S.PDiag(diag::err_using_directive_suggest) << Ident,
7318 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007319 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007320 R.addDecl(Corrected.getCorrectionDecl());
7321 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007322 }
7323 return false;
7324}
7325
John McCall48871652010-08-21 09:40:31 +00007326Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007327 SourceLocation UsingLoc,
7328 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007329 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007330 SourceLocation IdentLoc,
7331 IdentifierInfo *NamespcName,
7332 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007333 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7334 assert(NamespcName && "Invalid NamespcName.");
7335 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007336
7337 // This can only happen along a recovery path.
7338 while (S->getFlags() & Scope::TemplateParamScope)
7339 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007340 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007341
Craig Topperc3ec1492014-05-26 06:22:03 +00007342 UsingDirectiveDecl *UDir = nullptr;
7343 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007344 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007345 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007346
Douglas Gregor34074322009-01-14 22:20:51 +00007347 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007348 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7349 LookupParsedName(R, S, &SS);
7350 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007351 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007352
Douglas Gregorcdf87022010-06-29 17:53:46 +00007353 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007354 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007355 // Allow "using namespace std;" or "using namespace ::std;" even if
7356 // "std" hasn't been defined yet, for GCC compatibility.
7357 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7358 NamespcName->isStr("std")) {
7359 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007360 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007361 R.resolveKind();
7362 }
7363 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007364 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007365 }
7366
John McCall9f3059a2009-10-09 21:13:30 +00007367 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007368 NamedDecl *Named = R.getFoundDecl();
7369 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7370 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007371 // C++ [namespace.udir]p1:
7372 // A using-directive specifies that the names in the nominated
7373 // namespace can be used in the scope in which the
7374 // using-directive appears after the using-directive. During
7375 // unqualified name lookup (3.4.1), the names appear as if they
7376 // were declared in the nearest enclosing namespace which
7377 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007378 // namespace. [Note: in this context, "contains" means "contains
7379 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007380
7381 // Find enclosing context containing both using-directive and
7382 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007383 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007384 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7385 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7386 CommonAncestor = CommonAncestor->getParent();
7387
Sebastian Redla6602e92009-11-23 15:34:23 +00007388 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007389 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007390 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007391
Douglas Gregora172e082011-03-26 22:25:30 +00007392 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007393 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007394 Diag(IdentLoc, diag::warn_using_directive_in_header);
7395 }
7396
Douglas Gregor889ceb72009-02-03 19:21:40 +00007397 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007398 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007399 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007400 }
7401
Richard Smith54ecd982013-02-20 19:22:51 +00007402 if (UDir)
7403 ProcessDeclAttributeList(S, UDir, AttrList);
7404
John McCall48871652010-08-21 09:40:31 +00007405 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007406}
7407
7408void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007409 // If the scope has an associated entity and the using directive is at
7410 // namespace or translation unit scope, add the UsingDirectiveDecl into
7411 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007412 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007413 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007414 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007415 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007416 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007417 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007418 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007419}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007420
Douglas Gregorfec52632009-06-20 00:51:54 +00007421
John McCall48871652010-08-21 09:40:31 +00007422Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007423 AccessSpecifier AS,
7424 bool HasUsingKeyword,
7425 SourceLocation UsingLoc,
7426 CXXScopeSpec &SS,
7427 UnqualifiedId &Name,
7428 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007429 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007430 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007431 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007432
Douglas Gregor220f4272009-11-04 16:30:06 +00007433 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007434 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007435 case UnqualifiedId::IK_Identifier:
7436 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007437 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007438 case UnqualifiedId::IK_ConversionFunctionId:
7439 break;
7440
7441 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007442 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007443 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007444 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007445 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007446 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007447 diag::err_using_decl_constructor)
7448 << SS.getRange();
7449
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007450 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007451
Craig Topperc3ec1492014-05-26 06:22:03 +00007452 return nullptr;
7453
Douglas Gregor220f4272009-11-04 16:30:06 +00007454 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007455 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007456 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007457 return nullptr;
7458
Douglas Gregor220f4272009-11-04 16:30:06 +00007459 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007460 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007461 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007462 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007463 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007464
7465 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7466 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007467 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007468 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007469
Richard Smithc2bc61b2013-03-18 21:12:30 +00007470 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007471 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007472 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007473 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7474 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007475 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007476 }
7477
Douglas Gregorc4356532010-12-16 00:46:58 +00007478 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7479 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007480 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007481
John McCall3f746822009-11-17 05:59:44 +00007482 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007483 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007484 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007485 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007486 if (UD)
7487 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007488
John McCall48871652010-08-21 09:40:31 +00007489 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007490}
7491
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007492/// \brief Determine whether a using declaration considers the given
7493/// declarations as "equivalent", e.g., if they are redeclarations of
7494/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007495static bool
7496IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7497 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007498 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007499
Richard Smithdda56e42011-04-15 14:24:37 +00007500 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007501 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007502 return Context.hasSameType(TD1->getUnderlyingType(),
7503 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007504
7505 return false;
7506}
7507
7508
John McCall84d87672009-12-10 09:41:52 +00007509/// Determines whether to create a using shadow decl for a particular
7510/// decl, given the set of decls existing prior to this using lookup.
7511bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007512 const LookupResult &Previous,
7513 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007514 // Diagnose finding a decl which is not from a base class of the
7515 // current class. We do this now because there are cases where this
7516 // function will silently decide not to build a shadow decl, which
7517 // will pre-empt further diagnostics.
7518 //
7519 // We don't need to do this in C++0x because we do the check once on
7520 // the qualifier.
7521 //
7522 // FIXME: diagnose the following if we care enough:
7523 // struct A { int foo; };
7524 // struct B : A { using A::foo; };
7525 // template <class T> struct C : A {};
7526 // template <class T> struct D : C<T> { using B::foo; } // <---
7527 // This is invalid (during instantiation) in C++03 because B::foo
7528 // resolves to the using decl in B, which is not a base class of D<T>.
7529 // We can't diagnose it immediately because C<T> is an unknown
7530 // specialization. The UsingShadowDecl in D<T> then points directly
7531 // to A::foo, which will look well-formed when we instantiate.
7532 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007533 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007534 DeclContext *OrigDC = Orig->getDeclContext();
7535
7536 // Handle enums and anonymous structs.
7537 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7538 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7539 while (OrigRec->isAnonymousStructOrUnion())
7540 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7541
7542 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7543 if (OrigDC == CurContext) {
7544 Diag(Using->getLocation(),
7545 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007546 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007547 Diag(Orig->getLocation(), diag::note_using_decl_target);
7548 return true;
7549 }
7550
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007551 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007552 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007553 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007554 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007555 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007556 Diag(Orig->getLocation(), diag::note_using_decl_target);
7557 return true;
7558 }
7559 }
7560
7561 if (Previous.empty()) return false;
7562
7563 NamedDecl *Target = Orig;
7564 if (isa<UsingShadowDecl>(Target))
7565 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7566
John McCalla17e83e2009-12-11 02:33:26 +00007567 // If the target happens to be one of the previous declarations, we
7568 // don't have a conflict.
7569 //
7570 // FIXME: but we might be increasing its access, in which case we
7571 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007572 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007573 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007574 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7575 I != E; ++I) {
7576 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007577 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7578 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7579 PrevShadow = Shadow;
7580 FoundEquivalentDecl = true;
7581 }
John McCalla17e83e2009-12-11 02:33:26 +00007582
7583 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7584 }
7585
Richard Smithfd8634a2013-10-23 02:17:46 +00007586 if (FoundEquivalentDecl)
7587 return false;
7588
Alp Tokera2794f92014-01-22 07:29:52 +00007589 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007590 NamedDecl *OldDecl = nullptr;
7591 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7592 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007593 case Ovl_Overload:
7594 return false;
7595
7596 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007597 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007598 break;
Richard Smith18819302014-02-06 01:31:33 +00007599
John McCall84d87672009-12-10 09:41:52 +00007600 // We found a decl with the exact signature.
7601 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007602 // If we're in a record, we want to hide the target, so we
7603 // return true (without a diagnostic) to tell the caller not to
7604 // build a shadow decl.
7605 if (CurContext->isRecord())
7606 return true;
7607
7608 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007609 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007610 break;
7611 }
7612
7613 Diag(Target->getLocation(), diag::note_using_decl_target);
7614 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7615 return true;
7616 }
7617
7618 // Target is not a function.
7619
John McCall84d87672009-12-10 09:41:52 +00007620 if (isa<TagDecl>(Target)) {
7621 // No conflict between a tag and a non-tag.
7622 if (!Tag) return false;
7623
John McCalle29c5cd2009-12-10 19:51:03 +00007624 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007625 Diag(Target->getLocation(), diag::note_using_decl_target);
7626 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7627 return true;
7628 }
7629
7630 // No conflict between a tag and a non-tag.
7631 if (!NonTag) return false;
7632
John McCalle29c5cd2009-12-10 19:51:03 +00007633 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007634 Diag(Target->getLocation(), diag::note_using_decl_target);
7635 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7636 return true;
7637}
7638
John McCall3f746822009-11-17 05:59:44 +00007639/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007640UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007641 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007642 NamedDecl *Orig,
7643 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007644
7645 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007646 NamedDecl *Target = Orig;
7647 if (isa<UsingShadowDecl>(Target)) {
7648 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7649 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007650 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007651
John McCall3f746822009-11-17 05:59:44 +00007652 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007653 = UsingShadowDecl::Create(Context, CurContext,
7654 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007655 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007656
Douglas Gregor457104e2010-09-29 04:25:11 +00007657 Shadow->setAccess(UD->getAccess());
7658 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7659 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007660
7661 Shadow->setPreviousDecl(PrevDecl);
7662
John McCall3f746822009-11-17 05:59:44 +00007663 if (S)
John McCall3969e302009-12-08 07:46:18 +00007664 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007665 else
John McCall3969e302009-12-08 07:46:18 +00007666 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007667
John McCall3969e302009-12-08 07:46:18 +00007668
John McCall84d87672009-12-10 09:41:52 +00007669 return Shadow;
7670}
John McCall3969e302009-12-08 07:46:18 +00007671
John McCall84d87672009-12-10 09:41:52 +00007672/// Hides a using shadow declaration. This is required by the current
7673/// using-decl implementation when a resolvable using declaration in a
7674/// class is followed by a declaration which would hide or override
7675/// one or more of the using decl's targets; for example:
7676///
7677/// struct Base { void foo(int); };
7678/// struct Derived : Base {
7679/// using Base::foo;
7680/// void foo(int);
7681/// };
7682///
7683/// The governing language is C++03 [namespace.udecl]p12:
7684///
7685/// When a using-declaration brings names from a base class into a
7686/// derived class scope, member functions in the derived class
7687/// override and/or hide member functions with the same name and
7688/// parameter types in a base class (rather than conflicting).
7689///
7690/// There are two ways to implement this:
7691/// (1) optimistically create shadow decls when they're not hidden
7692/// by existing declarations, or
7693/// (2) don't create any shadow decls (or at least don't make them
7694/// visible) until we've fully parsed/instantiated the class.
7695/// The problem with (1) is that we might have to retroactively remove
7696/// a shadow decl, which requires several O(n) operations because the
7697/// decl structures are (very reasonably) not designed for removal.
7698/// (2) avoids this but is very fiddly and phase-dependent.
7699void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007700 if (Shadow->getDeclName().getNameKind() ==
7701 DeclarationName::CXXConversionFunctionName)
7702 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7703
John McCall84d87672009-12-10 09:41:52 +00007704 // Remove it from the DeclContext...
7705 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007706
John McCall84d87672009-12-10 09:41:52 +00007707 // ...and the scope, if applicable...
7708 if (S) {
John McCall48871652010-08-21 09:40:31 +00007709 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007710 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007711 }
7712
John McCall84d87672009-12-10 09:41:52 +00007713 // ...and the using decl.
7714 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7715
7716 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007717 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007718}
7719
Richard Smith09d5b3a2014-05-01 00:35:04 +00007720/// Find the base specifier for a base class with the given type.
7721static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7722 QualType DesiredBase,
7723 bool &AnyDependentBases) {
7724 // Check whether the named type is a direct base class.
7725 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7726 for (auto &Base : Derived->bases()) {
7727 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7728 if (CanonicalDesiredBase == BaseType)
7729 return &Base;
7730 if (BaseType->isDependentType())
7731 AnyDependentBases = true;
7732 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007733 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007734}
7735
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007736namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007737class UsingValidatorCCC : public CorrectionCandidateCallback {
7738public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007739 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007740 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007741 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007742 IsInstantiation(IsInstantiation), OldNNS(NNS),
7743 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007744
Craig Toppera798a9d2014-03-02 09:32:10 +00007745 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007746 NamedDecl *ND = Candidate.getCorrectionDecl();
7747
7748 // Keywords are not valid here.
7749 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007750 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007751
7752 // Completely unqualified names are invalid for a 'using' declaration.
7753 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7754 return false;
7755
Richard Smith09d5b3a2014-05-01 00:35:04 +00007756 if (RequireMemberOf) {
7757 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7758 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7759 // No-one ever wants a using-declaration to name an injected-class-name
7760 // of a base class, unless they're declaring an inheriting constructor.
7761 ASTContext &Ctx = ND->getASTContext();
7762 if (!Ctx.getLangOpts().CPlusPlus11)
7763 return false;
7764 QualType FoundType = Ctx.getRecordType(FoundRecord);
7765
7766 // Check that the injected-class-name is named as a member of its own
7767 // type; we don't want to suggest 'using Derived::Base;', since that
7768 // means something else.
7769 NestedNameSpecifier *Specifier =
7770 Candidate.WillReplaceSpecifier()
7771 ? Candidate.getCorrectionSpecifier()
7772 : OldNNS;
7773 if (!Specifier->getAsType() ||
7774 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7775 return false;
7776
7777 // Check that this inheriting constructor declaration actually names a
7778 // direct base class of the current class.
7779 bool AnyDependentBases = false;
7780 if (!findDirectBaseWithType(RequireMemberOf,
7781 Ctx.getRecordType(FoundRecord),
7782 AnyDependentBases) &&
7783 !AnyDependentBases)
7784 return false;
7785 } else {
7786 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7787 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7788 return false;
7789
7790 // FIXME: Check that the base class member is accessible?
7791 }
7792 }
7793
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007794 if (isa<TypeDecl>(ND))
7795 return HasTypenameKeyword || !IsInstantiation;
7796
7797 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007798 }
7799
7800private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007801 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007802 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007803 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007804 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007805};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007806} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007807
John McCalle61f2ba2009-11-18 02:36:19 +00007808/// Builds a using declaration.
7809///
7810/// \param IsInstantiation - Whether this call arises from an
7811/// instantiation of an unresolved using declaration. We treat
7812/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007813NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7814 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007815 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007816 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007817 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007818 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007819 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007820 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007821 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007822 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007823 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007824
Anders Carlssonf038fc22009-08-28 05:49:21 +00007825 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007826
Anders Carlsson59140b32009-08-28 03:16:11 +00007827 if (SS.isEmpty()) {
7828 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007829 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007830 }
Mike Stump11289f42009-09-09 15:08:12 +00007831
John McCall84d87672009-12-10 09:41:52 +00007832 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007833 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007834 ForRedeclaration);
7835 Previous.setHideTags(false);
7836 if (S) {
7837 LookupName(Previous, S);
7838
7839 // It is really dumb that we have to do this.
7840 LookupResult::Filter F = Previous.makeFilter();
7841 while (F.hasNext()) {
7842 NamedDecl *D = F.next();
7843 if (!isDeclInScope(D, CurContext, S))
7844 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007845 // If we found a local extern declaration that's not ordinarily visible,
7846 // and this declaration is being added to a non-block scope, ignore it.
7847 // We're only checking for scope conflicts here, not also for violations
7848 // of the linkage rules.
7849 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7850 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7851 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007852 }
7853 F.done();
7854 } else {
7855 assert(IsInstantiation && "no scope in non-instantiation");
7856 assert(CurContext->isRecord() && "scope not record in instantiation");
7857 LookupQualifiedName(Previous, CurContext);
7858 }
7859
John McCall84d87672009-12-10 09:41:52 +00007860 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007861 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7862 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007863 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007864
7865 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007866 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007867 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007868
John McCall84c16cf2009-11-12 03:15:40 +00007869 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007870 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007871 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007872 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007873 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007874 // FIXME: not all declaration name kinds are legal here
7875 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7876 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007877 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007878 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007879 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007880 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7881 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007882 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007883 D->setAccess(AS);
7884 CurContext->addDecl(D);
7885 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007886 }
John McCallb96ec562009-12-04 22:46:56 +00007887
Richard Smith09d5b3a2014-05-01 00:35:04 +00007888 auto Build = [&](bool Invalid) {
7889 UsingDecl *UD =
7890 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7891 HasTypenameKeyword);
7892 UD->setAccess(AS);
7893 CurContext->addDecl(UD);
7894 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007895 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007896 };
7897 auto BuildInvalid = [&]{ return Build(true); };
7898 auto BuildValid = [&]{ return Build(false); };
7899
7900 if (RequireCompleteDeclContext(SS, LookupContext))
7901 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007902
Richard Smith23d55872012-04-02 01:30:27 +00007903 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007904 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007905 UsingDecl *UD = BuildValid();
7906 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007907 return UD;
7908 }
7909
7910 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007911
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007912 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007913
John McCall3969e302009-12-08 07:46:18 +00007914 // Unlike most lookups, we don't always want to hide tag
7915 // declarations: tag names are visible through the using declaration
7916 // even if hidden by ordinary names, *except* in a dependent context
7917 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007918 if (!IsInstantiation)
7919 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007920
John McCall5dadb652012-04-07 03:04:20 +00007921 // For the purposes of this lookup, we have a base object type
7922 // equal to that of the current context.
7923 if (CurContext->isRecord()) {
7924 R.setBaseObjectType(
7925 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7926 }
7927
John McCall27b18f82009-11-17 02:14:36 +00007928 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007929
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007930 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007931 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007932 if (TypoCorrection Corrected = CorrectTypo(
7933 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
7934 llvm::make_unique<UsingValidatorCCC>(
7935 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7936 dyn_cast<CXXRecordDecl>(CurContext)),
7937 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007938 // We reject any correction for which ND would be NULL.
7939 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007940
Richard Smithf9b15102013-08-17 00:46:16 +00007941 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007942 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007943 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7944 << NameInfo.getName() << LookupContext << 0
7945 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007946
7947 // If we corrected to an inheriting constructor, handle it as one.
7948 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7949 if (RD && RD->isInjectedClassName()) {
7950 // Fix up the information we'll use to build the using declaration.
7951 if (Corrected.WillReplaceSpecifier()) {
7952 NestedNameSpecifierLocBuilder Builder;
7953 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7954 QualifierLoc.getSourceRange());
7955 QualifierLoc = Builder.getWithLocInContext(Context);
7956 }
7957
7958 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7959 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007960 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007961
7962 // Build it and process it as an inheriting constructor.
7963 UsingDecl *UD = BuildValid();
7964 CheckInheritingConstructorUsingDecl(UD);
7965 return UD;
7966 }
7967
7968 // FIXME: Pick up all the declarations if we found an overloaded function.
7969 R.setLookupName(Corrected.getCorrection());
7970 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007971 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007972 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007973 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007974 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007975 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007976 }
7977
Richard Smith09d5b3a2014-05-01 00:35:04 +00007978 if (R.isAmbiguous())
7979 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007980
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007981 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007982 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007983 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007984 Diag(IdentLoc, diag::err_using_typename_non_type);
7985 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7986 Diag((*I)->getUnderlyingDecl()->getLocation(),
7987 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007988 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007989 }
7990 } else {
7991 // If we asked for a non-typename and we got a type, error out,
7992 // but only if this is an instantiation of an unresolved using
7993 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007994 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007995 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7996 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007997 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007998 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007999 }
8000
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008001 // C++0x N2914 [namespace.udecl]p6:
8002 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008003 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008004 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8005 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008006 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008007 }
Mike Stump11289f42009-09-09 15:08:12 +00008008
Richard Smith09d5b3a2014-05-01 00:35:04 +00008009 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008010 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008011 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008012 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8013 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008014 }
John McCall3f746822009-11-17 05:59:44 +00008015
8016 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008017}
8018
Sebastian Redl08905022011-02-05 19:23:19 +00008019/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008020bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008021 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008022
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008023 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008024 assert(SourceType &&
8025 "Using decl naming constructor doesn't have type in scope spec.");
8026 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8027
8028 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008029 bool AnyDependentBases = false;
8030 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8031 AnyDependentBases);
8032 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008033 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008034 diag::err_using_decl_constructor_not_in_direct_base)
8035 << UD->getNameInfo().getSourceRange()
8036 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008037 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008038 return true;
8039 }
8040
Richard Smith09d5b3a2014-05-01 00:35:04 +00008041 if (Base)
8042 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008043
8044 return false;
8045}
8046
John McCall84d87672009-12-10 09:41:52 +00008047/// Checks that the given using declaration is not an invalid
8048/// redeclaration. Note that this is checking only for the using decl
8049/// itself, not for any ill-formedness among the UsingShadowDecls.
8050bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008051 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008052 const CXXScopeSpec &SS,
8053 SourceLocation NameLoc,
8054 const LookupResult &Prev) {
8055 // C++03 [namespace.udecl]p8:
8056 // C++0x [namespace.udecl]p10:
8057 // A using-declaration is a declaration and can therefore be used
8058 // repeatedly where (and only where) multiple declarations are
8059 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008060 //
John McCall032092f2010-11-29 18:01:58 +00008061 // That's in non-member contexts.
8062 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008063 return false;
8064
Aaron Ballman4a979672014-01-03 13:56:08 +00008065 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008066
8067 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8068 NamedDecl *D = *I;
8069
8070 bool DTypename;
8071 NestedNameSpecifier *DQual;
8072 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008073 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008074 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008075 } else if (UnresolvedUsingValueDecl *UD
8076 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8077 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008078 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008079 } else if (UnresolvedUsingTypenameDecl *UD
8080 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8081 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008082 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008083 } else continue;
8084
8085 // using decls differ if one says 'typename' and the other doesn't.
8086 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008087 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008088
8089 // using decls differ if they name different scopes (but note that
8090 // template instantiation can cause this check to trigger when it
8091 // didn't before instantiation).
8092 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8093 Context.getCanonicalNestedNameSpecifier(DQual))
8094 continue;
8095
8096 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008097 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008098 return true;
8099 }
8100
8101 return false;
8102}
8103
John McCall3969e302009-12-08 07:46:18 +00008104
John McCallb96ec562009-12-04 22:46:56 +00008105/// Checks that the given nested-name qualifier used in a using decl
8106/// in the current context is appropriately related to the current
8107/// scope. If an error is found, diagnoses it and returns true.
8108bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8109 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008110 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008111 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008112 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008113
John McCall3969e302009-12-08 07:46:18 +00008114 if (!CurContext->isRecord()) {
8115 // C++03 [namespace.udecl]p3:
8116 // C++0x [namespace.udecl]p8:
8117 // A using-declaration for a class member shall be a member-declaration.
8118
8119 // If we weren't able to compute a valid scope, it must be a
8120 // dependent class scope.
8121 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00008122 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
8123 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008124 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008125
John McCall3969e302009-12-08 07:46:18 +00008126 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8127 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008128
8129 // If we have a complete, non-dependent source type, try to suggest a
8130 // way to get the same effect.
8131 if (!RD)
8132 return true;
8133
8134 // Find what this using-declaration was referring to.
8135 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8136 R.setHideTags(false);
8137 R.suppressDiagnostics();
8138 LookupQualifiedName(R, RD);
8139
8140 if (R.getAsSingle<TypeDecl>()) {
8141 if (getLangOpts().CPlusPlus11) {
8142 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8143 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8144 << 0 // alias declaration
8145 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8146 NameInfo.getName().getAsString() +
8147 " = ");
8148 } else {
8149 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8150 SourceLocation InsertLoc =
8151 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8152 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8153 << 1 // typedef declaration
8154 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8155 << FixItHint::CreateInsertion(
8156 InsertLoc, " " + NameInfo.getName().getAsString());
8157 }
8158 } else if (R.getAsSingle<VarDecl>()) {
8159 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8160 // repeating the type of the static data member here.
8161 FixItHint FixIt;
8162 if (getLangOpts().CPlusPlus11) {
8163 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8164 FixIt = FixItHint::CreateReplacement(
8165 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8166 }
8167
8168 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8169 << 2 // reference declaration
8170 << FixIt;
8171 }
John McCall3969e302009-12-08 07:46:18 +00008172 return true;
8173 }
8174
8175 // Otherwise, everything is known to be fine.
8176 return false;
8177 }
8178
8179 // The current scope is a record.
8180
8181 // If the named context is dependent, we can't decide much.
8182 if (!NamedContext) {
8183 // FIXME: in C++0x, we can diagnose if we can prove that the
8184 // nested-name-specifier does not refer to a base class, which is
8185 // still possible in some cases.
8186
8187 // Otherwise we have to conservatively report that things might be
8188 // okay.
8189 return false;
8190 }
8191
8192 if (!NamedContext->isRecord()) {
8193 // Ideally this would point at the last name in the specifier,
8194 // but we don't have that level of source info.
8195 Diag(SS.getRange().getBegin(),
8196 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008197 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008198 return true;
8199 }
8200
Douglas Gregor7c842292010-12-21 07:41:49 +00008201 if (!NamedContext->isDependentContext() &&
8202 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8203 return true;
8204
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008205 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008206 // C++0x [namespace.udecl]p3:
8207 // In a using-declaration used as a member-declaration, the
8208 // nested-name-specifier shall name a base class of the class
8209 // being defined.
8210
8211 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8212 cast<CXXRecordDecl>(NamedContext))) {
8213 if (CurContext == NamedContext) {
8214 Diag(NameLoc,
8215 diag::err_using_decl_nested_name_specifier_is_current_class)
8216 << SS.getRange();
8217 return true;
8218 }
8219
8220 Diag(SS.getRange().getBegin(),
8221 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008222 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008223 << cast<CXXRecordDecl>(CurContext)
8224 << SS.getRange();
8225 return true;
8226 }
8227
8228 return false;
8229 }
8230
8231 // C++03 [namespace.udecl]p4:
8232 // A using-declaration used as a member-declaration shall refer
8233 // to a member of a base class of the class being defined [etc.].
8234
8235 // Salient point: SS doesn't have to name a base class as long as
8236 // lookup only finds members from base classes. Therefore we can
8237 // diagnose here only if we can prove that that can't happen,
8238 // i.e. if the class hierarchies provably don't intersect.
8239
8240 // TODO: it would be nice if "definitely valid" results were cached
8241 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8242 // need to be repeated.
8243
8244 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008245 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008246
8247 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8248 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8249 Data->Bases.insert(Base);
8250 return true;
8251 }
8252
8253 bool hasDependentBases(const CXXRecordDecl *Class) {
8254 return !Class->forallBases(collect, this);
8255 }
8256
8257 /// Returns true if the base is dependent or is one of the
8258 /// accumulated base classes.
8259 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8260 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8261 return !Data->Bases.count(Base);
8262 }
8263
8264 bool mightShareBases(const CXXRecordDecl *Class) {
8265 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8266 }
8267 };
8268
8269 UserData Data;
8270
8271 // Returns false if we find a dependent base.
8272 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8273 return false;
8274
8275 // Returns false if the class has a dependent base or if it or one
8276 // of its bases is present in the base set of the current context.
8277 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8278 return false;
8279
8280 Diag(SS.getRange().getBegin(),
8281 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008282 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008283 << cast<CXXRecordDecl>(CurContext)
8284 << SS.getRange();
8285
8286 return true;
John McCallb96ec562009-12-04 22:46:56 +00008287}
8288
Richard Smithdda56e42011-04-15 14:24:37 +00008289Decl *Sema::ActOnAliasDeclaration(Scope *S,
8290 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008291 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008292 SourceLocation UsingLoc,
8293 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008294 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008295 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008296 // Skip up to the relevant declaration scope.
8297 while (S->getFlags() & Scope::TemplateParamScope)
8298 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008299 assert((S->getFlags() & Scope::DeclScope) &&
8300 "got alias-declaration outside of declaration scope");
8301
8302 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008303 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008304
8305 bool Invalid = false;
8306 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008307 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008308 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008309
8310 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008311 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008312
8313 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008314 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008315 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008316 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8317 TInfo->getTypeLoc().getBeginLoc());
8318 }
Richard Smithdda56e42011-04-15 14:24:37 +00008319
8320 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8321 LookupName(Previous, S);
8322
8323 // Warn about shadowing the name of a template parameter.
8324 if (Previous.isSingleResult() &&
8325 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008326 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008327 Previous.clear();
8328 }
8329
8330 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8331 "name in alias declaration must be an identifier");
8332 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8333 Name.StartLocation,
8334 Name.Identifier, TInfo);
8335
8336 NewTD->setAccess(AS);
8337
8338 if (Invalid)
8339 NewTD->setInvalidDecl();
8340
Richard Smith54ecd982013-02-20 19:22:51 +00008341 ProcessDeclAttributeList(S, NewTD, AttrList);
8342
Richard Smith3f1b5d02011-05-05 21:57:07 +00008343 CheckTypedefForVariablyModifiedType(S, NewTD);
8344 Invalid |= NewTD->isInvalidDecl();
8345
Richard Smithdda56e42011-04-15 14:24:37 +00008346 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008347
8348 NamedDecl *NewND;
8349 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008350 TypeAliasTemplateDecl *OldDecl = nullptr;
8351 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008352
8353 if (TemplateParamLists.size() != 1) {
8354 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008355 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8356 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008357 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008358 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008359
8360 // Only consider previous declarations in the same scope.
8361 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8362 /*ExplicitInstantiationOrSpecialization*/false);
8363 if (!Previous.empty()) {
8364 Redeclaration = true;
8365
8366 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8367 if (!OldDecl && !Invalid) {
8368 Diag(UsingLoc, diag::err_redefinition_different_kind)
8369 << Name.Identifier;
8370
8371 NamedDecl *OldD = Previous.getRepresentativeDecl();
8372 if (OldD->getLocation().isValid())
8373 Diag(OldD->getLocation(), diag::note_previous_definition);
8374
8375 Invalid = true;
8376 }
8377
8378 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8379 if (TemplateParameterListsAreEqual(TemplateParams,
8380 OldDecl->getTemplateParameters(),
8381 /*Complain=*/true,
8382 TPL_TemplateMatch))
8383 OldTemplateParams = OldDecl->getTemplateParameters();
8384 else
8385 Invalid = true;
8386
8387 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8388 if (!Invalid &&
8389 !Context.hasSameType(OldTD->getUnderlyingType(),
8390 NewTD->getUnderlyingType())) {
8391 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8392 // but we can't reasonably accept it.
8393 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8394 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8395 if (OldTD->getLocation().isValid())
8396 Diag(OldTD->getLocation(), diag::note_previous_definition);
8397 Invalid = true;
8398 }
8399 }
8400 }
8401
8402 // Merge any previous default template arguments into our parameters,
8403 // and check the parameter list.
8404 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8405 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008406 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008407
8408 TypeAliasTemplateDecl *NewDecl =
8409 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8410 Name.Identifier, TemplateParams,
8411 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008412 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008413
8414 NewDecl->setAccess(AS);
8415
8416 if (Invalid)
8417 NewDecl->setInvalidDecl();
8418 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008419 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008420
8421 NewND = NewDecl;
8422 } else {
8423 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8424 NewND = NewTD;
8425 }
Richard Smithdda56e42011-04-15 14:24:37 +00008426
8427 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008428 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008429
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008430 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008431 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008432}
8433
Richard Smithf4634362014-09-03 23:11:22 +00008434Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8435 SourceLocation AliasLoc,
8436 IdentifierInfo *Alias, CXXScopeSpec &SS,
8437 SourceLocation IdentLoc,
8438 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008439
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008440 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008441 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8442 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008443
John McCall27b18f82009-11-17 02:14:36 +00008444 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008445 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008446
John McCall9f3059a2009-10-09 21:13:30 +00008447 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008448 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008449 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008450 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008451 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008452 }
Richard Smithf4634362014-09-03 23:11:22 +00008453 assert(!R.isAmbiguous() && !R.empty());
8454
8455 // Check if we have a previous declaration with the same name.
8456 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8457 ForRedeclaration);
8458 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8459 PrevDecl = nullptr;
8460
8461 if (PrevDecl) {
8462 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8463 // We already have an alias with the same name that points to the same
8464 // namespace; check that it matches.
8465 if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) {
8466 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8467 << Alias;
8468 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8469 << AD->getNamespace();
8470 return nullptr;
8471 }
8472 } else {
8473 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8474 ? diag::err_redefinition
8475 : diag::err_redefinition_different_kind;
8476 Diag(AliasLoc, DiagID) << Alias;
8477 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8478 return nullptr;
8479 }
8480 }
Mike Stump11289f42009-09-09 15:08:12 +00008481
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008482 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008483 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008484 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008485 IdentLoc, R.getFoundDecl());
Richard Smithf4634362014-09-03 23:11:22 +00008486 if (PrevDecl)
8487 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008488
John McCalld8d0d432010-02-16 06:53:13 +00008489 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008490 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008491}
8492
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008493Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008494Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8495 CXXMethodDecl *MD) {
8496 CXXRecordDecl *ClassDecl = MD->getParent();
8497
Douglas Gregor6d880b12010-07-01 22:31:05 +00008498 // C++ [except.spec]p14:
8499 // An implicitly declared special member function (Clause 12) shall have an
8500 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008501 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008502 if (ClassDecl->isInvalidDecl())
8503 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008504
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008505 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008506 for (const auto &B : ClassDecl->bases()) {
8507 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008508 continue;
8509
Aaron Ballman574705e2014-03-13 15:41:46 +00008510 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008511 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008512 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8513 // If this is a deleted function, add it anyway. This might be conformant
8514 // with the standard. This might not. I'm not sure. It might not matter.
8515 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008516 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008517 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008518 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008519
8520 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008521 for (const auto &B : ClassDecl->vbases()) {
8522 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008523 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008524 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8525 // If this is a deleted function, add it anyway. This might be conformant
8526 // with the standard. This might not. I'm not sure. It might not matter.
8527 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008528 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008529 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008530 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008531
8532 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008533 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008534 if (F->hasInClassInitializer()) {
8535 if (Expr *E = F->getInClassInitializer())
8536 ExceptSpec.CalledExpr(E);
8537 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008538 // DR1351:
8539 // If the brace-or-equal-initializer of a non-static data member
8540 // invokes a defaulted default constructor of its class or of an
8541 // enclosing class in a potentially evaluated subexpression, the
8542 // program is ill-formed.
8543 //
8544 // This resolution is unworkable: the exception specification of the
8545 // default constructor can be needed in an unevaluated context, in
8546 // particular, in the operand of a noexcept-expression, and we can be
8547 // unable to compute an exception specification for an enclosed class.
8548 //
8549 // We do not allow an in-class initializer to require the evaluation
8550 // of the exception specification for any in-class initializer whose
8551 // definition is not lexically complete.
8552 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008553 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008554 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008555 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8556 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8557 // If this is a deleted function, add it anyway. This might be conformant
8558 // with the standard. This might not. I'm not sure. It might not matter.
8559 // In particular, the problem is that this function never gets called. It
8560 // might just be ill-formed because this function attempts to refer to
8561 // a deleted function here.
8562 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008563 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008564 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008565 }
John McCalldb40c7f2010-12-14 08:05:40 +00008566
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008567 return ExceptSpec;
8568}
8569
Richard Smithc2bc61b2013-03-18 21:12:30 +00008570Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008571Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8572 CXXRecordDecl *ClassDecl = CD->getParent();
8573
8574 // C++ [except.spec]p14:
8575 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008576 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008577 if (ClassDecl->isInvalidDecl())
8578 return ExceptSpec;
8579
8580 // Inherited constructor.
8581 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8582 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8583 // FIXME: Copying or moving the parameters could add extra exceptions to the
8584 // set, as could the default arguments for the inherited constructor. This
8585 // will be addressed when we implement the resolution of core issue 1351.
8586 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8587
8588 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008589 for (const auto &B : ClassDecl->bases()) {
8590 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008591 continue;
8592
Aaron Ballman574705e2014-03-13 15:41:46 +00008593 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008594 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8595 if (BaseClassDecl == InheritedDecl)
8596 continue;
8597 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8598 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008599 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008600 }
8601 }
8602
8603 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008604 for (const auto &B : ClassDecl->vbases()) {
8605 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8607 if (BaseClassDecl == InheritedDecl)
8608 continue;
8609 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8610 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008611 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008612 }
8613 }
8614
8615 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008616 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008617 if (F->hasInClassInitializer()) {
8618 if (Expr *E = F->getInClassInitializer())
8619 ExceptSpec.CalledExpr(E);
8620 else if (!F->isInvalidDecl())
8621 Diag(CD->getLocation(),
8622 diag::err_in_class_initializer_references_def_ctor) << CD;
8623 } else if (const RecordType *RecordTy
8624 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8625 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8626 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8627 if (Constructor)
8628 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8629 }
8630 }
8631
Richard Smithc2bc61b2013-03-18 21:12:30 +00008632 return ExceptSpec;
8633}
8634
Richard Smith8bf22e52012-11-29 01:34:07 +00008635namespace {
8636/// RAII object to register a special member as being currently declared.
8637struct DeclaringSpecialMember {
8638 Sema &S;
8639 Sema::SpecialMemberDecl D;
8640 bool WasAlreadyBeingDeclared;
8641
8642 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8643 : S(S), D(RD, CSM) {
8644 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8645 if (WasAlreadyBeingDeclared)
8646 // This almost never happens, but if it does, ensure that our cache
8647 // doesn't contain a stale result.
8648 S.SpecialMemberCache.clear();
8649
8650 // FIXME: Register a note to be produced if we encounter an error while
8651 // declaring the special member.
8652 }
8653 ~DeclaringSpecialMember() {
8654 if (!WasAlreadyBeingDeclared)
8655 S.SpecialMembersBeingDeclared.erase(D);
8656 }
8657
8658 /// \brief Are we already trying to declare this special member?
8659 bool isAlreadyBeingDeclared() const {
8660 return WasAlreadyBeingDeclared;
8661 }
8662};
8663}
8664
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008665CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8666 CXXRecordDecl *ClassDecl) {
8667 // C++ [class.ctor]p5:
8668 // A default constructor for a class X is a constructor of class X
8669 // that can be called without an argument. If there is no
8670 // user-declared constructor for class X, a default constructor is
8671 // implicitly declared. An implicitly-declared default constructor
8672 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008673 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008674 "Should not build implicit default constructor!");
8675
Richard Smith8bf22e52012-11-29 01:34:07 +00008676 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8677 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008678 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008679
Richard Smithb5800092012-06-10 05:43:50 +00008680 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8681 CXXDefaultConstructor,
8682 false);
8683
Douglas Gregor6d880b12010-07-01 22:31:05 +00008684 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008685 CanQualType ClassType
8686 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008687 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008688 DeclarationName Name
8689 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008690 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008691 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008692 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8693 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8694 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008695 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008696 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008697
8698 if (getLangOpts().CUDA) {
8699 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8700 DefaultCon,
8701 /* ConstRHS */ false,
8702 /* Diagnose */ false);
8703 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008704
8705 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008706 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008707 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008708
Richard Smith6b02d462012-12-08 08:32:28 +00008709 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8710 // constructors is easy to compute.
8711 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8712
8713 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008714 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008715
Douglas Gregor9672f922010-07-03 00:47:00 +00008716 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008717 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008718
Douglas Gregor0be31a22010-07-02 17:43:08 +00008719 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008720 PushOnScopeChains(DefaultCon, S, false);
8721 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008722
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008723 return DefaultCon;
8724}
8725
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008726void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8727 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008728 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008729 !Constructor->doesThisDeclarationHaveABody() &&
8730 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008731 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008732
Anders Carlsson423f5d82010-04-23 16:04:08 +00008733 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008734 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008735
Eli Friedmaneaf34142012-10-18 20:14:08 +00008736 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008737 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008738 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008739 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008740 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008741 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008742 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008743 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008744 }
Douglas Gregor73193272010-09-20 16:48:21 +00008745
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008746 // The exception specification is needed because we are defining the
8747 // function.
8748 ResolveExceptionSpec(CurrentLocation,
8749 Constructor->getType()->castAs<FunctionProtoType>());
8750
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008751 SourceLocation Loc = Constructor->getLocEnd().isValid()
8752 ? Constructor->getLocEnd()
8753 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008754 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008755
Eli Friedman276dd182013-09-05 00:02:25 +00008756 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008757 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008758
8759 if (ASTMutationListener *L = getASTMutationListener()) {
8760 L->CompletedImplicitDefinition(Constructor);
8761 }
Richard Trieuef64e942013-10-25 00:56:00 +00008762
8763 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008764}
8765
Richard Smith938f40b2011-06-11 17:19:42 +00008766void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008767 // Perform any delayed checks on exception specifications.
8768 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008769}
8770
Richard Smith185be182013-04-10 05:48:59 +00008771namespace {
8772/// Information on inheriting constructors to declare.
8773class InheritingConstructorInfo {
8774public:
8775 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8776 : SemaRef(SemaRef), Derived(Derived) {
8777 // Mark the constructors that we already have in the derived class.
8778 //
8779 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8780 // unless there is a user-declared constructor with the same signature in
8781 // the class where the using-declaration appears.
8782 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8783 }
8784
8785 void inheritAll(CXXRecordDecl *RD) {
8786 visitAll(RD, &InheritingConstructorInfo::inherit);
8787 }
8788
8789private:
8790 /// Information about an inheriting constructor.
8791 struct InheritingConstructor {
8792 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008793 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008794
8795 /// If \c true, a constructor with this signature is already declared
8796 /// in the derived class.
8797 bool DeclaredInDerived;
8798
8799 /// The constructor which is inherited.
8800 const CXXConstructorDecl *BaseCtor;
8801
8802 /// The derived constructor we declared.
8803 CXXConstructorDecl *DerivedCtor;
8804 };
8805
8806 /// Inheriting constructors with a given canonical type. There can be at
8807 /// most one such non-template constructor, and any number of templated
8808 /// constructors.
8809 struct InheritingConstructorsForType {
8810 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008811 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8812 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008813
8814 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8815 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8816 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8817 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8818 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8819 false, S.TPL_TemplateMatch))
8820 return Templates[I].second;
8821 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8822 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008823 }
Richard Smith185be182013-04-10 05:48:59 +00008824
8825 return NonTemplate;
8826 }
8827 };
8828
8829 /// Get or create the inheriting constructor record for a constructor.
8830 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8831 QualType CtorType) {
8832 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8833 .getEntry(SemaRef, Ctor);
8834 }
8835
8836 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8837
8838 /// Process all constructors for a class.
8839 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008840 for (const auto *Ctor : RD->ctors())
8841 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008842 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8843 I(RD->decls_begin()), E(RD->decls_end());
8844 I != E; ++I) {
8845 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8846 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8847 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008848 }
8849 }
Richard Smith185be182013-04-10 05:48:59 +00008850
8851 /// Note that a constructor (or constructor template) was declared in Derived.
8852 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8853 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8854 }
8855
8856 /// Inherit a single constructor.
8857 void inherit(const CXXConstructorDecl *Ctor) {
8858 const FunctionProtoType *CtorType =
8859 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00008860 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00008861 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8862
8863 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8864
8865 // Core issue (no number yet): the ellipsis is always discarded.
8866 if (EPI.Variadic) {
8867 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8868 SemaRef.Diag(Ctor->getLocation(),
8869 diag::note_using_decl_constructor_ellipsis);
8870 EPI.Variadic = false;
8871 }
8872
8873 // Declare a constructor for each number of parameters.
8874 //
8875 // C++11 [class.inhctor]p1:
8876 // The candidate set of inherited constructors from the class X named in
8877 // the using-declaration consists of [... modulo defects ...] for each
8878 // constructor or constructor template of X, the set of constructors or
8879 // constructor templates that results from omitting any ellipsis parameter
8880 // specification and successively omitting parameters with a default
8881 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008882 unsigned MinParams = minParamsToInherit(Ctor);
8883 unsigned Params = Ctor->getNumParams();
8884 if (Params >= MinParams) {
8885 do
8886 declareCtor(UsingLoc, Ctor,
8887 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008888 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008889 while (Params > MinParams &&
8890 Ctor->getParamDecl(--Params)->hasDefaultArg());
8891 }
Richard Smith185be182013-04-10 05:48:59 +00008892 }
8893
8894 /// Find the using-declaration which specified that we should inherit the
8895 /// constructors of \p Base.
8896 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8897 // No fancy lookup required; just look for the base constructor name
8898 // directly within the derived class.
8899 ASTContext &Context = SemaRef.Context;
8900 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8901 Context.getCanonicalType(Context.getRecordType(Base)));
8902 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8903 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8904 }
8905
8906 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8907 // C++11 [class.inhctor]p3:
8908 // [F]or each constructor template in the candidate set of inherited
8909 // constructors, a constructor template is implicitly declared
8910 if (Ctor->getDescribedFunctionTemplate())
8911 return 0;
8912
8913 // For each non-template constructor in the candidate set of inherited
8914 // constructors other than a constructor having no parameters or a
8915 // copy/move constructor having a single parameter, a constructor is
8916 // implicitly declared [...]
8917 if (Ctor->getNumParams() == 0)
8918 return 1;
8919 if (Ctor->isCopyOrMoveConstructor())
8920 return 2;
8921
8922 // Per discussion on core reflector, never inherit a constructor which
8923 // would become a default, copy, or move constructor of Derived either.
8924 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8925 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8926 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8927 }
8928
8929 /// Declare a single inheriting constructor, inheriting the specified
8930 /// constructor, with the given type.
8931 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8932 QualType DerivedType) {
8933 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8934
8935 // C++11 [class.inhctor]p3:
8936 // ... a constructor is implicitly declared with the same constructor
8937 // characteristics unless there is a user-declared constructor with
8938 // the same signature in the class where the using-declaration appears
8939 if (Entry.DeclaredInDerived)
8940 return;
8941
8942 // C++11 [class.inhctor]p7:
8943 // If two using-declarations declare inheriting constructors with the
8944 // same signature, the program is ill-formed
8945 if (Entry.DerivedCtor) {
8946 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8947 // Only diagnose this once per constructor.
8948 if (Entry.DerivedCtor->isInvalidDecl())
8949 return;
8950 Entry.DerivedCtor->setInvalidDecl();
8951
8952 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8953 SemaRef.Diag(BaseCtor->getLocation(),
8954 diag::note_using_decl_constructor_conflict_current_ctor);
8955 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8956 diag::note_using_decl_constructor_conflict_previous_ctor);
8957 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8958 diag::note_using_decl_constructor_conflict_previous_using);
8959 } else {
8960 // Core issue (no number): if the same inheriting constructor is
8961 // produced by multiple base class constructors from the same base
8962 // class, the inheriting constructor is defined as deleted.
8963 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8964 }
8965
8966 return;
8967 }
8968
8969 ASTContext &Context = SemaRef.Context;
8970 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8971 Context.getCanonicalType(Context.getRecordType(Derived)));
8972 DeclarationNameInfo NameInfo(Name, UsingLoc);
8973
Craig Topperc3ec1492014-05-26 06:22:03 +00008974 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008975 if (const FunctionTemplateDecl *FTD =
8976 BaseCtor->getDescribedFunctionTemplate()) {
8977 TemplateParams = FTD->getTemplateParameters();
8978 // We're reusing template parameters from a different DeclContext. This
8979 // is questionable at best, but works out because the template depth in
8980 // both places is guaranteed to be 0.
8981 // FIXME: Rebuild the template parameters in the new context, and
8982 // transform the function type to refer to them.
8983 }
8984
8985 // Build type source info pointing at the using-declaration. This is
8986 // required by template instantiation.
8987 TypeSourceInfo *TInfo =
8988 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8989 FunctionProtoTypeLoc ProtoLoc =
8990 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8991
8992 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8993 Context, Derived, UsingLoc, NameInfo, DerivedType,
8994 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8995 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8996
8997 // Build an unevaluated exception specification for this constructor.
8998 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8999 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009000 EPI.ExceptionSpec.Type = EST_Unevaluated;
9001 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009002 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009003 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009004
9005 // Build the parameter declarations.
9006 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009007 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009008 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009009 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009010 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009011 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9012 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009013 PD->setScopeInfo(0, I);
9014 PD->setImplicit();
9015 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009016 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009017 }
9018
9019 // Set up the new constructor.
9020 DerivedCtor->setAccess(BaseCtor->getAccess());
9021 DerivedCtor->setParams(ParamDecls);
9022 DerivedCtor->setInheritedConstructor(BaseCtor);
9023 if (BaseCtor->isDeleted())
9024 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9025
9026 // If this is a constructor template, build the template declaration.
9027 if (TemplateParams) {
9028 FunctionTemplateDecl *DerivedTemplate =
9029 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9030 TemplateParams, DerivedCtor);
9031 DerivedTemplate->setAccess(BaseCtor->getAccess());
9032 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9033 Derived->addDecl(DerivedTemplate);
9034 } else {
9035 Derived->addDecl(DerivedCtor);
9036 }
9037
9038 Entry.BaseCtor = BaseCtor;
9039 Entry.DerivedCtor = DerivedCtor;
9040 }
9041
9042 Sema &SemaRef;
9043 CXXRecordDecl *Derived;
9044 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9045 MapType Map;
9046};
9047}
9048
9049void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9050 // Defer declaring the inheriting constructors until the class is
9051 // instantiated.
9052 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009053 return;
9054
Richard Smith185be182013-04-10 05:48:59 +00009055 // Find base classes from which we might inherit constructors.
9056 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009057 for (const auto &BaseIt : ClassDecl->bases())
9058 if (BaseIt.getInheritConstructors())
9059 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009060
Richard Smith185be182013-04-10 05:48:59 +00009061 // Go no further if we're not inheriting any constructors.
9062 if (InheritedBases.empty())
9063 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009064
Richard Smith185be182013-04-10 05:48:59 +00009065 // Declare the inherited constructors.
9066 InheritingConstructorInfo ICI(*this, ClassDecl);
9067 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9068 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009069}
9070
Richard Smithc2bc61b2013-03-18 21:12:30 +00009071void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9072 CXXConstructorDecl *Constructor) {
9073 CXXRecordDecl *ClassDecl = Constructor->getParent();
9074 assert(Constructor->getInheritedConstructor() &&
9075 !Constructor->doesThisDeclarationHaveABody() &&
9076 !Constructor->isDeleted());
9077
9078 SynthesizedFunctionScope Scope(*this, Constructor);
9079 DiagnosticErrorTrap Trap(Diags);
9080 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9081 Trap.hasErrorOccurred()) {
9082 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9083 << Context.getTagDeclType(ClassDecl);
9084 Constructor->setInvalidDecl();
9085 return;
9086 }
9087
9088 SourceLocation Loc = Constructor->getLocation();
9089 Constructor->setBody(new (Context) CompoundStmt(Loc));
9090
Eli Friedman276dd182013-09-05 00:02:25 +00009091 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009092 MarkVTableUsed(CurrentLocation, ClassDecl);
9093
9094 if (ASTMutationListener *L = getASTMutationListener()) {
9095 L->CompletedImplicitDefinition(Constructor);
9096 }
9097}
9098
9099
Alexis Huntf91729462011-05-12 22:46:25 +00009100Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009101Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9102 CXXRecordDecl *ClassDecl = MD->getParent();
9103
Douglas Gregorf1203042010-07-01 19:09:28 +00009104 // C++ [except.spec]p14:
9105 // An implicitly declared special member function (Clause 12) shall have
9106 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009107 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009108 if (ClassDecl->isInvalidDecl())
9109 return ExceptSpec;
9110
Douglas Gregorf1203042010-07-01 19:09:28 +00009111 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009112 for (const auto &B : ClassDecl->bases()) {
9113 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009114 continue;
9115
Aaron Ballman574705e2014-03-13 15:41:46 +00009116 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9117 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009118 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009119 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009120
Douglas Gregorf1203042010-07-01 19:09:28 +00009121 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009122 for (const auto &B : ClassDecl->vbases()) {
9123 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9124 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009125 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009126 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009127
Douglas Gregorf1203042010-07-01 19:09:28 +00009128 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009129 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009130 if (const RecordType *RecordTy
9131 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009132 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009133 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009134 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009135
Alexis Huntf91729462011-05-12 22:46:25 +00009136 return ExceptSpec;
9137}
9138
9139CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9140 // C++ [class.dtor]p2:
9141 // If a class has no user-declared destructor, a destructor is
9142 // declared implicitly. An implicitly-declared destructor is an
9143 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009144 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009145
Richard Smith8bf22e52012-11-29 01:34:07 +00009146 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9147 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009148 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009149
Douglas Gregor7454c562010-07-02 20:37:36 +00009150 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009151 CanQualType ClassType
9152 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009153 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009154 DeclarationName Name
9155 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009156 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009157 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009158 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009159 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009160 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009161 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009162 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009163
9164 if (getLangOpts().CUDA) {
9165 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9166 Destructor,
9167 /* ConstRHS */ false,
9168 /* Diagnose */ false);
9169 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009170
9171 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009172 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009173 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009174
Richard Smith6b02d462012-12-08 08:32:28 +00009175 AddOverriddenMethods(ClassDecl, Destructor);
9176
9177 // We don't need to use SpecialMemberIsTrivial here; triviality for
9178 // destructors is easy to compute.
9179 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9180
9181 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009182 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009183
Douglas Gregor7454c562010-07-02 20:37:36 +00009184 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009185 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009186
Douglas Gregor7454c562010-07-02 20:37:36 +00009187 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009188 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009189 PushOnScopeChains(Destructor, S, false);
9190 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009191
Douglas Gregorf1203042010-07-01 19:09:28 +00009192 return Destructor;
9193}
9194
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009195void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009196 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009197 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009198 !Destructor->doesThisDeclarationHaveABody() &&
9199 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009200 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009201 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009202 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009203
Douglas Gregor54818f02010-05-12 16:39:35 +00009204 if (Destructor->isInvalidDecl())
9205 return;
9206
Eli Friedmaneaf34142012-10-18 20:14:08 +00009207 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009208
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009209 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009210 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9211 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009212
Douglas Gregor54818f02010-05-12 16:39:35 +00009213 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009214 Diag(CurrentLocation, diag::note_member_synthesized_at)
9215 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9216
9217 Destructor->setInvalidDecl();
9218 return;
9219 }
9220
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009221 // The exception specification is needed because we are defining the
9222 // function.
9223 ResolveExceptionSpec(CurrentLocation,
9224 Destructor->getType()->castAs<FunctionProtoType>());
9225
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009226 SourceLocation Loc = Destructor->getLocEnd().isValid()
9227 ? Destructor->getLocEnd()
9228 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009229 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009230 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009231 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009232
9233 if (ASTMutationListener *L = getASTMutationListener()) {
9234 L->CompletedImplicitDefinition(Destructor);
9235 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009236}
9237
Richard Smith84973e52012-04-21 18:42:51 +00009238/// \brief Perform any semantic analysis which needs to be delayed until all
9239/// pending class member declarations have been parsed.
9240void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009241 // If the context is an invalid C++ class, just suppress these checks.
9242 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9243 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009244 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009245 DelayedDestructorExceptionSpecChecks.clear();
9246 return;
9247 }
9248 }
Richard Smith84973e52012-04-21 18:42:51 +00009249}
9250
Richard Smithd3b5c9082012-07-27 04:22:15 +00009251void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9252 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009253 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009254 "adjusting dtor exception specs was introduced in c++11");
9255
Sebastian Redl623ea822011-05-19 05:13:44 +00009256 // C++11 [class.dtor]p3:
9257 // A declaration of a destructor that does not have an exception-
9258 // specification is implicitly considered to have the same exception-
9259 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009260 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009261 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009262 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009263 return;
9264
Chandler Carruth9a797572011-09-20 04:55:26 +00009265 // Replace the destructor's type, building off the existing one. Fortunately,
9266 // the only thing of interest in the destructor type is its extended info.
9267 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009268 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009269 EPI.ExceptionSpec.Type = EST_Unevaluated;
9270 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009271 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009272
Sebastian Redl623ea822011-05-19 05:13:44 +00009273 // FIXME: If the destructor has a body that could throw, and the newly created
9274 // spec doesn't allow exceptions, we should emit a warning, because this
9275 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009276 // However, we don't have a body or an exception specification yet, so it
9277 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009278}
9279
Pavel Labath58934982013-08-30 08:52:28 +00009280namespace {
9281/// \brief An abstract base class for all helper classes used in building the
9282// copy/move operators. These classes serve as factory functions and help us
9283// avoid using the same Expr* in the AST twice.
9284class ExprBuilder {
9285 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9286 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9287
9288protected:
9289 static Expr *assertNotNull(Expr *E) {
9290 assert(E && "Expression construction must not fail.");
9291 return E;
9292 }
9293
9294public:
9295 ExprBuilder() {}
9296 virtual ~ExprBuilder() {}
9297
9298 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9299};
9300
9301class RefBuilder: public ExprBuilder {
9302 VarDecl *Var;
9303 QualType VarType;
9304
9305public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009306 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009307 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009308 }
9309
9310 RefBuilder(VarDecl *Var, QualType VarType)
9311 : Var(Var), VarType(VarType) {}
9312};
9313
9314class ThisBuilder: public ExprBuilder {
9315public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009316 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009317 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009318 }
9319};
9320
9321class CastBuilder: public ExprBuilder {
9322 const ExprBuilder &Builder;
9323 QualType Type;
9324 ExprValueKind Kind;
9325 const CXXCastPath &Path;
9326
9327public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009328 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009329 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9330 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009331 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009332 }
9333
9334 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9335 const CXXCastPath &Path)
9336 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9337};
9338
9339class DerefBuilder: public ExprBuilder {
9340 const ExprBuilder &Builder;
9341
9342public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009343 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009344 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009345 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009346 }
9347
9348 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9349};
9350
9351class MemberBuilder: public ExprBuilder {
9352 const ExprBuilder &Builder;
9353 QualType Type;
9354 CXXScopeSpec SS;
9355 bool IsArrow;
9356 LookupResult &MemberLookup;
9357
9358public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009359 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009360 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009361 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009362 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009363 }
9364
9365 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9366 LookupResult &MemberLookup)
9367 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9368 MemberLookup(MemberLookup) {}
9369};
9370
9371class MoveCastBuilder: public ExprBuilder {
9372 const ExprBuilder &Builder;
9373
9374public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009375 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009376 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9377 }
9378
9379 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9380};
9381
9382class LvalueConvBuilder: public ExprBuilder {
9383 const ExprBuilder &Builder;
9384
9385public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009386 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009387 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009388 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009389 }
9390
9391 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9392};
9393
9394class SubscriptBuilder: public ExprBuilder {
9395 const ExprBuilder &Base;
9396 const ExprBuilder &Index;
9397
9398public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009399 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009400 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009401 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009402 }
9403
9404 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9405 : Base(Base), Index(Index) {}
9406};
9407
9408} // end anonymous namespace
9409
Richard Smith41ae3282012-11-14 00:50:40 +00009410/// When generating a defaulted copy or move assignment operator, if a field
9411/// should be copied with __builtin_memcpy rather than via explicit assignments,
9412/// do so. This optimization only applies for arrays of scalars, and for arrays
9413/// of class type where the selected copy/move-assignment operator is trivial.
9414static StmtResult
9415buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009416 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009417 // Compute the size of the memory buffer to be copied.
9418 QualType SizeType = S.Context.getSizeType();
9419 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9420 S.Context.getTypeSizeInChars(T).getQuantity());
9421
9422 // Take the address of the field references for "from" and "to". We
9423 // directly construct UnaryOperators here because semantic analysis
9424 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009425 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009426 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9427 S.Context.getPointerType(From->getType()),
9428 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009429 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009430 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9431 S.Context.getPointerType(To->getType()),
9432 VK_RValue, OK_Ordinary, Loc);
9433
9434 const Type *E = T->getBaseElementTypeUnsafe();
9435 bool NeedsCollectableMemCpy =
9436 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9437
9438 // Create a reference to the __builtin_objc_memmove_collectable function
9439 StringRef MemCpyName = NeedsCollectableMemCpy ?
9440 "__builtin_objc_memmove_collectable" :
9441 "__builtin_memcpy";
9442 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9443 Sema::LookupOrdinaryName);
9444 S.LookupName(R, S.TUScope, true);
9445
9446 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9447 if (!MemCpy)
9448 // Something went horribly wrong earlier, and we will have complained
9449 // about it.
9450 return StmtError();
9451
9452 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009453 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009454 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9455
9456 Expr *CallArgs[] = {
9457 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9458 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009459 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009460 Loc, CallArgs, Loc);
9461
9462 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009463 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009464}
9465
Sebastian Redl22653ba2011-08-30 19:58:05 +00009466/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009467/// \c To.
9468///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009469/// This routine is used to copy/move the members of a class with an
9470/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009471/// copied are arrays, this routine builds for loops to copy them.
9472///
9473/// \param S The Sema object used for type-checking.
9474///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009475/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009476///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009477/// \param T The type of the expressions being copied/moved. Both expressions
9478/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009479///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009480/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009481///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009482/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009483///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009484/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009485/// Otherwise, it's a non-static member subobject.
9486///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009487/// \param Copying Whether we're copying or moving.
9488///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009489/// \param Depth Internal parameter recording the depth of the recursion.
9490///
Richard Smith41ae3282012-11-14 00:50:40 +00009491/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9492/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009493static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009494buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009495 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009496 bool CopyingBaseSubobject, bool Copying,
9497 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009498 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009499 // Each subobject is assigned in the manner appropriate to its type:
9500 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009501 // - if the subobject is of class type, as if by a call to operator= with
9502 // the subobject as the object expression and the corresponding
9503 // subobject of x as a single function argument (as if by explicit
9504 // qualification; that is, ignoring any possible virtual overriding
9505 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009506 //
9507 // C++03 [class.copy]p13:
9508 // - if the subobject is of class type, the copy assignment operator for
9509 // the class is used (as if by explicit qualification; that is,
9510 // ignoring any possible virtual overriding functions in more derived
9511 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009512 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9513 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009514
Douglas Gregorb139cd52010-05-01 20:49:11 +00009515 // Look for operator=.
9516 DeclarationName Name
9517 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9518 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9519 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009520
Richard Smith52c0b582012-11-13 00:54:12 +00009521 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9522 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009523 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009524 LookupResult::Filter F = OpLookup.makeFilter();
9525 while (F.hasNext()) {
9526 NamedDecl *D = F.next();
9527 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9528 if (Method->isCopyAssignmentOperator() ||
9529 (!Copying && Method->isMoveAssignmentOperator()))
9530 continue;
9531
9532 F.erase();
9533 }
9534 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009535 }
Richard Smith52c0b582012-11-13 00:54:12 +00009536
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009537 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009538 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009539 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009540 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009541 // ambiguities), we need to cast "this" to that subobject type; to
9542 // ensure that we don't go through the virtual call mechanism, we need
9543 // to qualify the operator= name with the base class (see below). However,
9544 // this means that if the base class has a protected copy assignment
9545 // operator, the protected member access check will fail. So, we
9546 // rewrite "protected" access to "public" access in this case, since we
9547 // know by construction that we're calling from a derived class.
9548 if (CopyingBaseSubobject) {
9549 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9550 L != LEnd; ++L) {
9551 if (L.getAccess() == AS_protected)
9552 L.setAccess(AS_public);
9553 }
9554 }
Richard Smith52c0b582012-11-13 00:54:12 +00009555
Douglas Gregorb139cd52010-05-01 20:49:11 +00009556 // Create the nested-name-specifier that will be used to qualify the
9557 // reference to operator=; this is required to suppress the virtual
9558 // call mechanism.
9559 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009560 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009561 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009562 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009563 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009564 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009565
Douglas Gregorb139cd52010-05-01 20:49:11 +00009566 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009567 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009568 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9569 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009570 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009571 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009572 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009573 /*SuppressQualifierCheck=*/true);
9574 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009575 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009576
Douglas Gregorb139cd52010-05-01 20:49:11 +00009577 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009578
Pavel Labath58934982013-08-30 08:52:28 +00009579 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009580 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009581 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009582 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009583 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009584 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009585
Richard Smith41ae3282012-11-14 00:50:40 +00009586 // If we built a call to a trivial 'operator=' while copying an array,
9587 // bail out. We'll replace the whole shebang with a memcpy.
9588 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9589 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009590 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009591
Richard Smith52c0b582012-11-13 00:54:12 +00009592 // Convert to an expression-statement, and clean up any produced
9593 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009594 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009595 }
John McCallab8c2732010-03-16 06:11:48 +00009596
Richard Smith52c0b582012-11-13 00:54:12 +00009597 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009598 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009599 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009600 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009601 ExprResult Assignment = S.CreateBuiltinBinOp(
9602 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009603 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009604 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009605 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009606 }
Richard Smith52c0b582012-11-13 00:54:12 +00009607
9608 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009609 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009610
Douglas Gregorb139cd52010-05-01 20:49:11 +00009611 // Construct a loop over the array bounds, e.g.,
9612 //
9613 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9614 //
9615 // that will copy each of the array elements.
9616 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009617
Douglas Gregorb139cd52010-05-01 20:49:11 +00009618 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009619 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009620 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009621 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009622 llvm::raw_svector_ostream OS(Str);
9623 OS << "__i" << Depth;
9624 IterationVarName = &S.Context.Idents.get(OS.str());
9625 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009626 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009627 IterationVarName, SizeType,
9628 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009629 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009630
Douglas Gregorb139cd52010-05-01 20:49:11 +00009631 // Initialize the iteration variable to zero.
9632 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009633 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009634
Pavel Labath58934982013-08-30 08:52:28 +00009635 // Creates a reference to the iteration variable.
9636 RefBuilder IterationVarRef(IterationVar, SizeType);
9637 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009638
Douglas Gregorb139cd52010-05-01 20:49:11 +00009639 // Create the DeclStmt that holds the iteration variable.
9640 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009641
Douglas Gregorb139cd52010-05-01 20:49:11 +00009642 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009643 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9644 MoveCastBuilder FromIndexMove(FromIndexCopy);
9645 const ExprBuilder *FromIndex;
9646 if (Copying)
9647 FromIndex = &FromIndexCopy;
9648 else
9649 FromIndex = &FromIndexMove;
9650
9651 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009652
9653 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009654 StmtResult Copy =
9655 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009656 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009657 Copying, Depth + 1);
9658 // Bail out if copying fails or if we determined that we should use memcpy.
9659 if (Copy.isInvalid() || !Copy.get())
9660 return Copy;
9661
9662 // Create the comparison against the array bound.
9663 llvm::APInt Upper
9664 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9665 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009666 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009667 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9668 BO_NE, S.Context.BoolTy,
9669 VK_RValue, OK_Ordinary, Loc, false);
9670
9671 // Create the pre-increment of the iteration variable.
9672 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009673 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9674 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009675
Douglas Gregorb139cd52010-05-01 20:49:11 +00009676 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009677 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009678 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009679 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009680 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009681}
9682
Richard Smith41ae3282012-11-14 00:50:40 +00009683static StmtResult
9684buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009685 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009686 bool CopyingBaseSubobject, bool Copying) {
9687 // Maybe we should use a memcpy?
9688 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9689 T.isTriviallyCopyableType(S.Context))
9690 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9691
9692 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9693 CopyingBaseSubobject,
9694 Copying, 0));
9695
9696 // If we ended up picking a trivial assignment operator for an array of a
9697 // non-trivially-copyable class type, just emit a memcpy.
9698 if (!Result.isInvalid() && !Result.get())
9699 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9700
9701 return Result;
9702}
9703
Richard Smithd3b5c9082012-07-27 04:22:15 +00009704Sema::ImplicitExceptionSpecification
9705Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9706 CXXRecordDecl *ClassDecl = MD->getParent();
9707
9708 ImplicitExceptionSpecification ExceptSpec(*this);
9709 if (ClassDecl->isInvalidDecl())
9710 return ExceptSpec;
9711
9712 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009713 assert(T->getNumParams() == 1 && "not a copy assignment op");
9714 unsigned ArgQuals =
9715 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009716
Douglas Gregor68e11362010-07-01 17:48:08 +00009717 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009718 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009719 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009720
9721 // It is unspecified whether or not an implicit copy assignment operator
9722 // attempts to deduplicate calls to assignment operators of virtual bases are
9723 // made. As such, this exception specification is effectively unspecified.
9724 // Based on a similar decision made for constness in C++0x, we're erring on
9725 // the side of assuming such calls to be made regardless of whether they
9726 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009727 for (const auto &Base : ClassDecl->bases()) {
9728 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009729 continue;
9730
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009731 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009732 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009733 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9734 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009735 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009736 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009737
Aaron Ballman445a9392014-03-13 16:15:17 +00009738 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009739 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009740 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009741 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9742 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009743 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009744 }
9745
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009746 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009747 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009748 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9749 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009750 LookupCopyingAssignment(FieldClassDecl,
9751 ArgQuals | FieldType.getCVRQualifiers(),
9752 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009753 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009754 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009755 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009756
Richard Smithd3b5c9082012-07-27 04:22:15 +00009757 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009758}
9759
9760CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9761 // Note: The following rules are largely analoguous to the copy
9762 // constructor rules. Note that virtual bases are not taken into account
9763 // for determining the argument type of the operator. Note also that
9764 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009765 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009766
Richard Smith8bf22e52012-11-29 01:34:07 +00009767 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9768 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009769 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009770
Alexis Hunt119f3652011-05-14 05:23:20 +00009771 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9772 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009773 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9774 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009775 ArgType = ArgType.withConst();
9776 ArgType = Context.getLValueReferenceType(ArgType);
9777
Richard Smith99005e62013-05-07 03:19:20 +00009778 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9779 CXXCopyAssignment,
9780 Const);
9781
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009782 // An implicitly-declared copy assignment operator is an inline public
9783 // member of its class.
9784 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009785 SourceLocation ClassLoc = ClassDecl->getLocation();
9786 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009787 CXXMethodDecl *CopyAssignment =
9788 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009789 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9790 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009791 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009792 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009793 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009794
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009795 if (getLangOpts().CUDA) {
9796 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9797 CopyAssignment,
9798 /* ConstRHS */ Const,
9799 /* Diagnose */ false);
9800 }
9801
Richard Smithd3b5c9082012-07-27 04:22:15 +00009802 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009803 FunctionProtoType::ExtProtoInfo EPI =
9804 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009805 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009806
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009807 // Add the parameter to the operator.
9808 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009809 ClassLoc, ClassLoc,
9810 /*Id=*/nullptr, ArgType,
9811 /*TInfo=*/nullptr, SC_None,
9812 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009813 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009814
Richard Smith6b02d462012-12-08 08:32:28 +00009815 AddOverriddenMethods(ClassDecl, CopyAssignment);
9816
9817 CopyAssignment->setTrivial(
9818 ClassDecl->needsOverloadResolutionForCopyAssignment()
9819 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9820 : ClassDecl->hasTrivialCopyAssignment());
9821
Richard Smith852265f2012-03-30 20:53:28 +00009822 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009823 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009824
Richard Smith6b02d462012-12-08 08:32:28 +00009825 // Note that we have added this copy-assignment operator.
9826 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9827
9828 if (Scope *S = getScopeForContext(ClassDecl))
9829 PushOnScopeChains(CopyAssignment, S, false);
9830 ClassDecl->addDecl(CopyAssignment);
9831
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009832 return CopyAssignment;
9833}
9834
Richard Smithd577fbb2013-06-13 03:23:42 +00009835/// Diagnose an implicit copy operation for a class which is odr-used, but
9836/// which is deprecated because the class has a user-declared copy constructor,
9837/// copy assignment operator, or destructor.
9838static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9839 SourceLocation UseLoc) {
9840 assert(CopyOp->isImplicit());
9841
9842 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009843 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009844
9845 // In Microsoft mode, assignment operations don't affect constructors and
9846 // vice versa.
9847 if (RD->hasUserDeclaredDestructor()) {
9848 UserDeclaredOperation = RD->getDestructor();
9849 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9850 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009851 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009852 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009853 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009854 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009855 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009856 break;
9857 }
9858 }
9859 assert(UserDeclaredOperation);
9860 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9861 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009862 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009863 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009864 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009865 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009866 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009867 break;
9868 }
9869 }
9870 assert(UserDeclaredOperation);
9871 }
9872
9873 if (UserDeclaredOperation) {
9874 S.Diag(UserDeclaredOperation->getLocation(),
9875 diag::warn_deprecated_copy_operation)
9876 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9877 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9878 S.Diag(UseLoc, diag::note_member_synthesized_at)
9879 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9880 : Sema::CXXCopyAssignment)
9881 << RD;
9882 }
9883}
9884
Douglas Gregorb139cd52010-05-01 20:49:11 +00009885void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9886 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009887 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009888 CopyAssignOperator->isOverloadedOperator() &&
9889 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009890 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9891 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009892 "DefineImplicitCopyAssignment called for wrong function");
9893
9894 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9895
9896 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9897 CopyAssignOperator->setInvalidDecl();
9898 return;
9899 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009900
9901 // C++11 [class.copy]p18:
9902 // The [definition of an implicitly declared copy assignment operator] is
9903 // deprecated if the class has a user-declared copy constructor or a
9904 // user-declared destructor.
9905 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9906 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9907
Eli Friedman276dd182013-09-05 00:02:25 +00009908 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009909
Eli Friedmaneaf34142012-10-18 20:14:08 +00009910 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009911 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009912
9913 // C++0x [class.copy]p30:
9914 // The implicitly-defined or explicitly-defaulted copy assignment operator
9915 // for a non-union class X performs memberwise copy assignment of its
9916 // subobjects. The direct base classes of X are assigned first, in the
9917 // order of their declaration in the base-specifier-list, and then the
9918 // immediate non-static data members of X are assigned, in the order in
9919 // which they were declared in the class definition.
9920
9921 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009922 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009923
9924 // The parameter for the "other" object, which we are copying from.
9925 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9926 Qualifiers OtherQuals = Other->getType().getQualifiers();
9927 QualType OtherRefType = Other->getType();
9928 if (const LValueReferenceType *OtherRef
9929 = OtherRefType->getAs<LValueReferenceType>()) {
9930 OtherRefType = OtherRef->getPointeeType();
9931 OtherQuals = OtherRefType.getQualifiers();
9932 }
9933
9934 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009935 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9936 ? CopyAssignOperator->getLocEnd()
9937 : CopyAssignOperator->getLocation();
9938
Pavel Labath58934982013-08-30 08:52:28 +00009939 // Builds a DeclRefExpr for the "other" object.
9940 RefBuilder OtherRef(Other, OtherRefType);
9941
9942 // Builds the "this" pointer.
9943 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009944
9945 // Assign base classes.
9946 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009947 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009948 // Form the assignment:
9949 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009950 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009951 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009952 Invalid = true;
9953 continue;
9954 }
9955
John McCallcf142162010-08-07 06:22:56 +00009956 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009957 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009958
Douglas Gregorb139cd52010-05-01 20:49:11 +00009959 // Construct the "from" expression, which is an implicit cast to the
9960 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009961 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9962 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009963
9964 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009965 DerefBuilder DerefThis(This);
9966 CastBuilder To(DerefThis,
9967 Context.getCVRQualifiedType(
9968 BaseType, CopyAssignOperator->getTypeQualifiers()),
9969 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009970
9971 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009972 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009973 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009974 /*CopyingBaseSubobject=*/true,
9975 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009976 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009977 Diag(CurrentLocation, diag::note_member_synthesized_at)
9978 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9979 CopyAssignOperator->setInvalidDecl();
9980 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009981 }
9982
9983 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009984 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009985 }
9986
Douglas Gregorb139cd52010-05-01 20:49:11 +00009987 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009988 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009989 if (Field->isUnnamedBitfield())
9990 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009991
9992 if (Field->isInvalidDecl()) {
9993 Invalid = true;
9994 continue;
9995 }
9996
Douglas Gregorb139cd52010-05-01 20:49:11 +00009997 // Check for members of reference type; we can't copy those.
9998 if (Field->getType()->isReferenceType()) {
9999 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10000 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10001 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010002 Diag(CurrentLocation, diag::note_member_synthesized_at)
10003 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010004 Invalid = true;
10005 continue;
10006 }
10007
10008 // Check for members of const-qualified, non-class type.
10009 QualType BaseType = Context.getBaseElementType(Field->getType());
10010 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10011 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10012 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10013 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010014 Diag(CurrentLocation, diag::note_member_synthesized_at)
10015 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010016 Invalid = true;
10017 continue;
10018 }
John McCall1b1a1db2011-06-17 00:18:42 +000010019
10020 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010021 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10022 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010023
10024 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010025 if (FieldType->isIncompleteArrayType()) {
10026 assert(ClassDecl->hasFlexibleArrayMember() &&
10027 "Incomplete array type is not valid");
10028 continue;
10029 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010030
10031 // Build references to the field in the object we're copying from and to.
10032 CXXScopeSpec SS; // Intentionally empty
10033 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10034 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010035 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010036 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010037
10038 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10039
10040 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010041
Douglas Gregorb139cd52010-05-01 20:49:11 +000010042 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010043 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010044 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010045 /*CopyingBaseSubobject=*/false,
10046 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010047 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010048 Diag(CurrentLocation, diag::note_member_synthesized_at)
10049 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10050 CopyAssignOperator->setInvalidDecl();
10051 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010052 }
10053
10054 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010055 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010056 }
10057
10058 if (!Invalid) {
10059 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010060 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010061
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010062 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010063 if (Return.isInvalid())
10064 Invalid = true;
10065 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010066 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010067
10068 if (Trap.hasErrorOccurred()) {
10069 Diag(CurrentLocation, diag::note_member_synthesized_at)
10070 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10071 Invalid = true;
10072 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010073 }
10074 }
10075
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010076 // The exception specification is needed because we are defining the
10077 // function.
10078 ResolveExceptionSpec(CurrentLocation,
10079 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10080
Douglas Gregorb139cd52010-05-01 20:49:11 +000010081 if (Invalid) {
10082 CopyAssignOperator->setInvalidDecl();
10083 return;
10084 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010085
10086 StmtResult Body;
10087 {
10088 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010089 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010090 /*isStmtExpr=*/false);
10091 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10092 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010093 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010094
10095 if (ASTMutationListener *L = getASTMutationListener()) {
10096 L->CompletedImplicitDefinition(CopyAssignOperator);
10097 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010098}
10099
Sebastian Redl22653ba2011-08-30 19:58:05 +000010100Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010101Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10102 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010103
Richard Smithd3b5c9082012-07-27 04:22:15 +000010104 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010105 if (ClassDecl->isInvalidDecl())
10106 return ExceptSpec;
10107
10108 // C++0x [except.spec]p14:
10109 // An implicitly declared special member function (Clause 12) shall have an
10110 // exception-specification. [...]
10111
10112 // It is unspecified whether or not an implicit move assignment operator
10113 // attempts to deduplicate calls to assignment operators of virtual bases are
10114 // made. As such, this exception specification is effectively unspecified.
10115 // Based on a similar decision made for constness in C++0x, we're erring on
10116 // the side of assuming such calls to be made regardless of whether they
10117 // actually happen.
10118 // Note that a move constructor is not implicitly declared when there are
10119 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010120 for (const auto &Base : ClassDecl->bases()) {
10121 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010122 continue;
10123
10124 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010125 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010126 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010127 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010128 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010129 }
10130
Aaron Ballman445a9392014-03-13 16:15:17 +000010131 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010132 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010133 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010134 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010135 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010136 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010137 }
10138
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010139 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010140 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010141 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010142 if (CXXMethodDecl *MoveAssign =
10143 LookupMovingAssignment(FieldClassDecl,
10144 FieldType.getCVRQualifiers(),
10145 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010146 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010147 }
10148 }
10149
10150 return ExceptSpec;
10151}
10152
10153CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010154 assert(ClassDecl->needsImplicitMoveAssignment());
10155
Richard Smith8bf22e52012-11-29 01:34:07 +000010156 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10157 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010158 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010159
Sebastian Redl22653ba2011-08-30 19:58:05 +000010160 // Note: The following rules are largely analoguous to the move
10161 // constructor rules.
10162
Sebastian Redl22653ba2011-08-30 19:58:05 +000010163 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10164 QualType RetType = Context.getLValueReferenceType(ArgType);
10165 ArgType = Context.getRValueReferenceType(ArgType);
10166
Richard Smith99005e62013-05-07 03:19:20 +000010167 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10168 CXXMoveAssignment,
10169 false);
10170
Sebastian Redl22653ba2011-08-30 19:58:05 +000010171 // An implicitly-declared move assignment operator is an inline public
10172 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010173 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10174 SourceLocation ClassLoc = ClassDecl->getLocation();
10175 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010176 CXXMethodDecl *MoveAssignment =
10177 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010178 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010179 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010180 MoveAssignment->setAccess(AS_public);
10181 MoveAssignment->setDefaulted();
10182 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010183
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010184 if (getLangOpts().CUDA) {
10185 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10186 MoveAssignment,
10187 /* ConstRHS */ false,
10188 /* Diagnose */ false);
10189 }
10190
Richard Smithd3b5c9082012-07-27 04:22:15 +000010191 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010192 FunctionProtoType::ExtProtoInfo EPI =
10193 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010194 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010195
Sebastian Redl22653ba2011-08-30 19:58:05 +000010196 // Add the parameter to the operator.
10197 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010198 ClassLoc, ClassLoc,
10199 /*Id=*/nullptr, ArgType,
10200 /*TInfo=*/nullptr, SC_None,
10201 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010202 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010203
Richard Smith6b02d462012-12-08 08:32:28 +000010204 AddOverriddenMethods(ClassDecl, MoveAssignment);
10205
10206 MoveAssignment->setTrivial(
10207 ClassDecl->needsOverloadResolutionForMoveAssignment()
10208 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10209 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010210
Richard Smithd951a1d2012-02-18 02:02:13 +000010211 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010212 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10213 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010214 }
10215
Richard Smith6b02d462012-12-08 08:32:28 +000010216 // Note that we have added this copy-assignment operator.
10217 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10218
Sebastian Redl22653ba2011-08-30 19:58:05 +000010219 if (Scope *S = getScopeForContext(ClassDecl))
10220 PushOnScopeChains(MoveAssignment, S, false);
10221 ClassDecl->addDecl(MoveAssignment);
10222
Sebastian Redl22653ba2011-08-30 19:58:05 +000010223 return MoveAssignment;
10224}
10225
Richard Smithb2504bd2013-11-04 04:26:14 +000010226/// Check if we're implicitly defining a move assignment operator for a class
10227/// with virtual bases. Such a move assignment might move-assign the virtual
10228/// base multiple times.
10229static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10230 SourceLocation CurrentLocation) {
10231 assert(!Class->isDependentContext() && "should not define dependent move");
10232
10233 // Only a virtual base could get implicitly move-assigned multiple times.
10234 // Only a non-trivial move assignment can observe this. We only want to
10235 // diagnose if we implicitly define an assignment operator that assigns
10236 // two base classes, both of which move-assign the same virtual base.
10237 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10238 Class->getNumBases() < 2)
10239 return;
10240
10241 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10242 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10243 VBaseMap VBases;
10244
Aaron Ballman574705e2014-03-13 15:41:46 +000010245 for (auto &BI : Class->bases()) {
10246 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010247 while (!Worklist.empty()) {
10248 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10249 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10250
10251 // If the base has no non-trivial move assignment operators,
10252 // we don't care about moves from it.
10253 if (!Base->hasNonTrivialMoveAssignment())
10254 continue;
10255
10256 // If there's nothing virtual here, skip it.
10257 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10258 continue;
10259
10260 // If we're not actually going to call a move assignment for this base,
10261 // or the selected move assignment is trivial, skip it.
10262 Sema::SpecialMemberOverloadResult *SMOR =
10263 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10264 /*ConstArg*/false, /*VolatileArg*/false,
10265 /*RValueThis*/true, /*ConstThis*/false,
10266 /*VolatileThis*/false);
10267 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10268 !SMOR->getMethod()->isMoveAssignmentOperator())
10269 continue;
10270
10271 if (BaseSpec->isVirtual()) {
10272 // We're going to move-assign this virtual base, and its move
10273 // assignment operator is not trivial. If this can happen for
10274 // multiple distinct direct bases of Class, diagnose it. (If it
10275 // only happens in one base, we'll diagnose it when synthesizing
10276 // that base class's move assignment operator.)
10277 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010278 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010279 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010280 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010281 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10282 << Class << Base;
10283 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10284 << (Base->getCanonicalDecl() ==
10285 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10286 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010287 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010288 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010289 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10290 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010291
10292 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010293 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010294 }
10295 } else {
10296 // Only walk over bases that have defaulted move assignment operators.
10297 // We assume that any user-provided move assignment operator handles
10298 // the multiple-moves-of-vbase case itself somehow.
10299 if (!SMOR->getMethod()->isDefaulted())
10300 continue;
10301
10302 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010303 for (auto &BI : Base->bases())
10304 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010305 }
10306 }
10307 }
10308}
10309
Sebastian Redl22653ba2011-08-30 19:58:05 +000010310void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10311 CXXMethodDecl *MoveAssignOperator) {
10312 assert((MoveAssignOperator->isDefaulted() &&
10313 MoveAssignOperator->isOverloadedOperator() &&
10314 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010315 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10316 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010317 "DefineImplicitMoveAssignment called for wrong function");
10318
10319 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10320
10321 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10322 MoveAssignOperator->setInvalidDecl();
10323 return;
10324 }
10325
Eli Friedman276dd182013-09-05 00:02:25 +000010326 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010327
Eli Friedmaneaf34142012-10-18 20:14:08 +000010328 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010329 DiagnosticErrorTrap Trap(Diags);
10330
10331 // C++0x [class.copy]p28:
10332 // The implicitly-defined or move assignment operator for a non-union class
10333 // X performs memberwise move assignment of its subobjects. The direct base
10334 // classes of X are assigned first, in the order of their declaration in the
10335 // base-specifier-list, and then the immediate non-static data members of X
10336 // are assigned, in the order in which they were declared in the class
10337 // definition.
10338
Richard Smithb2504bd2013-11-04 04:26:14 +000010339 // Issue a warning if our implicit move assignment operator will move
10340 // from a virtual base more than once.
10341 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010342
Sebastian Redl22653ba2011-08-30 19:58:05 +000010343 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010344 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010345
10346 // The parameter for the "other" object, which we are move from.
10347 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10348 QualType OtherRefType = Other->getType()->
10349 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010350 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010351 "Bad argument type of defaulted move assignment");
10352
10353 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010354 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10355 ? MoveAssignOperator->getLocEnd()
10356 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010357
Pavel Labath58934982013-08-30 08:52:28 +000010358 // Builds a reference to the "other" object.
10359 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010360 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010361 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010362
Pavel Labath58934982013-08-30 08:52:28 +000010363 // Builds the "this" pointer.
10364 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010365
Sebastian Redl22653ba2011-08-30 19:58:05 +000010366 // Assign base classes.
10367 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010368 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010369 // C++11 [class.copy]p28:
10370 // It is unspecified whether subobjects representing virtual base classes
10371 // are assigned more than once by the implicitly-defined copy assignment
10372 // operator.
10373 // FIXME: Do not assign to a vbase that will be assigned by some other base
10374 // class. For a move-assignment, this can result in the vbase being moved
10375 // multiple times.
10376
Sebastian Redl22653ba2011-08-30 19:58:05 +000010377 // Form the assignment:
10378 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010379 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010380 if (!BaseType->isRecordType()) {
10381 Invalid = true;
10382 continue;
10383 }
10384
10385 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010386 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010387
10388 // Construct the "from" expression, which is an implicit cast to the
10389 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010390 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010391
10392 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010393 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010394
10395 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010396 CastBuilder To(DerefThis,
10397 Context.getCVRQualifiedType(
10398 BaseType, MoveAssignOperator->getTypeQualifiers()),
10399 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010400
10401 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010402 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010403 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010404 /*CopyingBaseSubobject=*/true,
10405 /*Copying=*/false);
10406 if (Move.isInvalid()) {
10407 Diag(CurrentLocation, diag::note_member_synthesized_at)
10408 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10409 MoveAssignOperator->setInvalidDecl();
10410 return;
10411 }
10412
10413 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010414 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010415 }
10416
Sebastian Redl22653ba2011-08-30 19:58:05 +000010417 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010418 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010419 if (Field->isUnnamedBitfield())
10420 continue;
10421
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010422 if (Field->isInvalidDecl()) {
10423 Invalid = true;
10424 continue;
10425 }
10426
Sebastian Redl22653ba2011-08-30 19:58:05 +000010427 // Check for members of reference type; we can't move those.
10428 if (Field->getType()->isReferenceType()) {
10429 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10430 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10431 Diag(Field->getLocation(), diag::note_declared_at);
10432 Diag(CurrentLocation, diag::note_member_synthesized_at)
10433 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10434 Invalid = true;
10435 continue;
10436 }
10437
10438 // Check for members of const-qualified, non-class type.
10439 QualType BaseType = Context.getBaseElementType(Field->getType());
10440 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10441 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10442 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10443 Diag(Field->getLocation(), diag::note_declared_at);
10444 Diag(CurrentLocation, diag::note_member_synthesized_at)
10445 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10446 Invalid = true;
10447 continue;
10448 }
10449
10450 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010451 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10452 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010453
10454 QualType FieldType = Field->getType().getNonReferenceType();
10455 if (FieldType->isIncompleteArrayType()) {
10456 assert(ClassDecl->hasFlexibleArrayMember() &&
10457 "Incomplete array type is not valid");
10458 continue;
10459 }
10460
10461 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010462 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10463 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010464 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010465 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010466 MemberBuilder From(MoveOther, OtherRefType,
10467 /*IsArrow=*/false, MemberLookup);
10468 MemberBuilder To(This, getCurrentThisType(),
10469 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010470
Pavel Labath58934982013-08-30 08:52:28 +000010471 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010472 "Member reference with rvalue base must be rvalue except for reference "
10473 "members, which aren't allowed for move assignment.");
10474
Sebastian Redl22653ba2011-08-30 19:58:05 +000010475 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010476 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010477 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010478 /*CopyingBaseSubobject=*/false,
10479 /*Copying=*/false);
10480 if (Move.isInvalid()) {
10481 Diag(CurrentLocation, diag::note_member_synthesized_at)
10482 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10483 MoveAssignOperator->setInvalidDecl();
10484 return;
10485 }
Richard Smith11d19592012-11-12 23:33:00 +000010486
Sebastian Redl22653ba2011-08-30 19:58:05 +000010487 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010488 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010489 }
10490
10491 if (!Invalid) {
10492 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010493 ExprResult ThisObj =
10494 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10495
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010496 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010497 if (Return.isInvalid())
10498 Invalid = true;
10499 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010500 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010501
10502 if (Trap.hasErrorOccurred()) {
10503 Diag(CurrentLocation, diag::note_member_synthesized_at)
10504 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10505 Invalid = true;
10506 }
10507 }
10508 }
10509
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010510 // The exception specification is needed because we are defining the
10511 // function.
10512 ResolveExceptionSpec(CurrentLocation,
10513 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10514
Sebastian Redl22653ba2011-08-30 19:58:05 +000010515 if (Invalid) {
10516 MoveAssignOperator->setInvalidDecl();
10517 return;
10518 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010519
10520 StmtResult Body;
10521 {
10522 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010523 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010524 /*isStmtExpr=*/false);
10525 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10526 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010527 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010528
10529 if (ASTMutationListener *L = getASTMutationListener()) {
10530 L->CompletedImplicitDefinition(MoveAssignOperator);
10531 }
10532}
10533
Richard Smithd3b5c9082012-07-27 04:22:15 +000010534Sema::ImplicitExceptionSpecification
10535Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10536 CXXRecordDecl *ClassDecl = MD->getParent();
10537
10538 ImplicitExceptionSpecification ExceptSpec(*this);
10539 if (ClassDecl->isInvalidDecl())
10540 return ExceptSpec;
10541
10542 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010543 assert(T->getNumParams() >= 1 && "not a copy ctor");
10544 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010545
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010546 // C++ [except.spec]p14:
10547 // An implicitly declared special member function (Clause 12) shall have an
10548 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010549 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010550 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010551 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010552 continue;
10553
Douglas Gregora6d69502010-07-02 23:41:54 +000010554 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010555 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010556 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010557 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010558 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010559 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010560 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010561 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010562 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010563 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010564 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010565 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010566 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010567 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010568 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010569 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10570 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010571 LookupCopyingConstructor(FieldClassDecl,
10572 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010573 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010574 }
10575 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010576
Richard Smithd3b5c9082012-07-27 04:22:15 +000010577 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010578}
10579
10580CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10581 CXXRecordDecl *ClassDecl) {
10582 // C++ [class.copy]p4:
10583 // If the class definition does not explicitly declare a copy
10584 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010585 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010586
Richard Smith8bf22e52012-11-29 01:34:07 +000010587 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10588 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010589 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010590
Alexis Hunt913820d2011-05-13 06:10:58 +000010591 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10592 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010593 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010594 if (Const)
10595 ArgType = ArgType.withConst();
10596 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010597
Richard Smithb5800092012-06-10 05:43:50 +000010598 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10599 CXXCopyConstructor,
10600 Const);
10601
Douglas Gregor54be3392010-07-01 17:57:27 +000010602 DeclarationName Name
10603 = Context.DeclarationNames.getCXXConstructorName(
10604 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010605 SourceLocation ClassLoc = ClassDecl->getLocation();
10606 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010607
10608 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010609 // member of its class.
10610 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010611 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010612 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010613 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010614 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010615 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010616
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010617 if (getLangOpts().CUDA) {
10618 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10619 CopyConstructor,
10620 /* ConstRHS */ Const,
10621 /* Diagnose */ false);
10622 }
10623
Richard Smithd3b5c9082012-07-27 04:22:15 +000010624 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010625 FunctionProtoType::ExtProtoInfo EPI =
10626 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010627 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010628 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010629
Douglas Gregor54be3392010-07-01 17:57:27 +000010630 // Add the parameter to the constructor.
10631 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010632 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010633 /*IdentifierInfo=*/nullptr,
10634 ArgType, /*TInfo=*/nullptr,
10635 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010636 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010637
Richard Smith6b02d462012-12-08 08:32:28 +000010638 CopyConstructor->setTrivial(
10639 ClassDecl->needsOverloadResolutionForCopyConstructor()
10640 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10641 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010642
Richard Smith852265f2012-03-30 20:53:28 +000010643 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010644 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010645
Richard Smith6b02d462012-12-08 08:32:28 +000010646 // Note that we have declared this constructor.
10647 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10648
10649 if (Scope *S = getScopeForContext(ClassDecl))
10650 PushOnScopeChains(CopyConstructor, S, false);
10651 ClassDecl->addDecl(CopyConstructor);
10652
Douglas Gregor54be3392010-07-01 17:57:27 +000010653 return CopyConstructor;
10654}
10655
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010656void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010657 CXXConstructorDecl *CopyConstructor) {
10658 assert((CopyConstructor->isDefaulted() &&
10659 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010660 !CopyConstructor->doesThisDeclarationHaveABody() &&
10661 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010662 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010663
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010664 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010665 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010666
Richard Smithd577fbb2013-06-13 03:23:42 +000010667 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010668 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010669 // deprecated if the class has a user-declared copy assignment operator
10670 // or a user-declared destructor.
10671 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10672 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10673
Eli Friedmaneaf34142012-10-18 20:14:08 +000010674 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010675 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010676
David Blaikie3fc2f912013-01-17 05:26:25 +000010677 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010678 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010679 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010680 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010681 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010682 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010683 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10684 ? CopyConstructor->getLocEnd()
10685 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010686 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010687 CopyConstructor->setBody(
10688 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010689 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010690
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010691 // The exception specification is needed because we are defining the
10692 // function.
10693 ResolveExceptionSpec(CurrentLocation,
10694 CopyConstructor->getType()->castAs<FunctionProtoType>());
10695
Eli Friedman276dd182013-09-05 00:02:25 +000010696 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010697 MarkVTableUsed(CurrentLocation, ClassDecl);
10698
Sebastian Redlab238a72011-04-24 16:28:06 +000010699 if (ASTMutationListener *L = getASTMutationListener()) {
10700 L->CompletedImplicitDefinition(CopyConstructor);
10701 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010702}
10703
Sebastian Redl22653ba2011-08-30 19:58:05 +000010704Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010705Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10706 CXXRecordDecl *ClassDecl = MD->getParent();
10707
Sebastian Redl22653ba2011-08-30 19:58:05 +000010708 // C++ [except.spec]p14:
10709 // An implicitly declared special member function (Clause 12) shall have an
10710 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010711 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010712 if (ClassDecl->isInvalidDecl())
10713 return ExceptSpec;
10714
10715 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010716 for (const auto &B : ClassDecl->bases()) {
10717 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010718 continue;
10719
Aaron Ballman574705e2014-03-13 15:41:46 +000010720 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010721 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010722 CXXConstructorDecl *Constructor =
10723 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010724 // If this is a deleted function, add it anyway. This might be conformant
10725 // with the standard. This might not. I'm not sure. It might not matter.
10726 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010727 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010728 }
10729 }
10730
10731 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010732 for (const auto &B : ClassDecl->vbases()) {
10733 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010734 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010735 CXXConstructorDecl *Constructor =
10736 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010737 // If this is a deleted function, add it anyway. This might be conformant
10738 // with the standard. This might not. I'm not sure. It might not matter.
10739 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010740 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010741 }
10742 }
10743
10744 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010745 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010746 QualType FieldType = Context.getBaseElementType(F->getType());
10747 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10748 CXXConstructorDecl *Constructor =
10749 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010750 // If this is a deleted function, add it anyway. This might be conformant
10751 // with the standard. This might not. I'm not sure. It might not matter.
10752 // In particular, the problem is that this function never gets called. It
10753 // might just be ill-formed because this function attempts to refer to
10754 // a deleted function here.
10755 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010756 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010757 }
10758 }
10759
10760 return ExceptSpec;
10761}
10762
10763CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10764 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010765 assert(ClassDecl->needsImplicitMoveConstructor());
10766
Richard Smith8bf22e52012-11-29 01:34:07 +000010767 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10768 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010769 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010770
Sebastian Redl22653ba2011-08-30 19:58:05 +000010771 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10772 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010773
Richard Smithb5800092012-06-10 05:43:50 +000010774 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10775 CXXMoveConstructor,
10776 false);
10777
Sebastian Redl22653ba2011-08-30 19:58:05 +000010778 DeclarationName Name
10779 = Context.DeclarationNames.getCXXConstructorName(
10780 Context.getCanonicalType(ClassType));
10781 SourceLocation ClassLoc = ClassDecl->getLocation();
10782 DeclarationNameInfo NameInfo(Name, ClassLoc);
10783
Richard Smith99005e62013-05-07 03:19:20 +000010784 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010785 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010786 // member of its class.
10787 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010788 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010789 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010790 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010791 MoveConstructor->setAccess(AS_public);
10792 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010793
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010794 if (getLangOpts().CUDA) {
10795 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10796 MoveConstructor,
10797 /* ConstRHS */ false,
10798 /* Diagnose */ false);
10799 }
10800
Richard Smithd3b5c9082012-07-27 04:22:15 +000010801 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010802 FunctionProtoType::ExtProtoInfo EPI =
10803 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010804 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010805 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010806
Sebastian Redl22653ba2011-08-30 19:58:05 +000010807 // Add the parameter to the constructor.
10808 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10809 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010810 /*IdentifierInfo=*/nullptr,
10811 ArgType, /*TInfo=*/nullptr,
10812 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010813 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010814
Richard Smith6b02d462012-12-08 08:32:28 +000010815 MoveConstructor->setTrivial(
10816 ClassDecl->needsOverloadResolutionForMoveConstructor()
10817 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10818 : ClassDecl->hasTrivialMoveConstructor());
10819
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010820 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010821 ClassDecl->setImplicitMoveConstructorIsDeleted();
10822 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010823 }
10824
10825 // Note that we have declared this constructor.
10826 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10827
10828 if (Scope *S = getScopeForContext(ClassDecl))
10829 PushOnScopeChains(MoveConstructor, S, false);
10830 ClassDecl->addDecl(MoveConstructor);
10831
10832 return MoveConstructor;
10833}
10834
10835void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10836 CXXConstructorDecl *MoveConstructor) {
10837 assert((MoveConstructor->isDefaulted() &&
10838 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010839 !MoveConstructor->doesThisDeclarationHaveABody() &&
10840 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010841 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10842
10843 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10844 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10845
Eli Friedmaneaf34142012-10-18 20:14:08 +000010846 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010847 DiagnosticErrorTrap Trap(Diags);
10848
David Blaikie3fc2f912013-01-17 05:26:25 +000010849 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010850 Trap.hasErrorOccurred()) {
10851 Diag(CurrentLocation, diag::note_member_synthesized_at)
10852 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10853 MoveConstructor->setInvalidDecl();
10854 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010855 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10856 ? MoveConstructor->getLocEnd()
10857 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010858 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010859 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010860 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010861 }
10862
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010863 // The exception specification is needed because we are defining the
10864 // function.
10865 ResolveExceptionSpec(CurrentLocation,
10866 MoveConstructor->getType()->castAs<FunctionProtoType>());
10867
Eli Friedman276dd182013-09-05 00:02:25 +000010868 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010869 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010870
10871 if (ASTMutationListener *L = getASTMutationListener()) {
10872 L->CompletedImplicitDefinition(MoveConstructor);
10873 }
10874}
10875
Douglas Gregor74f7d502012-02-15 19:33:52 +000010876bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010877 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010878}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010879
10880void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010881 SourceLocation CurrentLocation,
10882 CXXConversionDecl *Conv) {
10883 CXXRecordDecl *Lambda = Conv->getParent();
10884 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10885 // If we are defining a specialization of a conversion to function-ptr
10886 // cache the deduced template arguments for this specialization
10887 // so that we can use them to retrieve the corresponding call-operator
10888 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010889 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10890
Faisal Vali571df122013-09-29 08:45:24 +000010891 // Retrieve the corresponding call-operator specialization.
10892 if (Lambda->isGenericLambda()) {
10893 assert(Conv->isFunctionTemplateSpecialization());
10894 FunctionTemplateDecl *CallOpTemplate =
10895 CallOp->getDescribedFunctionTemplate();
10896 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010897 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010898 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010899 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010900 InsertPos);
10901 assert(CallOpSpec &&
10902 "Conversion operator must have a corresponding call operator");
10903 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10904 }
10905 // Mark the call operator referenced (and add to pending instantiations
10906 // if necessary).
10907 // For both the conversion and static-invoker template specializations
10908 // we construct their body's in this function, so no need to add them
10909 // to the PendingInstantiations.
10910 MarkFunctionReferenced(CurrentLocation, CallOp);
10911
Eli Friedmaneaf34142012-10-18 20:14:08 +000010912 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010913 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010914
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010915 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010916 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10917 // ... and get the corresponding specialization for a generic lambda.
10918 if (Lambda->isGenericLambda()) {
10919 assert(DeducedTemplateArgs &&
10920 "Must have deduced template arguments from Conversion Operator");
10921 FunctionTemplateDecl *InvokeTemplate =
10922 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010923 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010924 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010925 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010926 InsertPos);
10927 assert(InvokeSpec &&
10928 "Must have a corresponding static invoker specialization");
10929 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10930 }
10931 // Construct the body of the conversion function { return __invoke; }.
10932 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010933 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010934 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010935 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010936 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10937 Conv->getLocation(),
10938 Conv->getLocation()));
10939
10940 Conv->markUsed(Context);
10941 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010942
Faisal Vali571df122013-09-29 08:45:24 +000010943 // Fill in the __invoke function with a dummy implementation. IR generation
10944 // will fill in the actual details.
10945 Invoker->markUsed(Context);
10946 Invoker->setReferenced();
10947 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10948
Douglas Gregord3b672c2012-02-16 01:06:16 +000010949 if (ASTMutationListener *L = getASTMutationListener()) {
10950 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010951 L->CompletedImplicitDefinition(Invoker);
10952 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010953}
10954
Faisal Vali571df122013-09-29 08:45:24 +000010955
10956
Douglas Gregord3b672c2012-02-16 01:06:16 +000010957void Sema::DefineImplicitLambdaToBlockPointerConversion(
10958 SourceLocation CurrentLocation,
10959 CXXConversionDecl *Conv)
10960{
Faisal Vali850da1a2013-09-29 17:08:32 +000010961 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010962
Eli Friedman276dd182013-09-05 00:02:25 +000010963 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010964
Eli Friedmaneaf34142012-10-18 20:14:08 +000010965 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010966 DiagnosticErrorTrap Trap(Diags);
10967
Douglas Gregored90df32012-02-22 05:02:47 +000010968 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010969 Expr *This = ActOnCXXThis(CurrentLocation).get();
10970 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010971
Eli Friedman98b01ed2012-03-01 04:01:32 +000010972 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10973 Conv->getLocation(),
10974 Conv, DerefThis);
10975
10976 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10977 // behavior. Note that only the general conversion function does this
10978 // (since it's unusable otherwise); in the case where we inline the
10979 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010980 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010981 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10982 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010983 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010984
10985 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010986 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010987 Conv->setInvalidDecl();
10988 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010989 }
Douglas Gregored90df32012-02-22 05:02:47 +000010990
Douglas Gregored90df32012-02-22 05:02:47 +000010991 // Create the return statement that returns the block from the conversion
10992 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010993 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010994 if (Return.isInvalid()) {
10995 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10996 Conv->setInvalidDecl();
10997 return;
10998 }
10999
11000 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011001 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011002 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011003 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011004 Conv->getLocation()));
11005
Douglas Gregored90df32012-02-22 05:02:47 +000011006 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011007 if (ASTMutationListener *L = getASTMutationListener()) {
11008 L->CompletedImplicitDefinition(Conv);
11009 }
11010}
11011
Douglas Gregord2f70072012-03-10 06:53:13 +000011012/// \brief Determine whether the given list arguments contains exactly one
11013/// "real" (non-default) argument.
11014static bool hasOneRealArgument(MultiExprArg Args) {
11015 switch (Args.size()) {
11016 case 0:
11017 return false;
11018
11019 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011020 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011021 return false;
11022
11023 // fall through
11024 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011025 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011026 }
11027
11028 return false;
11029}
11030
John McCalldadc5752010-08-24 06:29:42 +000011031ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011032Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011033 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011034 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011035 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011036 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011037 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011038 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011039 unsigned ConstructKind,
11040 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011041 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011042
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011043 // C++0x [class.copy]p34:
11044 // When certain criteria are met, an implementation is allowed to
11045 // omit the copy/move construction of a class object, even if the
11046 // copy/move constructor and/or destructor for the object have
11047 // side effects. [...]
11048 // - when a temporary class object that has not been bound to a
11049 // reference (12.2) would be copied/moved to a class object
11050 // with the same cv-unqualified type, the copy/move operation
11051 // can be omitted by constructing the temporary object
11052 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011053 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011054 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011055 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011056 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011057 }
Mike Stump11289f42009-09-09 15:08:12 +000011058
11059 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011060 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011061 IsListInitialization,
11062 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011063 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011064}
11065
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011066/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11067/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011068ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011069Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11070 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011071 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011072 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011073 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011074 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011075 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011076 unsigned ConstructKind,
11077 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011078 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011079 return CXXConstructExpr::Create(
11080 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011081 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11082 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011083 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11084 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011085}
11086
John McCall03c48482010-02-02 09:10:11 +000011087void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011088 if (VD->isInvalidDecl()) return;
11089
John McCall03c48482010-02-02 09:10:11 +000011090 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011091 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011092 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011093 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011094
Chandler Carruth86d17d32011-03-27 21:26:48 +000011095 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011096 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011097 CheckDestructorAccess(VD->getLocation(), Destructor,
11098 PDiag(diag::err_access_dtor_var)
11099 << VD->getDeclName()
11100 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011101 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011102
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011103 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011104 if (!VD->hasGlobalStorage()) return;
11105
11106 // Emit warning for non-trivial dtor in global scope (a real global,
11107 // class-static, function-static).
11108 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11109
11110 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011111 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011112 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011113}
11114
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011115/// \brief Given a constructor and the set of arguments provided for the
11116/// constructor, convert the arguments and add any required default arguments
11117/// to form a proper call to this constructor.
11118///
11119/// \returns true if an error occurred, false otherwise.
11120bool
11121Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11122 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011123 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011124 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011125 bool AllowExplicit,
11126 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011127 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11128 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011129 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011130
11131 const FunctionProtoType *Proto
11132 = Constructor->getType()->getAs<FunctionProtoType>();
11133 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011134 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011135
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011136 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011137 if (NumArgs < NumParams)
11138 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011139 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011140 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011141
11142 VariadicCallType CallType =
11143 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011144 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011145 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011146 Proto, 0,
11147 llvm::makeArrayRef(Args, NumArgs),
11148 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011149 CallType, AllowExplicit,
11150 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011151 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011152
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011153 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011154
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011155 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011156 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011157 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011158
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011159 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011160}
11161
Anders Carlssone363c8e2009-12-12 00:32:00 +000011162static inline bool
11163CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11164 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011165 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011166 if (isa<NamespaceDecl>(DC)) {
11167 return SemaRef.Diag(FnDecl->getLocation(),
11168 diag::err_operator_new_delete_declared_in_namespace)
11169 << FnDecl->getDeclName();
11170 }
11171
11172 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011173 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011174 return SemaRef.Diag(FnDecl->getLocation(),
11175 diag::err_operator_new_delete_declared_static)
11176 << FnDecl->getDeclName();
11177 }
11178
Anders Carlsson60659a82009-12-12 02:43:16 +000011179 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011180}
11181
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011182static inline bool
11183CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11184 CanQualType ExpectedResultType,
11185 CanQualType ExpectedFirstParamType,
11186 unsigned DependentParamTypeDiag,
11187 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011188 QualType ResultType =
11189 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011190
11191 // Check that the result type is not dependent.
11192 if (ResultType->isDependentType())
11193 return SemaRef.Diag(FnDecl->getLocation(),
11194 diag::err_operator_new_delete_dependent_result_type)
11195 << FnDecl->getDeclName() << ExpectedResultType;
11196
11197 // Check that the result type is what we expect.
11198 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11199 return SemaRef.Diag(FnDecl->getLocation(),
11200 diag::err_operator_new_delete_invalid_result_type)
11201 << FnDecl->getDeclName() << ExpectedResultType;
11202
11203 // A function template must have at least 2 parameters.
11204 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11205 return SemaRef.Diag(FnDecl->getLocation(),
11206 diag::err_operator_new_delete_template_too_few_parameters)
11207 << FnDecl->getDeclName();
11208
11209 // The function decl must have at least 1 parameter.
11210 if (FnDecl->getNumParams() == 0)
11211 return SemaRef.Diag(FnDecl->getLocation(),
11212 diag::err_operator_new_delete_too_few_parameters)
11213 << FnDecl->getDeclName();
11214
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011215 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011216 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11217 if (FirstParamType->isDependentType())
11218 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11219 << FnDecl->getDeclName() << ExpectedFirstParamType;
11220
11221 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011222 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011223 ExpectedFirstParamType)
11224 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11225 << FnDecl->getDeclName() << ExpectedFirstParamType;
11226
11227 return false;
11228}
11229
Anders Carlsson12308f42009-12-11 23:23:22 +000011230static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011231CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011232 // C++ [basic.stc.dynamic.allocation]p1:
11233 // A program is ill-formed if an allocation function is declared in a
11234 // namespace scope other than global scope or declared static in global
11235 // scope.
11236 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11237 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011238
11239 CanQualType SizeTy =
11240 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11241
11242 // C++ [basic.stc.dynamic.allocation]p1:
11243 // The return type shall be void*. The first parameter shall have type
11244 // std::size_t.
11245 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11246 SizeTy,
11247 diag::err_operator_new_dependent_param_type,
11248 diag::err_operator_new_param_type))
11249 return true;
11250
11251 // C++ [basic.stc.dynamic.allocation]p1:
11252 // The first parameter shall not have an associated default argument.
11253 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011254 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011255 diag::err_operator_new_default_arg)
11256 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11257
11258 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011259}
11260
11261static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011262CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011263 // C++ [basic.stc.dynamic.deallocation]p1:
11264 // A program is ill-formed if deallocation functions are declared in a
11265 // namespace scope other than global scope or declared static in global
11266 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011267 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11268 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011269
11270 // C++ [basic.stc.dynamic.deallocation]p2:
11271 // Each deallocation function shall return void and its first parameter
11272 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011273 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11274 SemaRef.Context.VoidPtrTy,
11275 diag::err_operator_delete_dependent_param_type,
11276 diag::err_operator_delete_param_type))
11277 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011278
Anders Carlsson12308f42009-12-11 23:23:22 +000011279 return false;
11280}
11281
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011282/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11283/// of this overloaded operator is well-formed. If so, returns false;
11284/// otherwise, emits appropriate diagnostics and returns true.
11285bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011286 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011287 "Expected an overloaded operator declaration");
11288
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011289 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11290
Mike Stump11289f42009-09-09 15:08:12 +000011291 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011292 // The allocation and deallocation functions, operator new,
11293 // operator new[], operator delete and operator delete[], are
11294 // described completely in 3.7.3. The attributes and restrictions
11295 // found in the rest of this subclause do not apply to them unless
11296 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011297 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011298 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011299
Anders Carlsson22f443f2009-12-12 00:26:23 +000011300 if (Op == OO_New || Op == OO_Array_New)
11301 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011302
11303 // C++ [over.oper]p6:
11304 // An operator function shall either be a non-static member
11305 // function or be a non-member function and have at least one
11306 // parameter whose type is a class, a reference to a class, an
11307 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011308 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11309 if (MethodDecl->isStatic())
11310 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011311 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011312 } else {
11313 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011314 for (auto Param : FnDecl->params()) {
11315 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011316 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11317 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011318 ClassOrEnumParam = true;
11319 break;
11320 }
11321 }
11322
Douglas Gregord69246b2008-11-17 16:14:12 +000011323 if (!ClassOrEnumParam)
11324 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011325 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011326 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011327 }
11328
11329 // C++ [over.oper]p8:
11330 // An operator function cannot have default arguments (8.3.6),
11331 // except where explicitly stated below.
11332 //
Mike Stump11289f42009-09-09 15:08:12 +000011333 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011334 // (C++ [over.call]p1).
11335 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011336 for (auto Param : FnDecl->params()) {
11337 if (Param->hasDefaultArg())
11338 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011339 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011340 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011341 }
11342 }
11343
Douglas Gregor6cf08062008-11-10 13:38:07 +000011344 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11345 { false, false, false }
11346#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11347 , { Unary, Binary, MemberOnly }
11348#include "clang/Basic/OperatorKinds.def"
11349 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011350
Douglas Gregor6cf08062008-11-10 13:38:07 +000011351 bool CanBeUnaryOperator = OperatorUses[Op][0];
11352 bool CanBeBinaryOperator = OperatorUses[Op][1];
11353 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011354
11355 // C++ [over.oper]p8:
11356 // [...] Operator functions cannot have more or fewer parameters
11357 // than the number required for the corresponding operator, as
11358 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011359 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011360 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011361 if (Op != OO_Call &&
11362 ((NumParams == 1 && !CanBeUnaryOperator) ||
11363 (NumParams == 2 && !CanBeBinaryOperator) ||
11364 (NumParams < 1) || (NumParams > 2))) {
11365 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011366 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011367 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011368 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011369 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011370 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011371 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011372 assert(CanBeBinaryOperator &&
11373 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011374 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011375 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011376
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011377 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011378 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011379 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011380
Douglas Gregord69246b2008-11-17 16:14:12 +000011381 // Overloaded operators other than operator() cannot be variadic.
11382 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011383 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011384 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011385 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011386 }
11387
11388 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011389 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11390 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011391 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011392 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011393 }
11394
11395 // C++ [over.inc]p1:
11396 // The user-defined function called operator++ implements the
11397 // prefix and postfix ++ operator. If this function is a member
11398 // function with no parameters, or a non-member function with one
11399 // parameter of class or enumeration type, it defines the prefix
11400 // increment operator ++ for objects of that type. If the function
11401 // is a member function with one parameter (which shall be of type
11402 // int) or a non-member function with two parameters (the second
11403 // of which shall be of type int), it defines the postfix
11404 // increment operator ++ for objects of that type.
11405 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11406 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011407 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011408
Richard Smith538b52a2014-01-30 22:24:05 +000011409 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11410 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011411 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011412 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011413 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011414 }
11415
Douglas Gregord69246b2008-11-17 16:14:12 +000011416 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011417}
Chris Lattner3b024a32008-12-17 07:09:26 +000011418
Alexis Huntc88db062010-01-13 09:01:02 +000011419/// CheckLiteralOperatorDeclaration - Check whether the declaration
11420/// of this literal operator function is well-formed. If so, returns
11421/// false; otherwise, emits appropriate diagnostics and returns true.
11422bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011423 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011424 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11425 << FnDecl->getDeclName();
11426 return true;
11427 }
11428
Richard Smith72eebee2012-03-04 09:41:16 +000011429 if (FnDecl->isExternC()) {
11430 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11431 return true;
11432 }
11433
Alexis Huntc88db062010-01-13 09:01:02 +000011434 bool Valid = false;
11435
Richard Smithbcc22fc2012-03-09 08:00:36 +000011436 // This might be the definition of a literal operator template.
11437 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11438 // This might be a specialization of a literal operator template.
11439 if (!TpDecl)
11440 TpDecl = FnDecl->getPrimaryTemplate();
11441
Richard Smithb8b41d32013-10-07 19:57:58 +000011442 // template <char...> type operator "" name() and
11443 // template <class T, T...> type operator "" name() are the only valid
11444 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011445 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011446 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011447 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011448 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11449 if (Params->size() == 1) {
11450 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011451 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011452
Alexis Hunt7dd26172010-04-07 23:11:06 +000011453 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011454 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11455 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11456 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011457 } else if (Params->size() == 2) {
11458 TemplateTypeParmDecl *PmType =
11459 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11460 NonTypeTemplateParmDecl *PmArgs =
11461 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11462
11463 // The second template parameter must be a parameter pack with the
11464 // first template parameter as its type.
11465 if (PmType && PmArgs &&
11466 !PmType->isTemplateParameterPack() &&
11467 PmArgs->isTemplateParameterPack()) {
11468 const TemplateTypeParmType *TArgs =
11469 PmArgs->getType()->getAs<TemplateTypeParmType>();
11470 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11471 TArgs->getIndex() == PmType->getIndex()) {
11472 Valid = true;
11473 if (ActiveTemplateInstantiations.empty())
11474 Diag(FnDecl->getLocation(),
11475 diag::ext_string_literal_operator_template);
11476 }
11477 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011478 }
11479 }
Richard Smith72eebee2012-03-04 09:41:16 +000011480 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011481 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011482 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11483
Richard Smith72eebee2012-03-04 09:41:16 +000011484 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011485
Alexis Hunt079a6f72010-04-07 22:57:35 +000011486 // unsigned long long int, long double, and any character type are allowed
11487 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011488 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11489 Context.hasSameType(T, Context.LongDoubleTy) ||
11490 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011491 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011492 Context.hasSameType(T, Context.Char16Ty) ||
11493 Context.hasSameType(T, Context.Char32Ty)) {
11494 if (++Param == FnDecl->param_end())
11495 Valid = true;
11496 goto FinishedParams;
11497 }
11498
Alexis Hunt079a6f72010-04-07 22:57:35 +000011499 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011500 const PointerType *PT = T->getAs<PointerType>();
11501 if (!PT)
11502 goto FinishedParams;
11503 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011504 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011505 goto FinishedParams;
11506 T = T.getUnqualifiedType();
11507
11508 // Move on to the second parameter;
11509 ++Param;
11510
11511 // If there is no second parameter, the first must be a const char *
11512 if (Param == FnDecl->param_end()) {
11513 if (Context.hasSameType(T, Context.CharTy))
11514 Valid = true;
11515 goto FinishedParams;
11516 }
11517
11518 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11519 // are allowed as the first parameter to a two-parameter function
11520 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011521 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011522 Context.hasSameType(T, Context.Char16Ty) ||
11523 Context.hasSameType(T, Context.Char32Ty)))
11524 goto FinishedParams;
11525
11526 // The second and final parameter must be an std::size_t
11527 T = (*Param)->getType().getUnqualifiedType();
11528 if (Context.hasSameType(T, Context.getSizeType()) &&
11529 ++Param == FnDecl->param_end())
11530 Valid = true;
11531 }
11532
11533 // FIXME: This diagnostic is absolutely terrible.
11534FinishedParams:
11535 if (!Valid) {
11536 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11537 << FnDecl->getDeclName();
11538 return true;
11539 }
11540
Richard Smith768cecc2012-03-09 08:16:22 +000011541 // A parameter-declaration-clause containing a default argument is not
11542 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011543 for (auto Param : FnDecl->params()) {
11544 if (Param->hasDefaultArg()) {
11545 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011546 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011547 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011548 break;
11549 }
11550 }
11551
Richard Smith0df56f42012-03-08 02:39:21 +000011552 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011553 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11554 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011555 // C++11 [usrlit.suffix]p1:
11556 // Literal suffix identifiers that do not start with an underscore
11557 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011558 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11559 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011560 }
Richard Smith0df56f42012-03-08 02:39:21 +000011561
Alexis Huntc88db062010-01-13 09:01:02 +000011562 return false;
11563}
11564
Douglas Gregor07665a62009-01-05 19:45:36 +000011565/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11566/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011567/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11568/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011569/// the '{' brace. Otherwise, this linkage specification does not
11570/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011571Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011572 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011573 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011574 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11575 if (!Lit->isAscii()) {
11576 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11577 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011578 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011579 }
11580
11581 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011582 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011583 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011584 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011585 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011586 Language = LinkageSpecDecl::lang_cxx;
11587 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011588 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11589 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011590 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011591 }
Mike Stump11289f42009-09-09 15:08:12 +000011592
Chris Lattner438e5012008-12-17 07:13:27 +000011593 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011594
Richard Smith4ee696d2014-02-17 23:25:27 +000011595 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11596 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011597 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011598 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011599 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011600 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011601}
11602
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011603/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011604/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11605/// valid, it's the position of the closing '}' brace in a linkage
11606/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011607Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011608 Decl *LinkageSpec,
11609 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011610 if (RBraceLoc.isValid()) {
11611 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11612 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011613 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011614 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011615 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011616}
11617
Michael Han84324352013-02-22 17:15:32 +000011618Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11619 AttributeList *AttrList,
11620 SourceLocation SemiLoc) {
11621 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11622 // Attribute declarations appertain to empty declaration so we handle
11623 // them here.
11624 if (AttrList)
11625 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011626
Michael Han84324352013-02-22 17:15:32 +000011627 CurContext->addDecl(ED);
11628 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011629}
11630
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011631/// \brief Perform semantic analysis for the variable declaration that
11632/// occurs within a C++ catch clause, returning the newly-created
11633/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011634VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011635 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011636 SourceLocation StartLoc,
11637 SourceLocation Loc,
11638 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011639 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011640 QualType ExDeclType = TInfo->getType();
11641
Sebastian Redl54c04d42008-12-22 19:15:10 +000011642 // Arrays and functions decay.
11643 if (ExDeclType->isArrayType())
11644 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11645 else if (ExDeclType->isFunctionType())
11646 ExDeclType = Context.getPointerType(ExDeclType);
11647
11648 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11649 // The exception-declaration shall not denote a pointer or reference to an
11650 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011651 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011652 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011653 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011654 Invalid = true;
11655 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011656
Sebastian Redl54c04d42008-12-22 19:15:10 +000011657 QualType BaseType = ExDeclType;
11658 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011659 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011660 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011661 BaseType = Ptr->getPointeeType();
11662 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011663 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011664 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011665 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011666 BaseType = Ref->getPointeeType();
11667 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011668 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011669 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011670 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011671 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011672 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011673
Mike Stump11289f42009-09-09 15:08:12 +000011674 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011675 RequireNonAbstractType(Loc, ExDeclType,
11676 diag::err_abstract_type_in_decl,
11677 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011678 Invalid = true;
11679
John McCall2ca705e2010-07-24 00:37:23 +000011680 // Only the non-fragile NeXT runtime currently supports C++ catches
11681 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011682 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011683 QualType T = ExDeclType;
11684 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11685 T = RT->getPointeeType();
11686
11687 if (T->isObjCObjectType()) {
11688 Diag(Loc, diag::err_objc_object_catch);
11689 Invalid = true;
11690 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011691 // FIXME: should this be a test for macosx-fragile specifically?
11692 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011693 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011694 }
11695 }
11696
Abramo Bagnaradff19302011-03-08 08:55:46 +000011697 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011698 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011699 ExDecl->setExceptionVariable(true);
11700
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011701 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011702 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011703 Invalid = true;
11704
Douglas Gregor750734c2011-07-06 18:14:43 +000011705 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011706 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011707 // Insulate this from anything else we might currently be parsing.
11708 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11709
Douglas Gregor6de584c2010-03-05 23:38:39 +000011710 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011711 // The object declared in an exception-declaration or, if the
11712 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011713 // copy-initialized (8.5) from the exception object. [...]
11714 // The object is destroyed when the handler exits, after the destruction
11715 // of any automatic objects initialized within the handler.
11716 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011717 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011718 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011719 QualType initType = ExDeclType;
11720
11721 InitializedEntity entity =
11722 InitializedEntity::InitializeVariable(ExDecl);
11723 InitializationKind initKind =
11724 InitializationKind::CreateCopy(Loc, SourceLocation());
11725
11726 Expr *opaqueValue =
11727 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011728 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11729 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011730 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011731 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011732 else {
11733 // If the constructor used was non-trivial, set this as the
11734 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011735 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011736 if (!construct->getConstructor()->isTrivial()) {
11737 Expr *init = MaybeCreateExprWithCleanups(construct);
11738 ExDecl->setInit(init);
11739 }
11740
11741 // And make sure it's destructable.
11742 FinalizeVarWithDestructor(ExDecl, recordType);
11743 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011744 }
11745 }
11746
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011747 if (Invalid)
11748 ExDecl->setInvalidDecl();
11749
11750 return ExDecl;
11751}
11752
11753/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11754/// handler.
John McCall48871652010-08-21 09:40:31 +000011755Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011756 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011757 bool Invalid = D.isInvalidType();
11758
11759 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011760 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11761 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011762 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11763 D.getIdentifierLoc());
11764 Invalid = true;
11765 }
11766
Sebastian Redl54c04d42008-12-22 19:15:10 +000011767 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011768 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011769 LookupOrdinaryName,
11770 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011771 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011772 // it contains any previous declaration, except for function parameters in
11773 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011774 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011775 if (isDeclInScope(PrevDecl, CurContext, S)) {
11776 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11777 << D.getIdentifier();
11778 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11779 Invalid = true;
11780 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011781 // Maybe we will complain about the shadowed template parameter.
11782 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011783 }
11784
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011785 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011786 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11787 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011788 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011789 }
11790
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011791 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011792 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011793 D.getIdentifierLoc(),
11794 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011795 if (Invalid)
11796 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011797
Sebastian Redl54c04d42008-12-22 19:15:10 +000011798 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011799 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011800 PushOnScopeChains(ExDecl, S);
11801 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011802 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011803
Douglas Gregor758a8692009-06-17 21:51:59 +000011804 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011805 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011806}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011807
Abramo Bagnaraea947882011-03-08 16:41:52 +000011808Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011809 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011810 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011811 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011812 StringLiteral *AssertMessage =
11813 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011814
Richard Smithded9c2e2012-07-11 22:37:56 +000011815 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011816 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011817
11818 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11819 AssertMessage, RParenLoc, false);
11820}
11821
11822Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11823 Expr *AssertExpr,
11824 StringLiteral *AssertMessage,
11825 SourceLocation RParenLoc,
11826 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011827 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011828 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11829 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011830 // In a static_assert-declaration, the constant-expression shall be a
11831 // constant expression that can be contextually converted to bool.
11832 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11833 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011834 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011835
Richard Smith902ca212011-12-14 23:32:26 +000011836 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011837 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011838 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011839 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011840 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011841
Richard Smithded9c2e2012-07-11 22:37:56 +000011842 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011843 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011844 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011845 if (AssertMessage)
11846 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011847 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011848 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011849 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011850 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011851 }
Mike Stump11289f42009-09-09 15:08:12 +000011852
Abramo Bagnaraea947882011-03-08 16:41:52 +000011853 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011854 AssertExpr, AssertMessage, RParenLoc,
11855 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011856
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011857 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011858 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011859}
Sebastian Redlf769df52009-03-24 22:27:57 +000011860
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011861/// \brief Perform semantic analysis of the given friend type declaration.
11862///
11863/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011864FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011865 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011866 TypeSourceInfo *TSInfo) {
11867 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11868
11869 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011870 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011871
Richard Smithc8239732011-10-18 21:39:00 +000011872 // C++03 [class.friend]p2:
11873 // An elaborated-type-specifier shall be used in a friend declaration
11874 // for a class.*
11875 //
11876 // * The class-key of the elaborated-type-specifier is required.
11877 if (!ActiveTemplateInstantiations.empty()) {
11878 // Do not complain about the form of friend template types during
11879 // template instantiation; we will already have complained when the
11880 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011881 } else {
11882 if (!T->isElaboratedTypeSpecifier()) {
11883 // If we evaluated the type to a record type, suggest putting
11884 // a tag in front.
11885 if (const RecordType *RT = T->getAs<RecordType>()) {
11886 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011887
11888 SmallString<16> InsertionText(" ");
11889 InsertionText += RD->getKindName();
11890
Nick Lewycky36722d22013-02-06 05:59:33 +000011891 Diag(TypeRange.getBegin(),
11892 getLangOpts().CPlusPlus11 ?
11893 diag::warn_cxx98_compat_unelaborated_friend_type :
11894 diag::ext_unelaborated_friend_type)
11895 << (unsigned) RD->getTagKind()
11896 << T
11897 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11898 InsertionText);
11899 } else {
11900 Diag(FriendLoc,
11901 getLangOpts().CPlusPlus11 ?
11902 diag::warn_cxx98_compat_nonclass_type_friend :
11903 diag::ext_nonclass_type_friend)
11904 << T
11905 << TypeRange;
11906 }
11907 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011908 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011909 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011910 diag::warn_cxx98_compat_enum_friend :
11911 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011912 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011913 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011914 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011915
Nick Lewycky36722d22013-02-06 05:59:33 +000011916 // C++11 [class.friend]p3:
11917 // A friend declaration that does not declare a function shall have one
11918 // of the following forms:
11919 // friend elaborated-type-specifier ;
11920 // friend simple-type-specifier ;
11921 // friend typename-specifier ;
11922 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11923 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11924 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011925
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011926 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011927 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011928 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011929 return FriendDecl::Create(Context, CurContext,
11930 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11931 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011932}
11933
John McCallace48cd2010-10-19 01:40:49 +000011934/// Handle a friend tag declaration where the scope specifier was
11935/// templated.
11936Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11937 unsigned TagSpec, SourceLocation TagLoc,
11938 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011939 IdentifierInfo *Name,
11940 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011941 AttributeList *Attr,
11942 MultiTemplateParamsArg TempParamLists) {
11943 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11944
11945 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011946 bool Invalid = false;
11947
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011948 if (TemplateParameterList *TemplateParams =
11949 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011950 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011951 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011952 if (TemplateParams->size() > 0) {
11953 // This is a declaration of a class template.
11954 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011955 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011956
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011957 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11958 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011959 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011960 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011961 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011962 } else {
11963 // The "template<>" header is extraneous.
11964 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11965 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11966 isExplicitSpecialization = true;
11967 }
11968 }
11969
Craig Topperc3ec1492014-05-26 06:22:03 +000011970 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011971
John McCallace48cd2010-10-19 01:40:49 +000011972 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011973 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011974 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011975 isAllExplicitSpecializations = false;
11976 break;
11977 }
11978 }
11979
11980 // FIXME: don't ignore attributes.
11981
11982 // If it's explicit specializations all the way down, just forget
11983 // about the template header and build an appropriate non-templated
11984 // friend. TODO: for source fidelity, remember the headers.
11985 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011986 if (SS.isEmpty()) {
11987 bool Owned = false;
11988 bool IsDependent = false;
11989 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011990 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011991 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011992 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011993 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011994 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011995 /*UnderlyingType=*/TypeResult(),
11996 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011997 }
Richard Smith649c7b062014-01-08 00:56:48 +000011998
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011999 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012000 ElaboratedTypeKeyword Keyword
12001 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012002 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012003 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012004 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012005 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012006
12007 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12008 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012009 DependentNameTypeLoc TL =
12010 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012011 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012012 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012013 TL.setNameLoc(NameLoc);
12014 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012015 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012016 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012017 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012018 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012019 }
12020
12021 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012022 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012023 Friend->setAccess(AS_public);
12024 CurContext->addDecl(Friend);
12025 return Friend;
12026 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012027
12028 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12029
12030
John McCallace48cd2010-10-19 01:40:49 +000012031
12032 // Handle the case of a templated-scope friend class. e.g.
12033 // template <class T> class A<T>::B;
12034 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012035 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12036 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012037 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12038 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12039 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012040 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012041 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012042 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012043 TL.setNameLoc(NameLoc);
12044
12045 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012046 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012047 Friend->setAccess(AS_public);
12048 Friend->setUnsupportedFriend(true);
12049 CurContext->addDecl(Friend);
12050 return Friend;
12051}
12052
12053
John McCall11083da2009-09-16 22:47:08 +000012054/// Handle a friend type declaration. This works in tandem with
12055/// ActOnTag.
12056///
12057/// Notes on friend class templates:
12058///
12059/// We generally treat friend class declarations as if they were
12060/// declaring a class. So, for example, the elaborated type specifier
12061/// in a friend declaration is required to obey the restrictions of a
12062/// class-head (i.e. no typedefs in the scope chain), template
12063/// parameters are required to match up with simple template-ids, &c.
12064/// However, unlike when declaring a template specialization, it's
12065/// okay to refer to a template specialization without an empty
12066/// template parameter declaration, e.g.
12067/// friend class A<T>::B<unsigned>;
12068/// We permit this as a special case; if there are any template
12069/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012070/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012071Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012072 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012073 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012074
12075 assert(DS.isFriendSpecified());
12076 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12077
John McCall11083da2009-09-16 22:47:08 +000012078 // Try to convert the decl specifier to a type. This works for
12079 // friend templates because ActOnTag never produces a ClassTemplateDecl
12080 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012081 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012082 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12083 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012084 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012085 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012086
Douglas Gregor6c110f32010-12-16 01:14:37 +000012087 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012088 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012089
John McCall11083da2009-09-16 22:47:08 +000012090 // This is definitely an error in C++98. It's probably meant to
12091 // be forbidden in C++0x, too, but the specification is just
12092 // poorly written.
12093 //
12094 // The problem is with declarations like the following:
12095 // template <T> friend A<T>::foo;
12096 // where deciding whether a class C is a friend or not now hinges
12097 // on whether there exists an instantiation of A that causes
12098 // 'foo' to equal C. There are restrictions on class-heads
12099 // (which we declare (by fiat) elaborated friend declarations to
12100 // be) that makes this tractable.
12101 //
12102 // FIXME: handle "template <> friend class A<T>;", which
12103 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012104 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012105 Diag(Loc, diag::err_tagless_friend_type_template)
12106 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012107 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012108 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012109
John McCallaa74a0c2009-08-28 07:59:38 +000012110 // C++98 [class.friend]p1: A friend of a class is a function
12111 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012112 // This is fixed in DR77, which just barely didn't make the C++03
12113 // deadline. It's also a very silly restriction that seriously
12114 // affects inner classes and which nobody else seems to implement;
12115 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012116 //
12117 // But note that we could warn about it: it's always useless to
12118 // friend one of your own members (it's not, however, worthless to
12119 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012120
John McCall11083da2009-09-16 22:47:08 +000012121 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012122 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012123 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012124 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012125 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012126 TSI,
John McCall11083da2009-09-16 22:47:08 +000012127 DS.getFriendSpecLoc());
12128 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012129 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012130
12131 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012132 return nullptr;
12133
John McCall11083da2009-09-16 22:47:08 +000012134 D->setAccess(AS_public);
12135 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012136
John McCall48871652010-08-21 09:40:31 +000012137 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012138}
12139
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012140NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12141 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012142 const DeclSpec &DS = D.getDeclSpec();
12143
12144 assert(DS.isFriendSpecified());
12145 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12146
12147 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012148 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012149
12150 // C++ [class.friend]p1
12151 // A friend of a class is a function or class....
12152 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012153 // It *doesn't* see through dependent types, which is correct
12154 // according to [temp.arg.type]p3:
12155 // If a declaration acquires a function type through a
12156 // type dependent on a template-parameter and this causes
12157 // a declaration that does not use the syntactic form of a
12158 // function declarator to have a function type, the program
12159 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012160 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012161 Diag(Loc, diag::err_unexpected_friend);
12162
12163 // It might be worthwhile to try to recover by creating an
12164 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012165 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012166 }
12167
12168 // C++ [namespace.memdef]p3
12169 // - If a friend declaration in a non-local class first declares a
12170 // class or function, the friend class or function is a member
12171 // of the innermost enclosing namespace.
12172 // - The name of the friend is not found by simple name lookup
12173 // until a matching declaration is provided in that namespace
12174 // scope (either before or after the class declaration granting
12175 // friendship).
12176 // - If a friend function is called, its name may be found by the
12177 // name lookup that considers functions from namespaces and
12178 // classes associated with the types of the function arguments.
12179 // - When looking for a prior declaration of a class or a function
12180 // declared as a friend, scopes outside the innermost enclosing
12181 // namespace scope are not considered.
12182
John McCallde3fd222010-10-12 23:13:28 +000012183 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012184 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12185 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012186 assert(Name);
12187
Douglas Gregor6c110f32010-12-16 01:14:37 +000012188 // Check for unexpanded parameter packs.
12189 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12190 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12191 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012192 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012193
John McCall07e91c02009-08-06 02:15:43 +000012194 // The context we found the declaration in, or in which we should
12195 // create the declaration.
12196 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012197 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012198 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012199 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012200
Richard Smith114394f2013-08-09 04:35:01 +000012201 // There are five cases here.
12202 // - There's no scope specifier and we're in a local class. Only look
12203 // for functions declared in the immediately-enclosing block scope.
12204 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012205 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012206 if ((SS.isInvalid() || !SS.isSet()) &&
12207 (FunctionContainingLocalClass =
12208 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12209 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012210 // If a friend declaration appears in a local class and the name
12211 // specified is an unqualified name, a prior declaration is
12212 // looked up without considering scopes that are outside the
12213 // innermost enclosing non-class scope. For a friend function
12214 // declaration, if there is no prior declaration, the program is
12215 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012216
12217 // Find the innermost enclosing non-class scope. This is the block
12218 // scope containing the local class definition (or for a nested class,
12219 // the outer local class).
12220 DCScope = S->getFnParent();
12221
12222 // Look up the function name in the scope.
12223 Previous.clear(LookupLocalFriendName);
12224 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12225
12226 if (!Previous.empty()) {
12227 // All possible previous declarations must have the same context:
12228 // either they were declared at block scope or they are members of
12229 // one of the enclosing local classes.
12230 DC = Previous.getRepresentativeDecl()->getDeclContext();
12231 } else {
12232 // This is ill-formed, but provide the context that we would have
12233 // declared the function in, if we were permitted to, for error recovery.
12234 DC = FunctionContainingLocalClass;
12235 }
Richard Smith541b38b2013-09-20 01:15:31 +000012236 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012237
12238 // C++ [class.friend]p6:
12239 // A function can be defined in a friend declaration of a class if and
12240 // only if the class is a non-local class (9.8), the function name is
12241 // unqualified, and the function has namespace scope.
12242 if (D.isFunctionDefinition()) {
12243 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12244 }
12245
12246 // - There's no scope specifier, in which case we just go to the
12247 // appropriate scope and look for a function or function template
12248 // there as appropriate.
12249 } else if (SS.isInvalid() || !SS.isSet()) {
12250 // C++11 [namespace.memdef]p3:
12251 // If the name in a friend declaration is neither qualified nor
12252 // a template-id and the declaration is a function or an
12253 // elaborated-type-specifier, the lookup to determine whether
12254 // the entity has been previously declared shall not consider
12255 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012256 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012257
John McCallf7cfb222010-10-13 05:45:15 +000012258 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012259 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012260
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012261 // Skip class contexts. If someone can cite chapter and verse
12262 // for this behavior, that would be nice --- it's what GCC and
12263 // EDG do, and it seems like a reasonable intent, but the spec
12264 // really only says that checks for unqualified existing
12265 // declarations should stop at the nearest enclosing namespace,
12266 // not that they should only consider the nearest enclosing
12267 // namespace.
12268 while (DC->isRecord())
12269 DC = DC->getParent();
12270
12271 DeclContext *LookupDC = DC;
12272 while (LookupDC->isTransparentContext())
12273 LookupDC = LookupDC->getParent();
12274
12275 while (true) {
12276 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012277
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012278 if (!Previous.empty()) {
12279 DC = LookupDC;
12280 break;
John McCallf4776592010-10-14 22:22:28 +000012281 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012282
12283 if (isTemplateId) {
12284 if (isa<TranslationUnitDecl>(LookupDC)) break;
12285 } else {
12286 if (LookupDC->isFileContext()) break;
12287 }
12288 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012289 }
12290
John McCallccbc0322010-10-13 06:22:15 +000012291 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012292
John McCallde3fd222010-10-12 23:13:28 +000012293 // - There's a non-dependent scope specifier, in which case we
12294 // compute it and do a previous lookup there for a function
12295 // or function template.
12296 } else if (!SS.getScopeRep()->isDependent()) {
12297 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012298 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012299
Craig Topperc3ec1492014-05-26 06:22:03 +000012300 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012301
12302 LookupQualifiedName(Previous, DC);
12303
12304 // Ignore things found implicitly in the wrong scope.
12305 // TODO: better diagnostics for this case. Suggesting the right
12306 // qualified scope would be nice...
12307 LookupResult::Filter F = Previous.makeFilter();
12308 while (F.hasNext()) {
12309 NamedDecl *D = F.next();
12310 if (!DC->InEnclosingNamespaceSetOf(
12311 D->getDeclContext()->getRedeclContext()))
12312 F.erase();
12313 }
12314 F.done();
12315
12316 if (Previous.empty()) {
12317 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012318 Diag(Loc, diag::err_qualified_friend_not_found)
12319 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012320 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012321 }
12322
12323 // C++ [class.friend]p1: A friend of a class is a function or
12324 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012325 if (DC->Equals(CurContext))
12326 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012327 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012328 diag::warn_cxx98_compat_friend_is_member :
12329 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012330
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012331 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012332 // C++ [class.friend]p6:
12333 // A function can be defined in a friend declaration of a class if and
12334 // only if the class is a non-local class (9.8), the function name is
12335 // unqualified, and the function has namespace scope.
12336 SemaDiagnosticBuilder DB
12337 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12338
12339 DB << SS.getScopeRep();
12340 if (DC->isFileContext())
12341 DB << FixItHint::CreateRemoval(SS.getRange());
12342 SS.clear();
12343 }
John McCallde3fd222010-10-12 23:13:28 +000012344
12345 // - There's a scope specifier that does not match any template
12346 // parameter lists, in which case we use some arbitrary context,
12347 // create a method or method template, and wait for instantiation.
12348 // - There's a scope specifier that does match some template
12349 // parameter lists, which we don't handle right now.
12350 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012351 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012352 // C++ [class.friend]p6:
12353 // A function can be defined in a friend declaration of a class if and
12354 // only if the class is a non-local class (9.8), the function name is
12355 // unqualified, and the function has namespace scope.
12356 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12357 << SS.getScopeRep();
12358 }
12359
John McCallde3fd222010-10-12 23:13:28 +000012360 DC = CurContext;
12361 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012362 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012363
John McCallf7cfb222010-10-13 05:45:15 +000012364 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012365 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012366 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12367 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12368 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012369 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012370 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12371 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012372 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012373 }
John McCall07e91c02009-08-06 02:15:43 +000012374 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012375
Douglas Gregordd847ba2011-11-03 16:37:14 +000012376 // FIXME: This is an egregious hack to cope with cases where the scope stack
12377 // does not contain the declaration context, i.e., in an out-of-line
12378 // definition of a class.
12379 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12380 if (!DCScope) {
12381 FakeDCScope.setEntity(DC);
12382 DCScope = &FakeDCScope;
12383 }
Richard Smith114394f2013-08-09 04:35:01 +000012384
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012385 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012386 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012387 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012388 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012389
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012390 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012391
Richard Smith114394f2013-08-09 04:35:01 +000012392 // If we performed typo correction, we might have added a scope specifier
12393 // and changed the decl context.
12394 DC = ND->getDeclContext();
12395
John McCall759e32b2009-08-31 22:39:49 +000012396 // Add the function declaration to the appropriate lookup tables,
12397 // adjusting the redeclarations list as necessary. We don't
12398 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012399 //
John McCall759e32b2009-08-31 22:39:49 +000012400 // Also update the scope-based lookup if the target context's
12401 // lookup context is in lexical scope.
12402 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012403 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012404 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012405 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012406 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012407 }
John McCallaa74a0c2009-08-28 07:59:38 +000012408
12409 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012410 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012411 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012412 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012413 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012414
John McCalla0a96892012-08-10 03:15:35 +000012415 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012416 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012417 } else {
12418 if (DC->isRecord()) CheckFriendAccess(ND);
12419
John McCall2c2eb122010-10-16 06:59:13 +000012420 FunctionDecl *FD;
12421 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12422 FD = FTD->getTemplatedDecl();
12423 else
12424 FD = cast<FunctionDecl>(ND);
12425
David Majnemer502b0ed2013-06-25 23:09:30 +000012426 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12427 // default argument expression, that declaration shall be a definition
12428 // and shall be the only declaration of the function or function
12429 // template in the translation unit.
12430 if (functionDeclHasDefaultArgument(FD)) {
12431 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12432 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12433 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12434 } else if (!D.isFunctionDefinition())
12435 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12436 }
12437
John McCall2c2eb122010-10-16 06:59:13 +000012438 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012439 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12440 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12441 << SS.getScopeRep() << SS.getRange()
12442 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012443 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012444 }
John McCall2c2eb122010-10-16 06:59:13 +000012445 }
John McCallde3fd222010-10-12 23:13:28 +000012446
John McCall48871652010-08-21 09:40:31 +000012447 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012448}
12449
John McCall48871652010-08-21 09:40:31 +000012450void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12451 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012452
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012453 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012454 if (!Fn) {
12455 Diag(DelLoc, diag::err_deleted_non_function);
12456 return;
12457 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012458
Douglas Gregorec9fd132012-01-14 16:38:05 +000012459 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012460 // Don't consider the implicit declaration we generate for explicit
12461 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012462 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12463 Prev->getPreviousDecl()) &&
12464 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012465 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012466 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12467 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12468 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012469 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012470 // If the declaration wasn't the first, we delete the function anyway for
12471 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012472 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012473 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012474
Nico Rieck9de0a572014-05-29 16:51:19 +000012475 // dllimport/dllexport cannot be deleted.
12476 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12477 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12478 Fn->setInvalidDecl();
12479 }
12480
Richard Smithb4d2a152013-04-02 19:38:47 +000012481 if (Fn->isDeleted())
12482 return;
12483
12484 // See if we're deleting a function which is already known to override a
12485 // non-deleted virtual function.
12486 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12487 bool IssuedDiagnostic = false;
12488 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12489 E = MD->end_overridden_methods();
12490 I != E; ++I) {
12491 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12492 if (!IssuedDiagnostic) {
12493 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12494 IssuedDiagnostic = true;
12495 }
12496 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12497 }
12498 }
12499 }
12500
Richard Smithb63b6ee2014-01-22 01:43:19 +000012501 // C++11 [basic.start.main]p3:
12502 // A program that defines main as deleted [...] is ill-formed.
12503 if (Fn->isMain())
12504 Diag(DelLoc, diag::err_deleted_main);
12505
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012506 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012507}
Sebastian Redl4c018662009-04-27 21:33:24 +000012508
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012509void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012510 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012511
12512 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012513 if (MD->getParent()->isDependentType()) {
12514 MD->setDefaulted();
12515 MD->setExplicitlyDefaulted();
12516 return;
12517 }
12518
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012519 CXXSpecialMember Member = getSpecialMember(MD);
12520 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012521 if (!MD->isInvalidDecl())
12522 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012523 return;
12524 }
12525
12526 MD->setDefaulted();
12527 MD->setExplicitlyDefaulted();
12528
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012529 // If this definition appears within the record, do the checking when
12530 // the record is complete.
12531 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012532 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012533 // Find the uninstantiated declaration that actually had the '= default'
12534 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012535 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012536
Richard Smith3901dfe2013-03-27 00:22:47 +000012537 // If the method was defaulted on its first declaration, we will have
12538 // already performed the checking in CheckCompletedCXXClass. Such a
12539 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012540 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012541 return;
12542
Richard Smithd3b5c9082012-07-27 04:22:15 +000012543 CheckExplicitlyDefaultedSpecialMember(MD);
12544
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012545 if (MD->isInvalidDecl())
12546 return;
12547
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012548 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012549 case CXXDefaultConstructor:
12550 DefineImplicitDefaultConstructor(DefaultLoc,
12551 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012552 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012553 case CXXCopyConstructor:
12554 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012555 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012556 case CXXCopyAssignment:
12557 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012558 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012559 case CXXDestructor:
12560 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012561 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012562 case CXXMoveConstructor:
12563 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012564 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012565 case CXXMoveAssignment:
12566 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012567 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012568 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012569 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012570 }
12571 } else {
12572 Diag(DefaultLoc, diag::err_default_special_members);
12573 }
12574}
12575
Sebastian Redl4c018662009-04-27 21:33:24 +000012576static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012577 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012578 Stmt *SubStmt = *CI;
12579 if (!SubStmt)
12580 continue;
12581 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012582 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012583 diag::err_return_in_constructor_handler);
12584 if (!isa<Expr>(SubStmt))
12585 SearchForReturnInStmt(Self, SubStmt);
12586 }
12587}
12588
12589void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12590 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12591 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12592 SearchForReturnInStmt(*this, Handler);
12593 }
12594}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012595
David Blaikie68f71a32013-01-18 23:03:15 +000012596bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012597 const CXXMethodDecl *Old) {
12598 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12599 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12600
12601 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12602
12603 // If the calling conventions match, everything is fine
12604 if (NewCC == OldCC)
12605 return false;
12606
Hans Wennborg2545efe2013-12-11 17:42:11 +000012607 // If the calling conventions mismatch because the new function is static,
12608 // suppress the calling convention mismatch error; the error about static
12609 // function override (err_static_overrides_virtual from
12610 // Sema::CheckFunctionDeclaration) is more clear.
12611 if (New->getStorageClass() == SC_Static)
12612 return false;
12613
Reid Kleckner78af0702013-08-27 23:08:25 +000012614 Diag(New->getLocation(),
12615 diag::err_conflicting_overriding_cc_attributes)
12616 << New->getDeclName() << New->getType() << Old->getType();
12617 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12618 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012619}
12620
Mike Stump11289f42009-09-09 15:08:12 +000012621bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012622 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012623 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12624 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012625
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012626 if (Context.hasSameType(NewTy, OldTy) ||
12627 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012628 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012629
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012630 // Check if the return types are covariant
12631 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012632
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012633 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012634 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12635 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012636 NewClassTy = NewPT->getPointeeType();
12637 OldClassTy = OldPT->getPointeeType();
12638 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012639 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12640 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12641 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12642 NewClassTy = NewRT->getPointeeType();
12643 OldClassTy = OldRT->getPointeeType();
12644 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012645 }
12646 }
Mike Stump11289f42009-09-09 15:08:12 +000012647
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012648 // The return types aren't either both pointers or references to a class type.
12649 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012650 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012651 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012652 << New->getDeclName() << NewTy << OldTy
12653 << New->getReturnTypeSourceRange();
12654 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12655 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012656
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012657 return true;
12658 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012659
Anders Carlssone60365b2009-12-31 18:34:24 +000012660 // C++ [class.virtual]p6:
12661 // If the return type of D::f differs from the return type of B::f, the
12662 // class type in the return type of D::f shall be complete at the point of
12663 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012664 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12665 if (!RT->isBeingDefined() &&
12666 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012667 diag::err_covariant_return_incomplete,
12668 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012669 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012670 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012671
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012672 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012673 // Check if the new class derives from the old class.
12674 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012675 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12676 << New->getDeclName() << NewTy << OldTy
12677 << New->getReturnTypeSourceRange();
12678 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12679 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012680 return true;
12681 }
Mike Stump11289f42009-09-09 15:08:12 +000012682
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012683 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012684 if (CheckDerivedToBaseConversion(
12685 NewClassTy, OldClassTy,
12686 diag::err_covariant_return_inaccessible_base,
12687 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12688 New->getLocation(), New->getReturnTypeSourceRange(),
12689 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012690 // FIXME: this note won't trigger for delayed access control
12691 // diagnostics, and it's impossible to get an undelayed error
12692 // here from access control during the original parse because
12693 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012694 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12695 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012696 return true;
12697 }
12698 }
Mike Stump11289f42009-09-09 15:08:12 +000012699
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012700 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012701 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012702 Diag(New->getLocation(),
12703 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012704 << New->getDeclName() << NewTy << OldTy
12705 << New->getReturnTypeSourceRange();
12706 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12707 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012708 return true;
12709 };
Mike Stump11289f42009-09-09 15:08:12 +000012710
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012711
12712 // The new class type must have the same or less qualifiers as the old type.
12713 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12714 Diag(New->getLocation(),
12715 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012716 << New->getDeclName() << NewTy << OldTy
12717 << New->getReturnTypeSourceRange();
12718 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12719 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012720 return true;
12721 };
Mike Stump11289f42009-09-09 15:08:12 +000012722
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012723 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012724}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012725
Douglas Gregor21920e372009-12-01 17:24:26 +000012726/// \brief Mark the given method pure.
12727///
12728/// \param Method the method to be marked pure.
12729///
12730/// \param InitRange the source range that covers the "0" initializer.
12731bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012732 SourceLocation EndLoc = InitRange.getEnd();
12733 if (EndLoc.isValid())
12734 Method->setRangeEnd(EndLoc);
12735
Douglas Gregor21920e372009-12-01 17:24:26 +000012736 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12737 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012738 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012739 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012740
12741 if (!Method->isInvalidDecl())
12742 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12743 << Method->getDeclName() << InitRange;
12744 return true;
12745}
12746
Douglas Gregor926410d2012-02-21 02:22:07 +000012747/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012748static bool isStaticDataMember(const Decl *D) {
12749 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12750 return Var->isStaticDataMember();
12751
12752 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012753}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012754
John McCall1f4ee7b2009-12-19 09:28:58 +000012755/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12756/// an initializer for the out-of-line declaration 'Dcl'. The scope
12757/// is a fresh scope pushed for just this purpose.
12758///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012759/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12760/// static data member of class X, names should be looked up in the scope of
12761/// class X.
John McCall48871652010-08-21 09:40:31 +000012762void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012763 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012764 if (!D || D->isInvalidDecl())
12765 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012766
Richard Smitha2302242013-12-05 07:51:02 +000012767 // We will always have a nested name specifier here, but this declaration
12768 // might not be out of line if the specifier names the current namespace:
12769 // extern int n;
12770 // int ::n = 0;
12771 if (D->isOutOfLine())
12772 EnterDeclaratorContext(S, D->getDeclContext());
12773
Douglas Gregor926410d2012-02-21 02:22:07 +000012774 // If we are parsing the initializer for a static data member, push a
12775 // new expression evaluation context that is associated with this static
12776 // data member.
12777 if (isStaticDataMember(D))
12778 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012779}
12780
12781/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012782/// initializer for the out-of-line declaration 'D'.
12783void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012784 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012785 if (!D || D->isInvalidDecl())
12786 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012787
Douglas Gregor926410d2012-02-21 02:22:07 +000012788 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012789 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012790
Richard Smitha2302242013-12-05 07:51:02 +000012791 if (D->isOutOfLine())
12792 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012793}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012794
12795/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12796/// C++ if/switch/while/for statement.
12797/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012798DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012799 // C++ 6.4p2:
12800 // The declarator shall not specify a function or an array.
12801 // The type-specifier-seq shall not contain typedef and shall not declare a
12802 // new class or enumeration.
12803 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12804 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012805
12806 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012807 if (!Dcl)
12808 return true;
12809
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012810 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12811 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012812 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012813 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012814 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012815
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012816 return Dcl;
12817}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012818
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012819void Sema::LoadExternalVTableUses() {
12820 if (!ExternalSource)
12821 return;
12822
12823 SmallVector<ExternalVTableUse, 4> VTables;
12824 ExternalSource->ReadUsedVTables(VTables);
12825 SmallVector<VTableUse, 4> NewUses;
12826 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12827 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12828 = VTablesUsed.find(VTables[I].Record);
12829 // Even if a definition wasn't required before, it may be required now.
12830 if (Pos != VTablesUsed.end()) {
12831 if (!Pos->second && VTables[I].DefinitionRequired)
12832 Pos->second = true;
12833 continue;
12834 }
12835
12836 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12837 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12838 }
12839
12840 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12841}
12842
Douglas Gregor88d292c2010-05-13 16:44:06 +000012843void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12844 bool DefinitionRequired) {
12845 // Ignore any vtable uses in unevaluated operands or for classes that do
12846 // not have a vtable.
12847 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012848 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012849 return;
12850
Douglas Gregor88d292c2010-05-13 16:44:06 +000012851 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012852 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012853 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12854 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12855 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12856 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012857 // If we already had an entry, check to see if we are promoting this vtable
12858 // to required a definition. If so, we need to reappend to the VTableUses
12859 // list, since we may have already processed the first entry.
12860 if (DefinitionRequired && !Pos.first->second) {
12861 Pos.first->second = true;
12862 } else {
12863 // Otherwise, we can early exit.
12864 return;
12865 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012866 } else {
12867 // The Microsoft ABI requires that we perform the destructor body
12868 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12869 // the deleting destructor is emitted with the vtable, not with the
12870 // destructor definition as in the Itanium ABI.
12871 // If it has a definition, we do the check at that point instead.
12872 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12873 Class->hasUserDeclaredDestructor() &&
12874 !Class->getDestructor()->isDefined() &&
12875 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012876 CXXDestructorDecl *DD = Class->getDestructor();
12877 ContextRAII SavedContext(*this, DD);
12878 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012879 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012880 }
12881
12882 // Local classes need to have their virtual members marked
12883 // immediately. For all other classes, we mark their virtual members
12884 // at the end of the translation unit.
12885 if (Class->isLocalClass())
12886 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012887 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012888 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012889}
12890
Douglas Gregor88d292c2010-05-13 16:44:06 +000012891bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012892 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012893 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012894 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012895
Douglas Gregor88d292c2010-05-13 16:44:06 +000012896 // Note: The VTableUses vector could grow as a result of marking
12897 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012898 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012899 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012900 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012901 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012902 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012903 if (!Class)
12904 continue;
12905
12906 SourceLocation Loc = VTableUses[I].second;
12907
Richard Smithd3b5c9082012-07-27 04:22:15 +000012908 bool DefineVTable = true;
12909
Douglas Gregor88d292c2010-05-13 16:44:06 +000012910 // If this class has a key function, but that key function is
12911 // defined in another translation unit, we don't need to emit the
12912 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012913 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012914 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012915 // The key function is in another translation unit.
12916 DefineVTable = false;
12917 TemplateSpecializationKind TSK =
12918 KeyFunction->getTemplateSpecializationKind();
12919 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12920 TSK != TSK_ImplicitInstantiation &&
12921 "Instantiations don't have key functions");
12922 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012923 } else if (!KeyFunction) {
12924 // If we have a class with no key function that is the subject
12925 // of an explicit instantiation declaration, suppress the
12926 // vtable; it will live with the explicit instantiation
12927 // definition.
12928 bool IsExplicitInstantiationDeclaration
12929 = Class->getTemplateSpecializationKind()
12930 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012931 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012932 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012933 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012934 if (TSK == TSK_ExplicitInstantiationDeclaration)
12935 IsExplicitInstantiationDeclaration = true;
12936 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12937 IsExplicitInstantiationDeclaration = false;
12938 break;
12939 }
12940 }
12941
12942 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012943 DefineVTable = false;
12944 }
12945
12946 // The exception specifications for all virtual members may be needed even
12947 // if we are not providing an authoritative form of the vtable in this TU.
12948 // We may choose to emit it available_externally anyway.
12949 if (!DefineVTable) {
12950 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12951 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012952 }
12953
12954 // Mark all of the virtual members of this class as referenced, so
12955 // that we can build a vtable. Then, tell the AST consumer that a
12956 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012957 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012958 MarkVirtualMembersReferenced(Loc, Class);
12959 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12960 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12961
12962 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012963 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012964 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012965 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012966 if (!KeyFunction ||
12967 (KeyFunction->hasBody(KeyFunctionDef) &&
12968 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012969 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12970 TSK_ExplicitInstantiationDefinition
12971 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12972 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012973 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012974 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012975 VTableUses.clear();
12976
Douglas Gregor97509692011-04-22 22:25:37 +000012977 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012978}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012979
Richard Smithd3b5c9082012-07-27 04:22:15 +000012980void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12981 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012982 for (const auto *I : RD->methods())
12983 if (I->isVirtual() && !I->isPure())
12984 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012985}
12986
Rafael Espindola5b334082010-03-26 00:36:59 +000012987void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12988 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012989 // Mark all functions which will appear in RD's vtable as used.
12990 CXXFinalOverriderMap FinalOverriders;
12991 RD->getFinalOverriders(FinalOverriders);
12992 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12993 E = FinalOverriders.end();
12994 I != E; ++I) {
12995 for (OverridingMethods::const_iterator OI = I->second.begin(),
12996 OE = I->second.end();
12997 OI != OE; ++OI) {
12998 assert(OI->second.size() > 0 && "no final overrider");
12999 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013000
Richard Smith4ff9ff92012-07-07 06:59:51 +000013001 // C++ [basic.def.odr]p2:
13002 // [...] A virtual member function is used if it is not pure. [...]
13003 if (!Overrider->isPure())
13004 MarkFunctionReferenced(Loc, Overrider);
13005 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013006 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013007
13008 // Only classes that have virtual bases need a VTT.
13009 if (RD->getNumVBases() == 0)
13010 return;
13011
Aaron Ballman574705e2014-03-13 15:41:46 +000013012 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013013 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013014 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013015 if (Base->getNumVBases() == 0)
13016 continue;
13017 MarkVirtualMembersReferenced(Loc, Base);
13018 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013019}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013020
13021/// SetIvarInitializers - This routine builds initialization ASTs for the
13022/// Objective-C implementation whose ivars need be initialized.
13023void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013024 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013025 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013026 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013027 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013028 CollectIvarsToConstructOrDestruct(OID, ivars);
13029 if (ivars.empty())
13030 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013031 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013032 for (unsigned i = 0; i < ivars.size(); i++) {
13033 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013034 if (Field->isInvalidDecl())
13035 continue;
13036
Alexis Hunt1d792652011-01-08 20:30:50 +000013037 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013038 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13039 InitializationKind InitKind =
13040 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013041
13042 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13043 ExprResult MemberInit =
13044 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013045 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013046 // Note, MemberInit could actually come back empty if no initialization
13047 // is required (e.g., because it would call a trivial default constructor)
13048 if (!MemberInit.get() || MemberInit.isInvalid())
13049 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013050
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013051 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013052 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13053 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013054 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013055 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013056 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013057
13058 // Be sure that the destructor is accessible and is marked as referenced.
13059 if (const RecordType *RecordTy
13060 = Context.getBaseElementType(Field->getType())
13061 ->getAs<RecordType>()) {
13062 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013063 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013064 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013065 CheckDestructorAccess(Field->getLocation(), Destructor,
13066 PDiag(diag::err_access_dtor_ivar)
13067 << Context.getBaseElementType(Field->getType()));
13068 }
13069 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013070 }
13071 ObjCImplementation->setIvarInitializers(Context,
13072 AllToInit.data(), AllToInit.size());
13073 }
13074}
Alexis Hunt6118d662011-05-04 05:57:24 +000013075
Alexis Hunt27a761d2011-05-04 23:29:54 +000013076static
13077void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13078 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13079 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13080 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13081 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013082 if (Ctor->isInvalidDecl())
13083 return;
13084
Richard Smith802c4b72012-08-23 06:16:52 +000013085 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13086
13087 // Target may not be determinable yet, for instance if this is a dependent
13088 // call in an uninstantiated template.
13089 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013090 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013091 (void)Target->hasBody(FNTarget);
13092 Target = const_cast<CXXConstructorDecl*>(
13093 cast_or_null<CXXConstructorDecl>(FNTarget));
13094 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013095
13096 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13097 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013098 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013099
13100 if (!Current.insert(Canonical))
13101 return;
13102
13103 // We know that beyond here, we aren't chaining into a cycle.
13104 if (!Target || !Target->isDelegatingConstructor() ||
13105 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013106 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013107 Current.clear();
13108 // We've hit a cycle.
13109 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13110 Current.count(TCanonical)) {
13111 // If we haven't diagnosed this cycle yet, do so now.
13112 if (!Invalid.count(TCanonical)) {
13113 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013114 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013115 << Ctor;
13116
Richard Smith802c4b72012-08-23 06:16:52 +000013117 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013118 if (TCanonical != Canonical)
13119 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13120
13121 CXXConstructorDecl *C = Target;
13122 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013123 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013124 (void)C->getTargetConstructor()->hasBody(FNTarget);
13125 assert(FNTarget && "Ctor cycle through bodiless function");
13126
Richard Smith802c4b72012-08-23 06:16:52 +000013127 C = const_cast<CXXConstructorDecl*>(
13128 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013129 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13130 }
13131 }
13132
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013133 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013134 Current.clear();
13135 } else {
13136 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13137 }
13138}
13139
13140
Alexis Hunt6118d662011-05-04 05:57:24 +000013141void Sema::CheckDelegatingCtorCycles() {
13142 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13143
Douglas Gregorbae31202011-07-27 21:57:17 +000013144 for (DelegatingCtorDeclsType::iterator
13145 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013146 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013147 I != E; ++I)
13148 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013149
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013150 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13151 CE = Invalid.end();
13152 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013153 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013154}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013155
Douglas Gregor3024f072012-04-16 07:05:22 +000013156namespace {
13157 /// \brief AST visitor that finds references to the 'this' expression.
13158 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13159 Sema &S;
13160
13161 public:
13162 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13163
13164 bool VisitCXXThisExpr(CXXThisExpr *E) {
13165 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13166 << E->isImplicit();
13167 return false;
13168 }
13169 };
13170}
13171
13172bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13173 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13174 if (!TSInfo)
13175 return false;
13176
13177 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013178 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013179 if (!ProtoTL)
13180 return false;
13181
13182 // C++11 [expr.prim.general]p3:
13183 // [The expression this] shall not appear before the optional
13184 // cv-qualifier-seq and it shall not appear within the declaration of a
13185 // static member function (although its type and value category are defined
13186 // within a static member function as they are within a non-static member
13187 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013188 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013189 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013190 FindCXXThisExpr Finder(*this);
13191
13192 // If the return type came after the cv-qualifier-seq, check it now.
13193 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013194 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013195 return true;
13196
13197 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013198 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13199 return true;
13200
13201 return checkThisInStaticMemberFunctionAttributes(Method);
13202}
13203
13204bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13205 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13206 if (!TSInfo)
13207 return false;
13208
13209 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013210 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013211 if (!ProtoTL)
13212 return false;
13213
David Blaikie6adc78e2013-02-18 22:06:02 +000013214 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013215 FindCXXThisExpr Finder(*this);
13216
Douglas Gregor3024f072012-04-16 07:05:22 +000013217 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000013218 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013219 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013220 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013221 case EST_DynamicNone:
13222 case EST_MSAny:
13223 case EST_None:
13224 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013225
Douglas Gregor3024f072012-04-16 07:05:22 +000013226 case EST_ComputedNoexcept:
13227 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13228 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013229
Douglas Gregor3024f072012-04-16 07:05:22 +000013230 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013231 for (const auto &E : Proto->exceptions()) {
13232 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013233 return true;
13234 }
13235 break;
13236 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013237
13238 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013239}
13240
13241bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13242 FindCXXThisExpr Finder(*this);
13243
13244 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013245 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013246 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013247 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013248 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013249 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013250 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013251 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013252 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013253 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013254 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013255 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013256 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013257 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013258 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013259 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013260 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013261 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013262 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013263 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013264 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013265 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013266 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013267 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013268 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013269 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013270 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013271 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013272 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013273 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013274 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013275
13276 if (Arg && !Finder.TraverseStmt(Arg))
13277 return true;
13278
13279 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13280 if (!Finder.TraverseStmt(Args[I]))
13281 return true;
13282 }
13283 }
13284
13285 return false;
13286}
13287
NAKAMURA Takumi23224152014-10-17 12:48:37 +000013288void
13289Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13290 ArrayRef<ParsedType> DynamicExceptions,
13291 ArrayRef<SourceRange> DynamicExceptionRanges,
13292 Expr *NoexceptExpr,
13293 SmallVectorImpl<QualType> &Exceptions,
13294 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013295 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013296 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013297 if (EST == EST_Dynamic) {
13298 Exceptions.reserve(DynamicExceptions.size());
13299 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13300 // FIXME: Preserve type source info.
13301 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13302
NAKAMURA Takumi23224152014-10-17 12:48:37 +000013303 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13304 collectUnexpandedParameterPacks(ET, Unexpanded);
13305 if (!Unexpanded.empty()) {
13306 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13307 UPPC_ExceptionType,
13308 Unexpanded);
13309 continue;
Douglas Gregor433e0532012-04-16 18:27:27 +000013310 }
13311
13312 // Check that the type is valid for an exception spec, and
13313 // drop it if not.
13314 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13315 Exceptions.push_back(ET);
13316 }
Richard Smith8acb4282014-07-31 21:57:55 +000013317 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013318 return;
13319 }
Richard Smith8acb4282014-07-31 21:57:55 +000013320
Douglas Gregor433e0532012-04-16 18:27:27 +000013321 if (EST == EST_ComputedNoexcept) {
13322 // If an error occurred, there's no expression here.
13323 if (NoexceptExpr) {
13324 assert((NoexceptExpr->isTypeDependent() ||
13325 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13326 Context.BoolTy) &&
13327 "Parser should have made sure that the expression is boolean");
NAKAMURA Takumi23224152014-10-17 12:48:37 +000013328 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013329 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013330 return;
13331 }
Richard Smith8acb4282014-07-31 21:57:55 +000013332
Douglas Gregor433e0532012-04-16 18:27:27 +000013333 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013334 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013335 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013336 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013337 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013338 }
13339 return;
13340 }
13341}
13342
John McCall5e77d762013-04-16 07:28:30 +000013343/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13344///
13345MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13346 SourceLocation DeclStart,
13347 Declarator &D, Expr *BitWidth,
13348 InClassInitStyle InitStyle,
13349 AccessSpecifier AS,
13350 AttributeList *MSPropertyAttr) {
13351 IdentifierInfo *II = D.getIdentifier();
13352 if (!II) {
13353 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013354 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013355 }
13356 SourceLocation Loc = D.getIdentifierLoc();
13357
13358 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13359 QualType T = TInfo->getType();
13360 if (getLangOpts().CPlusPlus) {
13361 CheckExtraCXXDefaultArguments(D);
13362
13363 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13364 UPPC_DataMemberType)) {
13365 D.setInvalidType();
13366 T = Context.IntTy;
13367 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13368 }
13369 }
13370
13371 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13372
13373 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13374 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13375 diag::err_invalid_thread)
13376 << DeclSpec::getSpecifierName(TSCS);
13377
13378 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013379 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013380 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13381 LookupName(Previous, S);
13382 switch (Previous.getResultKind()) {
13383 case LookupResult::Found:
13384 case LookupResult::FoundUnresolvedValue:
13385 PrevDecl = Previous.getAsSingle<NamedDecl>();
13386 break;
13387
13388 case LookupResult::FoundOverloaded:
13389 PrevDecl = Previous.getRepresentativeDecl();
13390 break;
13391
13392 case LookupResult::NotFound:
13393 case LookupResult::NotFoundInCurrentInstantiation:
13394 case LookupResult::Ambiguous:
13395 break;
13396 }
13397
13398 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13399 // Maybe we will complain about the shadowed template parameter.
13400 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13401 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013402 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013403 }
13404
13405 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013406 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013407
13408 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013409 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013410 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13411 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013412 ProcessDeclAttributes(TUScope, NewPD, D);
13413 NewPD->setAccess(AS);
13414
13415 if (NewPD->isInvalidDecl())
13416 Record->setInvalidDecl();
13417
13418 if (D.getDeclSpec().isModulePrivateSpecified())
13419 NewPD->setModulePrivate();
13420
13421 if (NewPD->isInvalidDecl() && PrevDecl) {
13422 // Don't introduce NewFD into scope; there's already something
13423 // with the same name in the same scope.
13424 } else if (II) {
13425 PushOnScopeChains(NewPD, S);
13426 } else
13427 Record->addDecl(NewPD);
13428
13429 return NewPD;
13430}