blob: 7ed9bfcb9796f5b97de9402852c375ab644c7d54 [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"
Reid Klecknerd60b82f2014-11-17 23:36:45 +000039#include "clang/Sema/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000148}
Chris Lattner58258242008-04-10 02:22:51 +0000149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000272 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000319 }
320
321 // C++11 [dcl.fct.default]p3
322 // A default argument expression [...] shall not be specified for a
323 // parameter pack.
324 if (Param->isParameterPack()) {
325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326 << DefaultArg->getSourceRange();
327 return;
328 }
329
Anders Carlssonf1c26952009-08-25 01:02:06 +0000330 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000333 Param->setInvalidDecl();
334 return;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
John McCallb268a282010-08-23 23:25:46 +0000337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000338}
339
Douglas Gregor58354032008-12-24 00:01:03 +0000340/// ActOnParamUnparsedDefaultArgument - We've seen a default
341/// argument for a function parameter, but we can't parse it yet
342/// because we're inside a class definition. Note that this default
343/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000344void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000345 SourceLocation EqualLoc,
346 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000347 if (!param)
348 return;
Mike Stump11289f42009-09-09 15:08:12 +0000349
John McCall48871652010-08-21 09:40:31 +0000350 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000351 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000352 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000353}
354
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000357void Sema::ActOnParamDefaultArgumentError(Decl *param,
358 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000359 if (!param)
360 return;
Mike Stump11289f42009-09-09 15:08:12 +0000361
John McCall48871652010-08-21 09:40:31 +0000362 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000363 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000364 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000365 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000366 OpaqueValueExpr(EqualLoc,
367 Param->getType().getNonReferenceType(),
368 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000369}
370
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000371/// CheckExtraCXXDefaultArguments - Check for any extra default
372/// arguments in the declarator, which is not a function declaration
373/// or definition and therefore is not permitted to have default
374/// arguments. This routine should be invoked for every declarator
375/// that is not a function declaration or definition.
376void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377 // C++ [dcl.fct.default]p3
378 // A default argument expression shall be specified only in the
379 // parameter-declaration-clause of a function declaration or in a
380 // template-parameter (14.1). It shall not be specified for a
381 // parameter pack. If it is specified in a
382 // parameter-declaration-clause, it shall not occur within a
383 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000384 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000386 DeclaratorChunk &chunk = D.getTypeObject(i);
387 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000388 if (MightBeFunction) {
389 // This is a function declaration. It can have default arguments, but
390 // keep looking in case its return type is a function type with default
391 // arguments.
392 MightBeFunction = false;
393 continue;
394 }
Alp Tokerc5350722014-02-26 22:27:52 +0000395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396 ++argIdx) {
397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000398 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000399 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000407 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000408 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000409 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000410 } else if (Param->getDefaultArg()) {
411 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
412 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000413 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000414 }
415 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000416 } else if (chunk.Kind != DeclaratorChunk::Paren) {
417 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000418 }
419 }
420}
421
David Majnemer502b0ed2013-06-25 23:09:30 +0000422static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
423 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
424 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
425 if (!PVD->hasDefaultArg())
426 return false;
427 if (!PVD->hasInheritedDefaultArg())
428 return true;
429 }
430 return false;
431}
432
Craig Toppere4794282012-09-21 04:33:26 +0000433/// MergeCXXFunctionDecl - Merge two declarations of the same C++
434/// function, once we already know that they have the same
435/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
436/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000437bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
438 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000439 bool Invalid = false;
440
Richard Smithc7d48d12015-05-20 17:50:35 +0000441 // The declaration context corresponding to the scope is the semantic
442 // parent, unless this is a local function declaration, in which case
443 // it is that surrounding function.
444 DeclContext *ScopeDC = New->isLocalExternDecl()
445 ? New->getLexicalDeclContext()
446 : New->getDeclContext();
447
448 // Find the previous declaration for the purpose of default arguments.
449 FunctionDecl *PrevForDefaultArgs = Old;
450 for (/**/; PrevForDefaultArgs;
451 // Don't bother looking back past the latest decl if this is a local
452 // extern declaration; nothing else could work.
453 PrevForDefaultArgs = New->isLocalExternDecl()
454 ? nullptr
455 : PrevForDefaultArgs->getPreviousDecl()) {
456 // Ignore hidden declarations.
457 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
458 continue;
459
460 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
461 !New->isCXXClassMember()) {
462 // Ignore default arguments of old decl if they are not in
463 // the same scope and this is not an out-of-line definition of
464 // a member function.
465 continue;
466 }
467
468 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
469 // If only one of these is a local function declaration, then they are
470 // declared in different scopes, even though isDeclInScope may think
471 // they're in the same scope. (If both are local, the scope check is
472 // sufficent, and if neither is local, then they are in the same scope.)
473 continue;
474 }
475
476 // We found our guy.
477 break;
478 }
479
Chris Lattner199abbc2008-04-08 05:04:30 +0000480 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000481 // For non-template functions, default arguments can be added in
482 // later declarations of a function in the same
483 // scope. Declarations in different scopes have completely
484 // distinct sets of default arguments. That is, declarations in
485 // inner scopes do not acquire default arguments from
486 // declarations in outer scopes, and vice versa. In a given
487 // function declaration, all parameters subsequent to a
488 // parameter with a default argument shall have default
489 // arguments supplied in this or previous declarations. A
490 // default argument shall not be redefined by a later
491 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000492 //
493 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000494 // Except for member functions of class templates, the default arguments
495 // in a member function definition that appears outside of the class
496 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000498 for (unsigned p = 0, NumParams = PrevForDefaultArgs
499 ? PrevForDefaultArgs->getNumParams()
500 : 0;
501 p < NumParams; ++p) {
502 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000503 ParmVarDecl *NewParam = New->getParamDecl(p);
504
Richard Smithc7d48d12015-05-20 17:50:35 +0000505 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000506 bool NewParamHasDfl = NewParam->hasDefaultArg();
507
James Molloye9430032012-03-13 08:55:35 +0000508 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000509 unsigned DiagDefaultParamID =
510 diag::err_param_default_argument_redefinition;
511
512 // MSVC accepts that default parameters be redefined for member functions
513 // of template class. The new default parameter's value is ignored.
514 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000515 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000516 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000517 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000518 // Merge the old default argument into the new parameter.
519 NewParam->setHasInheritedDefaultArg();
520 if (OldParam->hasUninstantiatedDefaultArg())
521 NewParam->setUninstantiatedDefaultArg(
522 OldParam->getUninstantiatedDefaultArg());
523 else
524 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000525 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000526 Invalid = false;
527 }
528 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000529
Francois Pichet8cb243a2011-04-10 04:58:30 +0000530 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
531 // hint here. Alternatively, we could walk the type-source information
532 // for NewParam to find the last source location in the type... but it
533 // isn't worth the effort right now. This is the kind of test case that
534 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000535 // int f(int);
536 // void g(int (*fp)(int) = f);
537 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000538 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000539 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000540
541 // Look for the function declaration where the default argument was
542 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000543 for (auto Older = PrevForDefaultArgs;
544 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000546 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000547 }
548
Douglas Gregorc732aba2009-09-11 18:44:32 +0000549 Diag(OldParam->getLocation(), diag::note_previous_definition)
550 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000551 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000552 // Merge the old default argument into the new parameter.
553 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000554 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000555 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000556 if (OldParam->hasUnparsedDefaultArg())
557 NewParam->setUnparsedDefaultArg();
558 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000559 NewParam->setUninstantiatedDefaultArg(
560 OldParam->getUninstantiatedDefaultArg());
561 else
John McCalle61b02b2010-05-04 01:53:42 +0000562 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000563 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000564 if (New->getDescribedFunctionTemplate()) {
565 // Paragraph 4, quoted above, only applies to non-template functions.
566 Diag(NewParam->getLocation(),
567 diag::err_param_default_argument_template_redecl)
568 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000569 Diag(PrevForDefaultArgs->getLocation(),
570 diag::note_template_prev_declaration)
571 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000572 } else if (New->getTemplateSpecializationKind()
573 != TSK_ImplicitInstantiation &&
574 New->getTemplateSpecializationKind() != TSK_Undeclared) {
575 // C++ [temp.expr.spec]p21:
576 // Default function arguments shall not be specified in a declaration
577 // or a definition for one of the following explicit specializations:
578 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000579 // - the explicit specialization of a member function template;
580 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000581 // template where the class template specialization to which the
582 // member function specialization belongs is implicitly
583 // instantiated.
584 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
585 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
586 << New->getDeclName()
587 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000588 } else if (New->getDeclContext()->isDependentContext()) {
589 // C++ [dcl.fct.default]p6 (DR217):
590 // Default arguments for a member function of a class template shall
591 // be specified on the initial declaration of the member function
592 // within the class template.
593 //
594 // Reading the tea leaves a bit in DR217 and its reference to DR205
595 // leads me to the conclusion that one cannot add default function
596 // arguments for an out-of-line definition of a member function of a
597 // dependent type.
598 int WhichKind = 2;
599 if (CXXRecordDecl *Record
600 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
601 if (Record->getDescribedClassTemplate())
602 WhichKind = 0;
603 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
604 WhichKind = 1;
605 else
606 WhichKind = 2;
607 }
608
609 Diag(NewParam->getLocation(),
610 diag::err_param_default_argument_member_template_redecl)
611 << WhichKind
612 << NewParam->getDefaultArgRange();
613 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000614 }
615 }
616
Richard Smith58c3cc12012-11-28 03:45:24 +0000617 // DR1344: If a default argument is added outside a class definition and that
618 // default argument makes the function a special member function, the program
619 // is ill-formed. This can only happen for constructors.
620 if (isa<CXXConstructorDecl>(New) &&
621 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
622 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
623 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
624 if (NewSM != OldSM) {
625 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
626 assert(NewParam->hasDefaultArg());
627 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
628 << NewParam->getDefaultArgRange() << NewSM;
629 Diag(Old->getLocation(), diag::note_previous_declaration);
630 }
631 }
632
David Majnemeree4f4022014-03-30 06:44:54 +0000633 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000636 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000637 if (New->isConstexpr() != Old->isConstexpr()) {
638 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
639 << New << New->isConstexpr();
640 Diag(Old->getLocation(), diag::note_previous_declaration);
641 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000642 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
643 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000644 // C++11 [dcl.fcn.spec]p4:
645 // If the definition of a function appears in a translation unit before its
646 // first declaration as inline, the program is ill-formed.
647 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
648 Diag(Def->getLocation(), diag::note_previous_definition);
649 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000650 }
651
David Majnemer502b0ed2013-06-25 23:09:30 +0000652 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000653 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000654 // the only declaration of the function or function template in the
655 // translation unit.
656 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
657 functionDeclHasDefaultArgument(Old)) {
658 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
659 Diag(Old->getLocation(), diag::note_previous_declaration);
660 Invalid = true;
661 }
662
Douglas Gregorf40863c2010-02-12 07:32:17 +0000663 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000664 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000665
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000666 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000667}
668
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000669/// \brief Merge the exception specifications of two variable declarations.
670///
671/// This is called when there's a redeclaration of a VarDecl. The function
672/// checks if the redeclaration might have an exception specification and
673/// validates compatibility and merges the specs if necessary.
674void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
675 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000676 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000677 return;
678
679 assert(Context.hasSameType(New->getType(), Old->getType()) &&
680 "Should only be called if types are otherwise the same.");
681
682 QualType NewType = New->getType();
683 QualType OldType = Old->getType();
684
685 // We're only interested in pointers and references to functions, as well
686 // as pointers to member functions.
687 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
688 NewType = R->getPointeeType();
689 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
690 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
691 NewType = P->getPointeeType();
692 OldType = OldType->getAs<PointerType>()->getPointeeType();
693 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
694 NewType = M->getPointeeType();
695 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
696 }
697
698 if (!NewType->isFunctionProtoType())
699 return;
700
701 // There's lots of special cases for functions. For function pointers, system
702 // libraries are hopefully not as broken so that we don't need these
703 // workarounds.
704 if (CheckEquivalentExceptionSpec(
705 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
706 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
707 New->setInvalidDecl();
708 }
709}
710
Chris Lattner199abbc2008-04-08 05:04:30 +0000711/// CheckCXXDefaultArguments - Verify that the default arguments for a
712/// function declaration are well-formed according to C++
713/// [dcl.fct.default].
714void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
715 unsigned NumParams = FD->getNumParams();
716 unsigned p;
717
718 // Find first parameter with a default argument
719 for (p = 0; p < NumParams; ++p) {
720 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000721 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000722 break;
723 }
724
Benjamin Kramerfe257592015-03-27 13:58:41 +0000725 // C++11 [dcl.fct.default]p4:
726 // In a given function declaration, each parameter subsequent to a parameter
727 // with a default argument shall have a default argument supplied in this or
728 // a previous declaration or shall be a function parameter pack. A default
729 // argument shall not be redefined by a later declaration (not even to the
730 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +0000731 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000732 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000733 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +0000734 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000735 if (Param->isInvalidDecl())
736 /* We already complained about this parameter. */;
737 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000738 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000739 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000740 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000741 else
Mike Stump11289f42009-09-09 15:08:12 +0000742 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000743 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000744
Chris Lattner199abbc2008-04-08 05:04:30 +0000745 LastMissingDefaultArg = p;
746 }
747 }
748
749 if (LastMissingDefaultArg > 0) {
750 // Some default arguments were missing. Clear out all of the
751 // default arguments up to (and including) the last missing
752 // default argument, so that we leave the function parameters
753 // in a semantically valid state.
754 for (p = 0; p <= LastMissingDefaultArg; ++p) {
755 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000756 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000757 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000758 }
759 }
760 }
761}
Douglas Gregor556877c2008-04-13 21:30:24 +0000762
Richard Smitheb3c10c2011-10-01 02:31:28 +0000763// CheckConstexprParameterTypes - Check whether a function's parameter types
764// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000765// diagnostic and return false.
766static bool CheckConstexprParameterTypes(Sema &SemaRef,
767 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000768 unsigned ArgIndex = 0;
769 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000770 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
771 e = FT->param_type_end();
772 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
774 SourceLocation ParamLoc = PD->getLocation();
775 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000776 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000777 diag::err_constexpr_non_literal_param,
778 ArgIndex+1, PD->getSourceRange(),
779 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000780 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000782 return true;
783}
784
785/// \brief Get diagnostic %select index for tag kind for
786/// record diagnostic message.
787/// WARNING: Indexes apply to particular diagnostics only!
788///
789/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000790static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000791 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000792 case TTK_Struct: return 0;
793 case TTK_Interface: return 1;
794 case TTK_Class: return 2;
795 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000796 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000797}
798
799// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
800// the requirements of a constexpr function definition or a constexpr
801// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000802// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803//
Richard Smith3607ffe2012-02-13 03:54:03 +0000804// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
805bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000806 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
807 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 // C++11 [dcl.constexpr]p4:
809 // The definition of a constexpr constructor shall satisfy the following
810 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000812 const CXXRecordDecl *RD = MD->getParent();
813 if (RD->getNumVBases()) {
814 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
815 << isa<CXXConstructorDecl>(NewFD)
816 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000817 for (const auto &I : RD->vbases())
818 Diag(I.getLocStart(),
819 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 return false;
821 }
Richard Smith7971b692012-01-13 04:54:00 +0000822 }
823
824 if (!isa<CXXConstructorDecl>(NewFD)) {
825 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 // The definition of a constexpr function shall satisfy the following
827 // constraints:
828 // - it shall not be virtual;
829 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
830 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +0000831 Method = Method->getCanonicalDecl();
832 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000833
Richard Smith3607ffe2012-02-13 03:54:03 +0000834 // If it's not obvious why this function is virtual, find an overridden
835 // function which uses the 'virtual' keyword.
836 const CXXMethodDecl *WrittenVirtual = Method;
837 while (!WrittenVirtual->isVirtualAsWritten())
838 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
839 if (WrittenVirtual != Method)
840 Diag(WrittenVirtual->getLocation(),
841 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000842 return false;
843 }
844
845 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000846 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000847 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000848 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000849 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000850 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000851 }
852
Richard Smith7971b692012-01-13 04:54:00 +0000853 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000854 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000855 return false;
856
Richard Smitheb3c10c2011-10-01 02:31:28 +0000857 return true;
858}
859
860/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000861/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000862///
Richard Smithd9f663b2013-04-22 15:31:51 +0000863/// \return true if the body is OK (maybe only as an extension), false if we
864/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000865static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000866 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
867 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000868 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
869 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000870 for (const auto *DclIt : DS->decls()) {
871 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000872 case Decl::StaticAssert:
873 case Decl::Using:
874 case Decl::UsingShadow:
875 case Decl::UsingDirective:
876 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000877 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000878 // - static_assert-declarations
879 // - using-declarations,
880 // - using-directives,
881 continue;
882
883 case Decl::Typedef:
884 case Decl::TypeAlias: {
885 // - typedef declarations and alias-declarations that do not define
886 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000887 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000888 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
889 // Don't allow variably-modified types in constexpr functions.
890 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
891 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
892 << TL.getSourceRange() << TL.getType()
893 << isa<CXXConstructorDecl>(Dcl);
894 return false;
895 }
896 continue;
897 }
898
899 case Decl::Enum:
900 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000902 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000903 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000904 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000905 ? diag::warn_cxx11_compat_constexpr_type_definition
906 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000907 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000908 continue;
909
Richard Smithd9f663b2013-04-22 15:31:51 +0000910 case Decl::EnumConstant:
911 case Decl::IndirectField:
912 case Decl::ParmVar:
913 // These can only appear with other declarations which are banned in
914 // C++11 and permitted in C++1y, so ignore them.
915 continue;
916
917 case Decl::Var: {
918 // C++1y [dcl.constexpr]p3 allows anything except:
919 // a definition of a variable of non-literal type or of static or
920 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000921 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000922 if (VD->isThisDeclarationADefinition()) {
923 if (VD->isStaticLocal()) {
924 SemaRef.Diag(VD->getLocation(),
925 diag::err_constexpr_local_var_static)
926 << isa<CXXConstructorDecl>(Dcl)
927 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
928 return false;
929 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000930 if (!VD->getType()->isDependentType() &&
931 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000932 VD->getLocation(), VD->getType(),
933 diag::err_constexpr_local_var_non_literal_type,
934 isa<CXXConstructorDecl>(Dcl)))
935 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000936 if (!VD->getType()->isDependentType() &&
937 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000938 SemaRef.Diag(VD->getLocation(),
939 diag::err_constexpr_local_var_no_init)
940 << isa<CXXConstructorDecl>(Dcl);
941 return false;
942 }
943 }
944 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000945 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000946 ? diag::warn_cxx11_compat_constexpr_local_var
947 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000948 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000949 continue;
950 }
951
952 case Decl::NamespaceAlias:
953 case Decl::Function:
954 // These are disallowed in C++11 and permitted in C++1y. Allow them
955 // everywhere as an extension.
956 if (!Cxx1yLoc.isValid())
957 Cxx1yLoc = DS->getLocStart();
958 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959
960 default:
961 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
962 << isa<CXXConstructorDecl>(Dcl);
963 return false;
964 }
965 }
966
967 return true;
968}
969
970/// Check that the given field is initialized within a constexpr constructor.
971///
972/// \param Dcl The constexpr constructor being checked.
973/// \param Field The field being checked. This may be a member of an anonymous
974/// struct or union nested within the class being checked.
975/// \param Inits All declarations, including anonymous struct/union members and
976/// indirect members, for which any initialization was provided.
977/// \param Diagnosed Set to true if an error is produced.
978static void CheckConstexprCtorInitializer(Sema &SemaRef,
979 const FunctionDecl *Dcl,
980 FieldDecl *Field,
981 llvm::SmallSet<Decl*, 16> &Inits,
982 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000983 if (Field->isInvalidDecl())
984 return;
985
Douglas Gregor556e5862011-10-10 17:22:13 +0000986 if (Field->isUnnamedBitfield())
987 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000988
Richard Smithab44d5b2013-12-10 08:25:00 +0000989 // Anonymous unions with no variant members and empty anonymous structs do not
990 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
991 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000992 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000993 (Field->getType()->isUnionType()
994 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
995 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000996 return;
997
Richard Smitheb3c10c2011-10-01 02:31:28 +0000998 if (!Inits.count(Field)) {
999 if (!Diagnosed) {
1000 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1001 Diagnosed = true;
1002 }
1003 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1004 } else if (Field->isAnonymousStructOrUnion()) {
1005 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001006 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001007 // If an anonymous union contains an anonymous struct of which any member
1008 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001009 if (!RD->isUnion() || Inits.count(I))
1010 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001011 }
1012}
1013
Richard Smithd9f663b2013-04-22 15:31:51 +00001014/// Check the provided statement is allowed in a constexpr function
1015/// definition.
1016static bool
1017CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001018 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001019 SourceLocation &Cxx1yLoc) {
1020 // - its function-body shall be [...] a compound-statement that contains only
1021 switch (S->getStmtClass()) {
1022 case Stmt::NullStmtClass:
1023 // - null statements,
1024 return true;
1025
1026 case Stmt::DeclStmtClass:
1027 // - static_assert-declarations
1028 // - using-declarations,
1029 // - using-directives,
1030 // - typedef declarations and alias-declarations that do not define
1031 // classes or enumerations,
1032 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1033 return false;
1034 return true;
1035
1036 case Stmt::ReturnStmtClass:
1037 // - and exactly one return statement;
1038 if (isa<CXXConstructorDecl>(Dcl)) {
1039 // C++1y allows return statements in constexpr constructors.
1040 if (!Cxx1yLoc.isValid())
1041 Cxx1yLoc = S->getLocStart();
1042 return true;
1043 }
1044
1045 ReturnStmts.push_back(S->getLocStart());
1046 return true;
1047
1048 case Stmt::CompoundStmtClass: {
1049 // C++1y allows compound-statements.
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1052
1053 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001054 for (auto *BodyIt : CompStmt->body()) {
1055 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001056 Cxx1yLoc))
1057 return false;
1058 }
1059 return true;
1060 }
1061
1062 case Stmt::AttributedStmtClass:
1063 if (!Cxx1yLoc.isValid())
1064 Cxx1yLoc = S->getLocStart();
1065 return true;
1066
1067 case Stmt::IfStmtClass: {
1068 // C++1y allows if-statements.
1069 if (!Cxx1yLoc.isValid())
1070 Cxx1yLoc = S->getLocStart();
1071
1072 IfStmt *If = cast<IfStmt>(S);
1073 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1074 Cxx1yLoc))
1075 return false;
1076 if (If->getElse() &&
1077 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1078 Cxx1yLoc))
1079 return false;
1080 return true;
1081 }
1082
1083 case Stmt::WhileStmtClass:
1084 case Stmt::DoStmtClass:
1085 case Stmt::ForStmtClass:
1086 case Stmt::CXXForRangeStmtClass:
1087 case Stmt::ContinueStmtClass:
1088 // C++1y allows all of these. We don't allow them as extensions in C++11,
1089 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001090 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001091 break;
1092 if (!Cxx1yLoc.isValid())
1093 Cxx1yLoc = S->getLocStart();
1094 for (Stmt::child_range Children = S->children(); Children; ++Children)
1095 if (*Children &&
1096 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1097 Cxx1yLoc))
1098 return false;
1099 return true;
1100
1101 case Stmt::SwitchStmtClass:
1102 case Stmt::CaseStmtClass:
1103 case Stmt::DefaultStmtClass:
1104 case Stmt::BreakStmtClass:
1105 // C++1y allows switch-statements, and since they don't need variable
1106 // mutation, we can reasonably allow them in C++11 as an extension.
1107 if (!Cxx1yLoc.isValid())
1108 Cxx1yLoc = S->getLocStart();
1109 for (Stmt::child_range Children = S->children(); Children; ++Children)
1110 if (*Children &&
1111 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1112 Cxx1yLoc))
1113 return false;
1114 return true;
1115
1116 default:
1117 if (!isa<Expr>(S))
1118 break;
1119
1120 // C++1y allows expression-statements.
1121 if (!Cxx1yLoc.isValid())
1122 Cxx1yLoc = S->getLocStart();
1123 return true;
1124 }
1125
1126 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1127 << isa<CXXConstructorDecl>(Dcl);
1128 return false;
1129}
1130
Richard Smitheb3c10c2011-10-01 02:31:28 +00001131/// Check the body for the given constexpr function declaration only contains
1132/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1133///
1134/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001135bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001136 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001137 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 // The definition of a constexpr function shall satisfy the following
1139 // constraints: [...]
1140 // - its function-body shall be = delete, = default, or a
1141 // compound-statement
1142 //
Richard Smith74388b42012-02-04 00:33:54 +00001143 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001144 // In the definition of a constexpr constructor, [...]
1145 // - its function-body shall not be a function-try-block;
1146 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1147 << isa<CXXConstructorDecl>(Dcl);
1148 return false;
1149 }
1150
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001151 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001152
1153 // - its function-body shall be [...] a compound-statement that contains only
1154 // [... list of cases ...]
1155 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1156 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001157 for (auto *BodyIt : CompBody->body()) {
1158 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001159 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001160 }
1161
Richard Smithd9f663b2013-04-22 15:31:51 +00001162 if (Cxx1yLoc.isValid())
1163 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001164 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001165 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1166 : diag::ext_constexpr_body_invalid_stmt)
1167 << isa<CXXConstructorDecl>(Dcl);
1168
Richard Smitheb3c10c2011-10-01 02:31:28 +00001169 if (const CXXConstructorDecl *Constructor
1170 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1171 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001172 // DR1359:
1173 // - every non-variant non-static data member and base class sub-object
1174 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001175 // DR1460:
1176 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001177 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001178 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001179 if (Constructor->getNumCtorInitializers() == 0 &&
1180 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001181 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1182 return false;
1183 }
Richard Smithf368fb42011-10-10 16:38:04 +00001184 } else if (!Constructor->isDependentContext() &&
1185 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001186 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1187
1188 // Skip detailed checking if we have enough initializers, and we would
1189 // allow at most one initializer per member.
1190 bool AnyAnonStructUnionMembers = false;
1191 unsigned Fields = 0;
1192 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1193 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001194 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001195 AnyAnonStructUnionMembers = true;
1196 break;
1197 }
1198 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001199 // DR1460:
1200 // - if the class is a union-like class, but is not a union, for each of
1201 // its anonymous union members having variant members, exactly one of
1202 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001203 if (AnyAnonStructUnionMembers ||
1204 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1205 // Check initialization of non-static data members. Base classes are
1206 // always initialized so do not need to be checked. Dependent bases
1207 // might not have initializers in the member initializer list.
1208 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001209 for (const auto *I: Constructor->inits()) {
1210 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001211 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001212 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001213 Inits.insert(ID->chain_begin(), ID->chain_end());
1214 }
1215
1216 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001217 for (auto *I : RD->fields())
1218 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001219 if (Diagnosed)
1220 return false;
1221 }
1222 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001223 } else {
1224 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001225 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001226 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001227 // otherwise if there's no return statement, the function cannot
1228 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001229 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001230 (Dcl->getReturnType()->isVoidType() ||
1231 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001232 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001233 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1234 : diag::err_constexpr_body_no_return);
1235 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001236 }
1237 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001238 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001239 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001240 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1241 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001242 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1243 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001244 }
1245 }
1246
Richard Smith74388b42012-02-04 00:33:54 +00001247 // C++11 [dcl.constexpr]p5:
1248 // if no function argument values exist such that the function invocation
1249 // substitution would produce a constant expression, the program is
1250 // ill-formed; no diagnostic required.
1251 // C++11 [dcl.constexpr]p3:
1252 // - every constructor call and implicit conversion used in initializing the
1253 // return value shall be one of those allowed in a constant expression.
1254 // C++11 [dcl.constexpr]p4:
1255 // - every constructor involved in initializing non-static data members and
1256 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001257 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001258 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001259 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001260 << isa<CXXConstructorDecl>(Dcl);
1261 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1262 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001263 // Don't return false here: we allow this for compatibility in
1264 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001265 }
1266
Richard Smitheb3c10c2011-10-01 02:31:28 +00001267 return true;
1268}
1269
Douglas Gregor61956c42008-10-31 09:07:45 +00001270/// isCurrentClassName - Determine whether the identifier II is the
1271/// name of the class type currently being defined. In the case of
1272/// nested classes, this will only return true if II is the name of
1273/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001274bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1275 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001276 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001277
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001278 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001279 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001280 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1282 } else
1283 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1284
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001285 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001286 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001287 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001288}
1289
Richard Smithfb8b7b92013-10-15 00:00:26 +00001290/// \brief Determine whether the identifier II is a typo for the name of
1291/// the class type currently being defined. If so, update it to the identifier
1292/// that should have been used.
1293bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1294 assert(getLangOpts().CPlusPlus && "No class names in C!");
1295
1296 if (!getLangOpts().SpellChecking)
1297 return false;
1298
1299 CXXRecordDecl *CurDecl;
1300 if (SS && SS->isSet() && !SS->isInvalid()) {
1301 DeclContext *DC = computeDeclContext(*SS, true);
1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1303 } else
1304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1305
1306 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1307 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1308 < II->getLength()) {
1309 II = CurDecl->getIdentifier();
1310 return true;
1311 }
1312
1313 return false;
1314}
1315
Douglas Gregordc974572012-11-10 07:24:09 +00001316/// \brief Determine whether the given class is a base class of the given
1317/// class, including looking at dependent bases.
1318static bool findCircularInheritance(const CXXRecordDecl *Class,
1319 const CXXRecordDecl *Current) {
1320 SmallVector<const CXXRecordDecl*, 8> Queue;
1321
1322 Class = Class->getCanonicalDecl();
1323 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001324 for (const auto &I : Current->bases()) {
1325 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001326 if (!Base)
1327 continue;
1328
1329 Base = Base->getDefinition();
1330 if (!Base)
1331 continue;
1332
1333 if (Base->getCanonicalDecl() == Class)
1334 return true;
1335
1336 Queue.push_back(Base);
1337 }
1338
1339 if (Queue.empty())
1340 return false;
1341
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001342 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001343 }
1344
1345 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001346}
1347
Mike Stump11289f42009-09-09 15:08:12 +00001348/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001349///
1350/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1351/// and returns NULL otherwise.
1352CXXBaseSpecifier *
1353Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1354 SourceRange SpecifierRange,
1355 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001356 TypeSourceInfo *TInfo,
1357 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001358 QualType BaseType = TInfo->getType();
1359
Douglas Gregor463421d2009-03-03 04:44:36 +00001360 // C++ [class.union]p1:
1361 // A union shall not have base classes.
1362 if (Class->isUnion()) {
1363 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1364 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001365 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001366 }
1367
Douglas Gregor752a5952011-01-03 22:36:02 +00001368 if (EllipsisLoc.isValid() &&
1369 !TInfo->getType()->containsUnexpandedParameterPack()) {
1370 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1371 << TInfo->getTypeLoc().getSourceRange();
1372 EllipsisLoc = SourceLocation();
1373 }
Douglas Gregor62004702012-11-10 01:18:17 +00001374
1375 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1376
1377 if (BaseType->isDependentType()) {
1378 // Make sure that we don't have circular inheritance among our dependent
1379 // bases. For non-dependent bases, the check for completeness below handles
1380 // this.
1381 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1382 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1383 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001384 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001385 Diag(BaseLoc, diag::err_circular_inheritance)
1386 << BaseType << Context.getTypeDeclType(Class);
1387
1388 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1389 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1390 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001391
1392 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001393 }
1394 }
1395
Mike Stump11289f42009-09-09 15:08:12 +00001396 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001397 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001398 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001399 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001400
1401 // Base specifiers must be record types.
1402 if (!BaseType->isRecordType()) {
1403 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001404 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001405 }
1406
1407 // C++ [class.union]p1:
1408 // A union shall not be used as a base class.
1409 if (BaseType->isUnionType()) {
1410 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001411 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001412 }
1413
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001414 // For the MS ABI, propagate DLL attributes to base class templates.
1415 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1416 if (Attr *ClassAttr = getDLLAttr(Class)) {
1417 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1418 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00001419 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1420 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001421 }
1422 }
1423 }
1424
Douglas Gregor463421d2009-03-03 04:44:36 +00001425 // C++ [class.derived]p2:
1426 // The class-name in a base-specifier shall not be an incompletely
1427 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001428 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001429 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001430 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001431 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001432 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001433
Eli Friedmanc96d4962009-08-15 21:55:26 +00001434 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001435 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001436 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001437 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001438 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001439 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001440 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001441
David Majnemer9b1754d2013-11-02 12:00:36 +00001442 // A class which contains a flexible array member is not suitable for use as a
1443 // base class:
1444 // - If the layout determines that a base comes before another base,
1445 // the flexible array member would index into the subsequent base.
1446 // - If the layout determines that base comes before the derived class,
1447 // the flexible array member would index into the derived class.
1448 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1449 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1450 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001451 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001452 }
1453
Anders Carlsson65c76d32011-03-25 14:55:14 +00001454 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001455 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001456 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001457 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001458 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001459 << CXXBaseDecl->getDeclName()
1460 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001461 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1462 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001464 }
1465
John McCall3696dcb2010-08-17 07:23:57 +00001466 if (BaseDecl->isInvalidDecl())
1467 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001468
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001469 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001470 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001471 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001472 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001473}
1474
Douglas Gregor556877c2008-04-13 21:30:24 +00001475/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1476/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001477/// example:
1478/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001479/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001480BaseResult
John McCall48871652010-08-21 09:40:31 +00001481Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001482 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001483 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001484 ParsedType basetype, SourceLocation BaseLoc,
1485 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001486 if (!classdecl)
1487 return true;
1488
Douglas Gregorc40290e2009-03-09 23:48:35 +00001489 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001490 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001491 if (!Class)
1492 return true;
1493
David Majnemer5ef4fe72014-06-13 06:43:46 +00001494 // We haven't yet attached the base specifiers.
1495 Class->setIsParsingBaseSpecifiers();
1496
Richard Smith4c96e992013-02-19 23:47:15 +00001497 // We do not support any C++11 attributes on base-specifiers yet.
1498 // Diagnose any attributes we see.
1499 if (!Attributes.empty()) {
1500 for (AttributeList *Attr = Attributes.getList(); Attr;
1501 Attr = Attr->getNext()) {
1502 if (Attr->isInvalid() ||
1503 Attr->getKind() == AttributeList::IgnoredAttribute)
1504 continue;
1505 Diag(Attr->getLoc(),
1506 Attr->getKind() == AttributeList::UnknownAttribute
1507 ? diag::warn_unknown_attribute_ignored
1508 : diag::err_base_specifier_attribute)
1509 << Attr->getName();
1510 }
1511 }
1512
Craig Topperc3ec1492014-05-26 06:22:03 +00001513 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001514 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001515
Douglas Gregor752a5952011-01-03 22:36:02 +00001516 if (EllipsisLoc.isInvalid() &&
1517 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001518 UPPC_BaseType))
1519 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001520
Douglas Gregor463421d2009-03-03 04:44:36 +00001521 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001522 Virtual, Access, TInfo,
1523 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001524 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001525 else
1526 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001527
Douglas Gregor463421d2009-03-03 04:44:36 +00001528 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001529}
Douglas Gregor556877c2008-04-13 21:30:24 +00001530
Nathan Sidwell44b21742015-01-19 01:44:02 +00001531/// Use small set to collect indirect bases. As this is only used
1532/// locally, there's no need to abstract the small size parameter.
1533typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1534
1535/// \brief Recursively add the bases of Type. Don't add Type itself.
1536static void
1537NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1538 const QualType &Type)
1539{
1540 // Even though the incoming type is a base, it might not be
1541 // a class -- it could be a template parm, for instance.
1542 if (auto Rec = Type->getAs<RecordType>()) {
1543 auto Decl = Rec->getAsCXXRecordDecl();
1544
1545 // Iterate over its bases.
1546 for (const auto &BaseSpec : Decl->bases()) {
1547 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1548 .getUnqualifiedType();
1549 if (Set.insert(Base).second)
1550 // If we've not already seen it, recurse.
1551 NoteIndirectBases(Context, Set, Base);
1552 }
1553 }
1554}
1555
Douglas Gregor463421d2009-03-03 04:44:36 +00001556/// \brief Performs the actual work of attaching the given base class
1557/// specifiers to a C++ class.
1558bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1559 unsigned NumBases) {
1560 if (NumBases == 0)
1561 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001562
1563 // Used to keep track of which base types we have already seen, so
1564 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001565 // that the key is always the unqualified canonical type of the base
1566 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001567 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1568
Nathan Sidwell44b21742015-01-19 01:44:02 +00001569 // Used to track indirect bases so we can see if a direct base is
1570 // ambiguous.
1571 IndirectBaseSet IndirectBaseTypes;
1572
Douglas Gregor29a92472008-10-22 17:49:05 +00001573 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001574 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001575 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001576 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001577 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001578 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001579 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001580
1581 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1582 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001583 // C++ [class.mi]p3:
1584 // A class shall not be specified as a direct base class of a
1585 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001586 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001587 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001588 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001589 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001590
1591 // Delete the duplicate base class specifier; we're going to
1592 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001593 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001594
1595 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001596 } else {
1597 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001598 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001599 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001600
1601 // Note this base's direct & indirect bases, if there could be ambiguity.
1602 if (NumBases > 1)
1603 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1604
John McCalldb632ac2012-09-25 07:32:39 +00001605 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1606 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1607 if (Class->isInterface() &&
1608 (!RD->isInterface() ||
1609 KnownBase->getAccessSpecifier() != AS_public)) {
1610 // The Microsoft extension __interface does not permit bases that
1611 // are not themselves public interfaces.
1612 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1613 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1614 << RD->getSourceRange();
1615 Invalid = true;
1616 }
1617 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001618 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001619 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001620 }
1621 }
1622
1623 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001624 Class->setBases(Bases, NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001625
1626 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1627 // Check whether this direct base is inaccessible due to ambiguity.
1628 QualType BaseType = Bases[idx]->getType();
1629 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1630 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001631
Nathan Sidwell44b21742015-01-19 01:44:02 +00001632 if (IndirectBaseTypes.count(CanonicalBase)) {
1633 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1634 /*DetectVirtual=*/true);
1635 bool found
1636 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1637 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001638 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001639
1640 if (Paths.isAmbiguous(CanonicalBase))
1641 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1642 << BaseType << getAmbiguousPathsDisplayString(Paths)
1643 << Bases[idx]->getSourceRange();
1644 else
1645 assert(Bases[idx]->isVirtual());
1646 }
1647
1648 // Delete the base class specifier, since its data has been copied
1649 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001650 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001651 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001652
1653 return Invalid;
1654}
1655
1656/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1657/// class, after checking whether there are any duplicate base
1658/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001659void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001660 unsigned NumBases) {
1661 if (!ClassDecl || !Bases || !NumBases)
1662 return;
1663
1664 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001665 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001666}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001667
Douglas Gregor36d1b142009-10-06 17:59:45 +00001668/// \brief Determine whether the type \p Derived is a C++ class that is
1669/// derived from the type \p Base.
1670bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001671 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001672 return false;
John McCalle78aac42010-03-10 03:28:59 +00001673
Douglas Gregor45bb4832013-03-26 23:36:30 +00001674 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001675 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001676 return false;
1677
Douglas Gregor45bb4832013-03-26 23:36:30 +00001678 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001679 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001680 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001681
1682 // If either the base or the derived type is invalid, don't try to
1683 // check whether one is derived from the other.
1684 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1685 return false;
1686
John McCall67da35c2010-02-04 22:26:26 +00001687 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1688 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001689}
1690
1691/// \brief Determine whether the type \p Derived is a C++ class that is
1692/// derived from the type \p Base.
1693bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001694 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001695 return false;
1696
Douglas Gregor45bb4832013-03-26 23:36:30 +00001697 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001698 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001699 return false;
1700
Douglas Gregor45bb4832013-03-26 23:36:30 +00001701 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001702 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 return false;
1704
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1706}
1707
Anders Carlssona70cff62010-04-24 19:06:50 +00001708void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001709 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001710 assert(BasePathArray.empty() && "Base path array must be empty!");
1711 assert(Paths.isRecordingPaths() && "Must record paths!");
1712
1713 const CXXBasePath &Path = Paths.front();
1714
1715 // We first go backward and check if we have a virtual base.
1716 // FIXME: It would be better if CXXBasePath had the base specifier for
1717 // the nearest virtual base.
1718 unsigned Start = 0;
1719 for (unsigned I = Path.size(); I != 0; --I) {
1720 if (Path[I - 1].Base->isVirtual()) {
1721 Start = I - 1;
1722 break;
1723 }
1724 }
1725
1726 // Now add all bases.
1727 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001728 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001729}
1730
Douglas Gregor36d1b142009-10-06 17:59:45 +00001731/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1732/// conversion (where Derived and Base are class types) is
1733/// well-formed, meaning that the conversion is unambiguous (and
1734/// that all of the base classes are accessible). Returns true
1735/// and emits a diagnostic if the code is ill-formed, returns false
1736/// otherwise. Loc is the location where this routine should point to
1737/// if there is an error, and Range is the source range to highlight
1738/// if there is an error.
1739bool
1740Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001741 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001742 unsigned AmbigiousBaseConvID,
1743 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001744 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001745 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001746 // First, determine whether the path from Derived to Base is
1747 // ambiguous. This is slightly more expensive than checking whether
1748 // the Derived to Base conversion exists, because here we need to
1749 // explore multiple paths to determine if there is an ambiguity.
1750 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1751 /*DetectVirtual=*/false);
1752 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1753 assert(DerivationOkay &&
1754 "Can only be used with a derived-to-base conversion");
1755 (void)DerivationOkay;
1756
1757 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001758 if (InaccessibleBaseID) {
1759 // Check that the base class can be accessed.
1760 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1761 InaccessibleBaseID)) {
1762 case AR_inaccessible:
1763 return true;
1764 case AR_accessible:
1765 case AR_dependent:
1766 case AR_delayed:
1767 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001768 }
John McCall5b0829a2010-02-10 09:31:12 +00001769 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001770
1771 // Build a base path if necessary.
1772 if (BasePath)
1773 BuildBasePathArray(Paths, *BasePath);
1774 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001775 }
1776
David Majnemer626032f2013-06-22 06:43:58 +00001777 if (AmbigiousBaseConvID) {
1778 // We know that the derived-to-base conversion is ambiguous, and
1779 // we're going to produce a diagnostic. Perform the derived-to-base
1780 // search just one more time to compute all of the possible paths so
1781 // that we can print them out. This is more expensive than any of
1782 // the previous derived-to-base checks we've done, but at this point
1783 // performance isn't as much of an issue.
1784 Paths.clear();
1785 Paths.setRecordingPaths(true);
1786 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1787 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1788 (void)StillOkay;
1789
1790 // Build up a textual representation of the ambiguous paths, e.g.,
1791 // D -> B -> A, that will be used to illustrate the ambiguous
1792 // conversions in the diagnostic. We only print one of the paths
1793 // to each base class subobject.
1794 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1795
1796 Diag(Loc, AmbigiousBaseConvID)
1797 << Derived << Base << PathDisplayStr << Range << Name;
1798 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001799 return true;
1800}
1801
1802bool
1803Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001804 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001805 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001806 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001807 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001808 IgnoreAccess ? 0
1809 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001810 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001811 Loc, Range, DeclarationName(),
1812 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001813}
1814
1815
1816/// @brief Builds a string representing ambiguous paths from a
1817/// specific derived class to different subobjects of the same base
1818/// class.
1819///
1820/// This function builds a string that can be used in error messages
1821/// to show the different paths that one can take through the
1822/// inheritance hierarchy to go from the derived class to different
1823/// subobjects of a base class. The result looks something like this:
1824/// @code
1825/// struct D -> struct B -> struct A
1826/// struct D -> struct C -> struct A
1827/// @endcode
1828std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1829 std::string PathDisplayStr;
1830 std::set<unsigned> DisplayedPaths;
1831 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1832 Path != Paths.end(); ++Path) {
1833 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1834 // We haven't displayed a path to this particular base
1835 // class subobject yet.
1836 PathDisplayStr += "\n ";
1837 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1838 for (CXXBasePath::const_iterator Element = Path->begin();
1839 Element != Path->end(); ++Element)
1840 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1841 }
1842 }
1843
1844 return PathDisplayStr;
1845}
1846
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001847//===----------------------------------------------------------------------===//
1848// C++ class member Handling
1849//===----------------------------------------------------------------------===//
1850
Abramo Bagnarad7340582010-06-05 05:09:32 +00001851/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001852bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1853 SourceLocation ASLoc,
1854 SourceLocation ColonLoc,
1855 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001856 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001857 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001858 ASLoc, ColonLoc);
1859 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001860 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001861}
1862
Richard Smith18f07db2012-08-06 03:25:17 +00001863/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001864void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001865 if (D->isInvalidDecl())
1866 return;
1867
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001868 // We only care about "override" and "final" declarations.
1869 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1870 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001871
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001872 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001873
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001874 // We can't check dependent instance methods.
1875 if (MD && MD->isInstance() &&
1876 (MD->getParent()->hasAnyDependentBases() ||
1877 MD->getType()->isDependentType()))
1878 return;
1879
1880 if (MD && !MD->isVirtual()) {
1881 // If we have a non-virtual method, check if if hides a virtual method.
1882 // (In that case, it's most likely the method has the wrong type.)
1883 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1884 FindHiddenVirtualMethods(MD, OverloadedMethods);
1885
1886 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001887 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1888 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001889 diag::override_keyword_hides_virtual_member_function)
1890 << "override" << (OverloadedMethods.size() > 1);
1891 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001892 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001893 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001894 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1895 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001896 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001897 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1898 MD->setInvalidDecl();
1899 return;
1900 }
1901 // Fall through into the general case diagnostic.
1902 // FIXME: We might want to attempt typo correction here.
1903 }
1904
1905 if (!MD || !MD->isVirtual()) {
1906 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1907 Diag(OA->getLocation(),
1908 diag::override_keyword_only_allowed_on_virtual_member_functions)
1909 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1910 D->dropAttr<OverrideAttr>();
1911 }
1912 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1913 Diag(FA->getLocation(),
1914 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001915 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1916 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001917 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001918 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001919 return;
1920 }
Richard Smith18f07db2012-08-06 03:25:17 +00001921
Richard Smith18f07db2012-08-06 03:25:17 +00001922 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001923 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001924 // does not override a member function of a base class, the program is
1925 // ill-formed.
1926 bool HasOverriddenMethods =
1927 MD->begin_overridden_methods() != MD->end_overridden_methods();
1928 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1929 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1930 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001931}
1932
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001933void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1934 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1935 return;
1936 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1937 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1938 isa<CXXDestructorDecl>(MD))
1939 return;
1940
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001941 SourceLocation Loc = MD->getLocation();
1942 SourceLocation SpellingLoc = Loc;
1943 if (getSourceManager().isMacroArgExpansion(Loc))
1944 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1945 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1946 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001947 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001948
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001949 if (MD->size_overridden_methods() > 0) {
1950 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1951 << MD->getDeclName();
1952 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1953 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1954 }
1955}
1956
Richard Smith18f07db2012-08-06 03:25:17 +00001957/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001958/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001959/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001960bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1961 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001962 FinalAttr *FA = Old->getAttr<FinalAttr>();
1963 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001964 return false;
1965
1966 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001967 << New->getDeclName()
1968 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001969 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1970 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001971}
1972
Daniel Jasper0baec5492012-06-06 08:32:04 +00001973static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001974 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1975 // FIXME: Destruction of ObjC lifetime types has side-effects.
1976 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1977 return !RD->isCompleteDefinition() ||
1978 !RD->hasTrivialDefaultConstructor() ||
1979 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001980 return false;
1981}
1982
John McCall5e77d762013-04-16 07:28:30 +00001983static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001984 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001985 if (it->isDeclspecPropertyAttribute())
1986 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001987 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001988}
1989
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001990/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1991/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001992/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001993/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1994/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001995NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001996Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001997 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001998 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001999 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002000 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002001 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2002 DeclarationName Name = NameInfo.getName();
2003 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002004
2005 // For anonymous bitfields, the location should point to the type.
2006 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002007 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002008
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002009 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002010
John McCallb1cd7da2010-06-04 08:34:12 +00002011 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002012 assert(!DS.isFriendSpecified());
2013
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002014 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002015
John McCalldb632ac2012-09-25 07:32:39 +00002016 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2017 // The Microsoft extension __interface only permits public member functions
2018 // and prohibits constructors, destructors, operators, non-public member
2019 // functions, static methods and data members.
2020 unsigned InvalidDecl;
2021 bool ShowDeclName = true;
2022 if (!isFunc)
2023 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2024 else if (AS != AS_public)
2025 InvalidDecl = 2;
2026 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2027 InvalidDecl = 3;
2028 else switch (Name.getNameKind()) {
2029 case DeclarationName::CXXConstructorName:
2030 InvalidDecl = 4;
2031 ShowDeclName = false;
2032 break;
2033
2034 case DeclarationName::CXXDestructorName:
2035 InvalidDecl = 5;
2036 ShowDeclName = false;
2037 break;
2038
2039 case DeclarationName::CXXOperatorName:
2040 case DeclarationName::CXXConversionFunctionName:
2041 InvalidDecl = 6;
2042 break;
2043
2044 default:
2045 InvalidDecl = 0;
2046 break;
2047 }
2048
2049 if (InvalidDecl) {
2050 if (ShowDeclName)
2051 Diag(Loc, diag::err_invalid_member_in_interface)
2052 << (InvalidDecl-1) << Name;
2053 else
2054 Diag(Loc, diag::err_invalid_member_in_interface)
2055 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002056 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002057 }
2058 }
2059
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002060 // C++ 9.2p6: A member shall not be declared to have automatic storage
2061 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002062 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2063 // data members and cannot be applied to names declared const or static,
2064 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002065 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002066 case DeclSpec::SCS_unspecified:
2067 case DeclSpec::SCS_typedef:
2068 case DeclSpec::SCS_static:
2069 break;
2070 case DeclSpec::SCS_mutable:
2071 if (isFunc) {
2072 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Richard Smithb4a9e862013-04-12 22:46:28 +00002074 // FIXME: It would be nicer if the keyword was ignored only for this
2075 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002076 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002077 }
2078 break;
2079 default:
2080 Diag(DS.getStorageClassSpecLoc(),
2081 diag::err_storageclass_invalid_for_member);
2082 D.getMutableDeclSpec().ClearStorageClassSpecs();
2083 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002084 }
2085
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002086 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2087 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002088 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002089
David Blaikie35506f82013-01-30 01:22:18 +00002090 if (DS.isConstexprSpecified() && isInstField) {
2091 SemaDiagnosticBuilder B =
2092 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2093 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2094 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002095 B << 0 << 0;
2096 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2097 B << FixItHint::CreateRemoval(ConstexprLoc);
2098 else {
2099 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2100 D.getMutableDeclSpec().ClearConstexprSpec();
2101 const char *PrevSpec;
2102 unsigned DiagID;
2103 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2104 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2105 (void)Failed;
2106 assert(!Failed && "Making a constexpr member const shouldn't fail");
2107 }
David Blaikie35506f82013-01-30 01:22:18 +00002108 } else {
2109 B << 1;
2110 const char *PrevSpec;
2111 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002112 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002113 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2114 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002115 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002116 "This is the only DeclSpec that should fail to be applied");
2117 B << 1;
2118 } else {
2119 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2120 isInstField = false;
2121 }
2122 }
2123 }
2124
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002125 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002126 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002127 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002128
2129 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002130 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002131 Diag(Loc, diag::err_bad_variable_name)
2132 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002133 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002134 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002135
Benjamin Kramer365082d2012-05-19 16:34:46 +00002136 IdentifierInfo *II = Name.getAsIdentifierInfo();
2137
Douglas Gregor7c26c042011-09-21 14:40:46 +00002138 // Member field could not be with "template" keyword.
2139 // So TemplateParameterLists should be empty in this case.
2140 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002141 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002142 if (TemplateParams->size()) {
2143 // There is no such thing as a member field template.
2144 Diag(D.getIdentifierLoc(), diag::err_template_member)
2145 << II
2146 << SourceRange(TemplateParams->getTemplateLoc(),
2147 TemplateParams->getRAngleLoc());
2148 } else {
2149 // There is an extraneous 'template<>' for this member.
2150 Diag(TemplateParams->getTemplateLoc(),
2151 diag::err_template_member_noparams)
2152 << II
2153 << SourceRange(TemplateParams->getTemplateLoc(),
2154 TemplateParams->getRAngleLoc());
2155 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002156 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002157 }
2158
Douglas Gregora007d362010-10-13 22:19:53 +00002159 if (SS.isSet() && !SS.isInvalid()) {
2160 // The user provided a superfluous scope specifier inside a class
2161 // definition:
2162 //
2163 // class X {
2164 // int X::member;
2165 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002166 if (DeclContext *DC = computeDeclContext(SS, false))
2167 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002168 else
2169 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2170 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002171
Douglas Gregora007d362010-10-13 22:19:53 +00002172 SS.clear();
2173 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002174
John McCall5e77d762013-04-16 07:28:30 +00002175 AttributeList *MSPropertyAttr =
2176 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002177 if (MSPropertyAttr) {
2178 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2179 BitWidth, InitStyle, AS, MSPropertyAttr);
2180 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002181 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002182 isInstField = false;
2183 } else {
2184 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2185 BitWidth, InitStyle, AS);
2186 assert(Member && "HandleField never returns null");
2187 }
2188 } else {
Nico Webera089c7c2015-01-16 21:09:43 +00002189 assert(InitStyle == ICIS_NoInit ||
2190 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002191
2192 Member = HandleDeclarator(S, D, TemplateParameterLists);
2193 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002194 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002195
2196 // Non-instance-fields can't have a bitfield.
2197 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002198 if (Member->isInvalidDecl()) {
2199 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002200 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002201 // C++ 9.6p3: A bit-field shall not be a static member.
2202 // "static member 'A' cannot be a bit-field"
2203 Diag(Loc, diag::err_static_not_bitfield)
2204 << Name << BitWidth->getSourceRange();
2205 } else if (isa<TypedefDecl>(Member)) {
2206 // "typedef member 'x' cannot be a bit-field"
2207 Diag(Loc, diag::err_typedef_not_bitfield)
2208 << Name << BitWidth->getSourceRange();
2209 } else {
2210 // A function typedef ("typedef int f(); f a;").
2211 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2212 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002213 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002214 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Craig Topperc3ec1492014-05-26 06:22:03 +00002217 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002218 Member->setInvalidDecl();
2219 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002220
2221 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002222
Larisse Voufo39a1e502013-08-06 01:03:05 +00002223 // If we have declared a member function template or static data member
2224 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002225 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2226 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002227 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2228 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002229 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002230
Richard Smith18f07db2012-08-06 03:25:17 +00002231 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002232 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002233 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002234 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2235 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002236
Douglas Gregorf2f08062011-03-08 17:10:18 +00002237 if (VS.getLastLocation().isValid()) {
2238 // Update the end location of a method that has a virt-specifiers.
2239 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2240 MD->setRangeEnd(VS.getLastLocation());
2241 }
Richard Smith18f07db2012-08-06 03:25:17 +00002242
Anders Carlssonc87f8612011-01-20 06:29:02 +00002243 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002244
Douglas Gregor92751d42008-11-17 22:58:34 +00002245 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002246
Daniel Jasper0baec5492012-06-06 08:32:04 +00002247 if (isInstField) {
2248 FieldDecl *FD = cast<FieldDecl>(Member);
2249 FieldCollector->Add(FD);
2250
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002251 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002252 // Remember all explicit private FieldDecls that have a name, no side
2253 // effects and are not part of a dependent type declaration.
2254 if (!FD->isImplicit() && FD->getDeclName() &&
2255 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002256 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002257 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002258 !InitializationHasSideEffects(*FD))
2259 UnusedPrivateFields.insert(FD);
2260 }
2261 }
2262
John McCall48871652010-08-21 09:40:31 +00002263 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002264}
2265
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002266namespace {
2267 class UninitializedFieldVisitor
2268 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2269 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002270 // List of Decls to generate a warning on. Also remove Decls that become
2271 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002272 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002273 // List of base classes of the record. Classes are removed after their
2274 // initializers.
2275 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002276 // Vector of decls to be removed from the Decl set prior to visiting the
2277 // nodes. These Decls may have been initialized in the prior initializer.
2278 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002279 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002280 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002281 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002282 // InitList is true, special case initialization of FieldDecls matching
2283 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002284 bool InitList;
2285 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002286 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2287
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002288 public:
2289 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002290 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002291 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2292 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2293 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2294 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002295
Richard Trieufa1d0a72014-10-17 20:56:10 +00002296 // Returns true if the use of ME is not an uninitialized use.
2297 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2298 bool CheckReferenceOnly) {
2299 llvm::SmallVector<FieldDecl*, 4> Fields;
2300 bool ReferenceField = false;
2301 while (ME) {
2302 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2303 if (!FD)
2304 return false;
2305 Fields.push_back(FD);
2306 if (FD->getType()->isReferenceType())
2307 ReferenceField = true;
2308 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2309 }
2310
2311 // Binding a reference to an unintialized field is not an
2312 // uninitialized use.
2313 if (CheckReferenceOnly && !ReferenceField)
2314 return true;
2315
2316 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2317 // Discard the first field since it is the field decl that is being
2318 // initialized.
2319 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2320 UsedFieldIndex.push_back((*I)->getFieldIndex());
2321 }
2322
2323 for (auto UsedIter = UsedFieldIndex.begin(),
2324 UsedEnd = UsedFieldIndex.end(),
2325 OrigIter = InitFieldIndex.begin(),
2326 OrigEnd = InitFieldIndex.end();
2327 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2328 if (*UsedIter < *OrigIter)
2329 return true;
2330 if (*UsedIter > *OrigIter)
2331 break;
2332 }
2333
2334 return false;
2335 }
2336
Richard Trieu2d779b92014-10-01 03:44:58 +00002337 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2338 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002339 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2340 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002341
Richard Trieu1bc22c12013-09-13 03:20:53 +00002342 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2343 // or union.
2344 MemberExpr *FieldME = ME;
2345
Richard Trieu2d779b92014-10-01 03:44:58 +00002346 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2347
Richard Trieu1bc22c12013-09-13 03:20:53 +00002348 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002349 while (MemberExpr *SubME =
2350 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002351
Richard Trieufa1d0a72014-10-17 20:56:10 +00002352 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002353 return;
2354
Richard Trieufa1d0a72014-10-17 20:56:10 +00002355 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002356 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002357 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002358
Richard Trieu2d779b92014-10-01 03:44:58 +00002359 if (!FieldME->getType().isPODType(S.Context))
2360 AllPODFields = false;
2361
Richard Trieu3630c392014-11-21 03:10:30 +00002362 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002363 }
2364
Richard Trieu3630c392014-11-21 03:10:30 +00002365 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002366 return;
2367
Richard Trieu2d779b92014-10-01 03:44:58 +00002368 if (AddressOf && AllPODFields)
2369 return;
2370
Richard Trieu406e65c2013-09-20 03:03:06 +00002371 ValueDecl* FoundVD = FieldME->getMemberDecl();
2372
Richard Trieu3630c392014-11-21 03:10:30 +00002373 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2374 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2375 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2376 }
2377
2378 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2379 QualType T = BaseCast->getType();
2380 if (T->isPointerType() &&
2381 BaseClasses.count(T->getPointeeType())) {
2382 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2383 << T->getPointeeType() << FoundVD;
2384 }
2385 }
2386 }
2387
Richard Trieuef64e942013-10-25 00:56:00 +00002388 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002389 return;
2390
Richard Trieuef64e942013-10-25 00:56:00 +00002391 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002392
Richard Trieufa1d0a72014-10-17 20:56:10 +00002393 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2394 // Special checking for initializer lists.
2395 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2396 return;
2397 }
2398 } else {
2399 // Prevent double warnings on use of unbounded references.
2400 if (CheckReferenceOnly && !IsReference)
2401 return;
2402 }
Richard Trieuef64e942013-10-25 00:56:00 +00002403
2404 unsigned diag = IsReference
2405 ? diag::warn_reference_field_is_uninit
2406 : diag::warn_field_is_uninit;
2407 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2408 if (Constructor)
2409 S.Diag(Constructor->getLocation(),
2410 diag::note_uninit_in_this_constructor)
2411 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2412
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002413 }
2414
Richard Trieu2d779b92014-10-01 03:44:58 +00002415 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002416 E = E->IgnoreParens();
2417
2418 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002419 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2420 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002421 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002422 }
2423
2424 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002425 Visit(CO->getCond());
2426 HandleValue(CO->getTrueExpr(), AddressOf);
2427 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002428 return;
2429 }
2430
2431 if (BinaryConditionalOperator *BCO =
2432 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002433 Visit(BCO->getCond());
2434 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002435 return;
2436 }
2437
Richard Trieuabf6ec42014-08-27 22:15:10 +00002438 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002439 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002440 return;
2441 }
2442
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002443 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2444 switch (BO->getOpcode()) {
2445 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002446 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002447 case(BO_PtrMemD):
2448 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002449 HandleValue(BO->getLHS(), AddressOf);
2450 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002451 return;
2452 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002453 Visit(BO->getLHS());
2454 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002455 return;
2456 }
2457 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002458
2459 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002460 }
2461
Richard Trieufa1d0a72014-10-17 20:56:10 +00002462 void CheckInitListExpr(InitListExpr *ILE) {
2463 InitFieldIndex.push_back(0);
2464 for (auto Child : ILE->children()) {
2465 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2466 CheckInitListExpr(SubList);
2467 } else {
2468 Visit(Child);
2469 }
2470 ++InitFieldIndex.back();
2471 }
2472 InitFieldIndex.pop_back();
2473 }
2474
Richard Trieu8d08a272014-08-28 03:23:47 +00002475 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002476 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002477 // Remove Decls that may have been initialized in the previous
2478 // initializer.
2479 for (ValueDecl* VD : DeclsToRemove)
2480 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002481 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002482
Richard Trieu8d08a272014-08-28 03:23:47 +00002483 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002484 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2485
2486 if (ILE && Field) {
2487 InitList = true;
2488 InitListFieldDecl = Field;
2489 InitFieldIndex.clear();
2490 CheckInitListExpr(ILE);
2491 } else {
2492 InitList = false;
2493 Visit(E);
2494 }
2495
Richard Trieu8d08a272014-08-28 03:23:47 +00002496 if (Field)
2497 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002498 if (BaseClass)
2499 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002500 }
2501
Richard Trieu1bc22c12013-09-13 03:20:53 +00002502 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002503 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002504 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002505 }
2506
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002507 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002508 if (E->getCastKind() == CK_LValueToRValue) {
2509 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2510 return;
2511 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002512
2513 Inherited::VisitImplicitCastExpr(E);
2514 }
2515
Richard Trieu1bc22c12013-09-13 03:20:53 +00002516 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002517 if (E->getConstructor()->isCopyConstructor()) {
2518 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002519 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2520 if (ILE->getNumInits() == 1)
2521 ArgExpr = ILE->getInit(0);
2522 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2523 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002524 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002525 HandleValue(ArgExpr, false /*AddressOf*/);
2526 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002527 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002528 Inherited::VisitCXXConstructExpr(E);
2529 }
2530
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002531 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2532 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002533 if (isa<MemberExpr>(Callee)) {
2534 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002535 for (auto Arg : E->arguments())
2536 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002537 return;
2538 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002539
2540 Inherited::VisitCXXMemberCallExpr(E);
2541 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002542
Richard Trieu11fd0792014-08-26 04:30:55 +00002543 void VisitCallExpr(CallExpr *E) {
2544 // Treat std::move as a use.
2545 if (E->getNumArgs() == 1) {
2546 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002547 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2548 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002549 HandleValue(E->getArg(0), false /*AddressOf*/);
2550 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002551 }
2552 }
2553 }
2554
2555 Inherited::VisitCallExpr(E);
2556 }
2557
Richard Trieud4a01362014-10-31 21:10:22 +00002558 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2559 Expr *Callee = E->getCallee();
2560
2561 if (isa<UnresolvedLookupExpr>(Callee))
2562 return Inherited::VisitCXXOperatorCallExpr(E);
2563
2564 Visit(Callee);
2565 for (auto Arg : E->arguments())
2566 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2567 }
2568
Richard Trieu406e65c2013-09-20 03:03:06 +00002569 void VisitBinaryOperator(BinaryOperator *E) {
2570 // If a field assignment is detected, remove the field from the
2571 // uninitiailized field set.
2572 if (E->getOpcode() == BO_Assign)
2573 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2574 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002575 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002576 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002577
Richard Trieu52b8b602014-09-25 01:15:40 +00002578 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002579 HandleValue(E->getLHS(), false /*AddressOf*/);
2580 Visit(E->getRHS());
2581 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002582 }
2583
Richard Trieu406e65c2013-09-20 03:03:06 +00002584 Inherited::VisitBinaryOperator(E);
2585 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002586
2587 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002588 if (E->isIncrementDecrementOp()) {
2589 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2590 return;
2591 }
2592 if (E->getOpcode() == UO_AddrOf) {
2593 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2594 HandleValue(ME->getBase(), true /*AddressOf*/);
2595 return;
2596 }
2597 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002598
2599 Inherited::VisitUnaryOperator(E);
2600 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002601 };
Richard Trieuef64e942013-10-25 00:56:00 +00002602
2603 // Diagnose value-uses of fields to initialize themselves, e.g.
2604 // foo(foo)
2605 // where foo is not also a parameter to the constructor.
2606 // Also diagnose across field uninitialized use such as
2607 // x(y), y(x)
2608 // TODO: implement -Wuninitialized and fold this into that framework.
2609 static void DiagnoseUninitializedFields(
2610 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2611
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002612 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2613 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002614 return;
2615 }
2616
2617 if (Constructor->isInvalidDecl())
2618 return;
2619
2620 const CXXRecordDecl *RD = Constructor->getParent();
2621
Richard Trieu353a4b42014-10-22 05:21:59 +00002622 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002623 return;
2624
Richard Trieuef64e942013-10-25 00:56:00 +00002625 // Holds fields that are uninitialized.
2626 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2627
2628 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002629 for (auto *I : RD->decls()) {
2630 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002631 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002632 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002633 UninitializedFields.insert(IFD->getAnonField());
2634 }
2635 }
2636
Richard Trieu3630c392014-11-21 03:10:30 +00002637 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2638 for (auto I : RD->bases())
2639 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2640
2641 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002642 return;
2643
2644 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002645 UninitializedFields,
2646 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002647
Aaron Ballman0ad78302014-03-13 17:34:31 +00002648 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002649 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002650 break;
2651
Aaron Ballman0ad78302014-03-13 17:34:31 +00002652 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002653 if (!InitExpr)
2654 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002655
Richard Trieu8d08a272014-08-28 03:23:47 +00002656 if (CXXDefaultInitExpr *Default =
2657 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2658 InitExpr = Default->getExpr();
2659 if (!InitExpr)
2660 continue;
2661 // In class initializers will point to the constructor.
2662 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002663 FieldInit->getAnyMember(),
2664 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002665 } else {
2666 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002667 FieldInit->getAnyMember(),
2668 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002669 }
Richard Trieuef64e942013-10-25 00:56:00 +00002670 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002671 }
2672} // namespace
2673
Richard Smith74108172014-01-17 03:11:34 +00002674/// \brief Enter a new C++ default initializer scope. After calling this, the
2675/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2676/// parsing or instantiating the initializer failed.
2677void Sema::ActOnStartCXXInClassMemberInitializer() {
2678 // Create a synthetic function scope to represent the call to the constructor
2679 // that notionally surrounds a use of this initializer.
2680 PushFunctionScope();
2681}
2682
2683/// \brief This is invoked after parsing an in-class initializer for a
2684/// non-static C++ class member, and after instantiating an in-class initializer
2685/// in a class template. Such actions are deferred until the class is complete.
2686void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2687 SourceLocation InitLoc,
2688 Expr *InitExpr) {
2689 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002690 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002691
David Majnemer87ff66c2014-12-13 11:34:16 +00002692 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2693 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002694 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002695
2696 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002697 D->setInvalidDecl();
2698 if (FD)
2699 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002700 return;
2701 }
2702
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002703 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2704 FD->setInvalidDecl();
2705 FD->removeInClassInitializer();
2706 return;
2707 }
2708
Richard Smith938f40b2011-06-11 17:19:42 +00002709 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002710 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002711 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002712 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002713 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002714 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002715 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2716 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002717 if (Init.isInvalid()) {
2718 FD->setInvalidDecl();
2719 return;
2720 }
Richard Smith938f40b2011-06-11 17:19:42 +00002721 }
2722
Richard Smith945f8d32013-01-14 22:39:08 +00002723 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002724 // The initialization of each base and member constitutes a
2725 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002726 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002727 if (Init.isInvalid()) {
2728 FD->setInvalidDecl();
2729 return;
2730 }
2731
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002732 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002733
2734 FD->setInClassInitializer(InitExpr);
2735}
2736
Douglas Gregor15e77a22009-12-31 09:10:24 +00002737/// \brief Find the direct and/or virtual base specifiers that
2738/// correspond to the given base type, for use in base initialization
2739/// within a constructor.
2740static bool FindBaseInitializer(Sema &SemaRef,
2741 CXXRecordDecl *ClassDecl,
2742 QualType BaseType,
2743 const CXXBaseSpecifier *&DirectBaseSpec,
2744 const CXXBaseSpecifier *&VirtualBaseSpec) {
2745 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002746 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002747 for (const auto &Base : ClassDecl->bases()) {
2748 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002749 // We found a direct base of this type. That's what we're
2750 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002751 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002752 break;
2753 }
2754 }
2755
2756 // Check for a virtual base class.
2757 // FIXME: We might be able to short-circuit this if we know in advance that
2758 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002759 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002760 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2761 // We haven't found a base yet; search the class hierarchy for a
2762 // virtual base class.
2763 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2764 /*DetectVirtual=*/false);
2765 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2766 BaseType, Paths)) {
2767 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2768 Path != Paths.end(); ++Path) {
2769 if (Path->back().Base->isVirtual()) {
2770 VirtualBaseSpec = Path->back().Base;
2771 break;
2772 }
2773 }
2774 }
2775 }
2776
2777 return DirectBaseSpec || VirtualBaseSpec;
2778}
2779
Sebastian Redla74948d2011-09-24 17:48:25 +00002780/// \brief Handle a C++ member initializer using braced-init-list syntax.
2781MemInitResult
2782Sema::ActOnMemInitializer(Decl *ConstructorD,
2783 Scope *S,
2784 CXXScopeSpec &SS,
2785 IdentifierInfo *MemberOrBase,
2786 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002787 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002788 SourceLocation IdLoc,
2789 Expr *InitList,
2790 SourceLocation EllipsisLoc) {
2791 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002792 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002793 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002794}
2795
2796/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002797MemInitResult
John McCall48871652010-08-21 09:40:31 +00002798Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002799 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002800 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002801 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002802 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002803 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002804 SourceLocation IdLoc,
2805 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002806 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002807 SourceLocation RParenLoc,
2808 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002809 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002810 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002811 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002812 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002813}
2814
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002815namespace {
2816
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002817// Callback to only accept typo corrections that can be a valid C++ member
2818// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002819class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002820public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002821 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2822 : ClassDecl(ClassDecl) {}
2823
Craig Toppera798a9d2014-03-02 09:32:10 +00002824 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002825 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2826 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2827 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002828 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002829 }
2830 return false;
2831 }
2832
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002833private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002834 CXXRecordDecl *ClassDecl;
2835};
2836
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002837}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002838
Sebastian Redla74948d2011-09-24 17:48:25 +00002839/// \brief Handle a C++ member initializer.
2840MemInitResult
2841Sema::BuildMemInitializer(Decl *ConstructorD,
2842 Scope *S,
2843 CXXScopeSpec &SS,
2844 IdentifierInfo *MemberOrBase,
2845 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002846 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002847 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002848 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002849 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002850 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2851 if (!Res.isUsable())
2852 return true;
2853 Init = Res.get();
2854
Douglas Gregor71a57182009-06-22 23:20:33 +00002855 if (!ConstructorD)
2856 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002857
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002858 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002859
2860 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002861 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002862 if (!Constructor) {
2863 // The user wrote a constructor initializer on a function that is
2864 // not a C++ constructor. Ignore the error for now, because we may
2865 // have more member initializers coming; we'll diagnose it just
2866 // once in ActOnMemInitializers.
2867 return true;
2868 }
2869
2870 CXXRecordDecl *ClassDecl = Constructor->getParent();
2871
2872 // C++ [class.base.init]p2:
2873 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002874 // constructor's class and, if not found in that scope, are looked
2875 // up in the scope containing the constructor's definition.
2876 // [Note: if the constructor's class contains a member with the
2877 // same name as a direct or virtual base class of the class, a
2878 // mem-initializer-id naming the member or base class and composed
2879 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002880 // mem-initializer-id for the hidden base class may be specified
2881 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002882 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002883 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002884 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002885 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002886 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002887 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2888 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002889 if (EllipsisLoc.isValid())
2890 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002891 << MemberOrBase
2892 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002893
Sebastian Redla9351792012-02-11 23:51:47 +00002894 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002895 }
Francois Pichetd583da02010-12-04 09:14:42 +00002896 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002897 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002898 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002899 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002900 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002901
2902 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002903 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002904 } else if (DS.getTypeSpecType() == TST_decltype) {
2905 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002906 } else {
2907 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2908 LookupParsedName(R, S, &SS);
2909
2910 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2911 if (!TyD) {
2912 if (R.isAmbiguous()) return true;
2913
John McCallda6841b2010-04-09 19:01:14 +00002914 // We don't want access-control diagnostics here.
2915 R.suppressDiagnostics();
2916
Douglas Gregora3b624a2010-01-19 06:46:48 +00002917 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2918 bool NotUnknownSpecialization = false;
2919 DeclContext *DC = computeDeclContext(SS, false);
2920 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2921 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2922
2923 if (!NotUnknownSpecialization) {
2924 // When the scope specifier can refer to a member of an unknown
2925 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002926 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2927 SS.getWithLocInContext(Context),
2928 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002929 if (BaseType.isNull())
2930 return true;
2931
Douglas Gregora3b624a2010-01-19 06:46:48 +00002932 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002933 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002934 }
2935 }
2936
Douglas Gregor15e77a22009-12-31 09:10:24 +00002937 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002938 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002939 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002940 (Corr = CorrectTypo(
2941 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2942 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2943 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002944 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002945 // We have found a non-static data member with a similar
2946 // name to what was typed; complain and initialize that
2947 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002948 diagnoseTypo(Corr,
2949 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2950 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002951 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002952 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002953 const CXXBaseSpecifier *DirectBaseSpec;
2954 const CXXBaseSpecifier *VirtualBaseSpec;
2955 if (FindBaseInitializer(*this, ClassDecl,
2956 Context.getTypeDeclType(Type),
2957 DirectBaseSpec, VirtualBaseSpec)) {
2958 // We have found a direct or virtual base class with a
2959 // similar name to what was typed; complain and initialize
2960 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002961 diagnoseTypo(Corr,
2962 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2963 << MemberOrBase << false,
2964 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002965
Richard Smithf9b15102013-08-17 00:46:16 +00002966 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2967 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002968 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002969 diag::note_base_class_specified_here)
2970 << BaseSpec->getType()
2971 << BaseSpec->getSourceRange();
2972
Douglas Gregor15e77a22009-12-31 09:10:24 +00002973 TyD = Type;
2974 }
2975 }
2976 }
2977
Douglas Gregora3b624a2010-01-19 06:46:48 +00002978 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002979 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002980 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002981 return true;
2982 }
John McCallb5a0d312009-12-21 10:41:20 +00002983 }
2984
Douglas Gregora3b624a2010-01-19 06:46:48 +00002985 if (BaseType.isNull()) {
2986 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00002987 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00002988 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002989 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002990 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2991 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002992 }
2993 }
Mike Stump11289f42009-09-09 15:08:12 +00002994
John McCallbcd03502009-12-07 02:54:59 +00002995 if (!TInfo)
2996 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002997
Sebastian Redla9351792012-02-11 23:51:47 +00002998 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002999}
3000
Chandler Carruth599deef2011-09-03 01:14:15 +00003001/// Checks a member initializer expression for cases where reference (or
3002/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003003static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3004 Expr *Init,
3005 SourceLocation IdLoc) {
3006 QualType MemberTy = Member->getType();
3007
3008 // We only handle pointers and references currently.
3009 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3010 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3011 return;
3012
3013 const bool IsPointer = MemberTy->isPointerType();
3014 if (IsPointer) {
3015 if (const UnaryOperator *Op
3016 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3017 // The only case we're worried about with pointers requires taking the
3018 // address.
3019 if (Op->getOpcode() != UO_AddrOf)
3020 return;
3021
3022 Init = Op->getSubExpr();
3023 } else {
3024 // We only handle address-of expression initializers for pointers.
3025 return;
3026 }
3027 }
3028
Richard Smithe3b28bc2013-06-12 21:51:50 +00003029 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003030 // We only warn when referring to a non-reference parameter declaration.
3031 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3032 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003033 return;
3034
3035 S.Diag(Init->getExprLoc(),
3036 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3037 : diag::warn_bind_ref_member_to_parameter)
3038 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003039 } else {
3040 // Other initializers are fine.
3041 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003042 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003043
3044 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3045 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003046}
3047
John McCallfaf5fb42010-08-26 23:41:50 +00003048MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003049Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003050 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003051 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3052 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3053 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003054 "Member must be a FieldDecl or IndirectFieldDecl");
3055
Sebastian Redla9351792012-02-11 23:51:47 +00003056 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003057 return true;
3058
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003059 if (Member->isInvalidDecl())
3060 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003061
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003062 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003063 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003064 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003065 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003066 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003067 } else {
3068 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003069 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003070 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003071
Sebastian Redla9351792012-02-11 23:51:47 +00003072 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003073
Sebastian Redla9351792012-02-11 23:51:47 +00003074 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003075 // Can't check initialization for a member of dependent type or when
3076 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003077 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003078 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003079 bool InitList = false;
3080 if (isa<InitListExpr>(Init)) {
3081 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003082 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003083 }
3084
Chandler Carruthd44c3102010-12-06 09:23:57 +00003085 // Initialize the member.
3086 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003087 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3088 : InitializedEntity::InitializeMember(IndirectMember,
3089 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003090 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003091 InitList ? InitializationKind::CreateDirectList(IdLoc)
3092 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3093 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003094
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003095 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003096 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3097 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003098 if (MemberInit.isInvalid())
3099 return true;
3100
Richard Smith736a9472013-06-12 20:42:33 +00003101 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3102
Richard Smith945f8d32013-01-14 22:39:08 +00003103 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003104 // The initialization of each base and member constitutes a
3105 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003106 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003107 if (MemberInit.isInvalid())
3108 return true;
3109
Richard Smithd59b8322012-12-19 01:39:02 +00003110 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003111 }
3112
Chandler Carruthd44c3102010-12-06 09:23:57 +00003113 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003114 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3115 InitRange.getBegin(), Init,
3116 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003117 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003118 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3119 InitRange.getBegin(), Init,
3120 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003121 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003122}
3123
John McCallfaf5fb42010-08-26 23:41:50 +00003124MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003125Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003126 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003127 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003128 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003129 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003130 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003131 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003132
Sebastian Redl0501c632012-02-12 16:37:36 +00003133 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003134 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003135 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3136 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003137 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003138 }
3139
Sebastian Redla9351792012-02-11 23:51:47 +00003140 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003141 // Initialize the object.
3142 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3143 QualType(ClassDecl->getTypeForDecl(), 0));
3144 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003145 InitList ? InitializationKind::CreateDirectList(NameLoc)
3146 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3147 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003148 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003149 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003150 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003151 if (DelegationInit.isInvalid())
3152 return true;
3153
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003154 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3155 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003156
Richard Smith945f8d32013-01-14 22:39:08 +00003157 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003158 // The initialization of each base and member constitutes a
3159 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003160 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3161 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003162 if (DelegationInit.isInvalid())
3163 return true;
3164
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003165 // If we are in a dependent context, template instantiation will
3166 // perform this type-checking again. Just save the arguments that we
3167 // received in a ParenListExpr.
3168 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3169 // of the information that we have about the base
3170 // initializer. However, deconstructing the ASTs is a dicey process,
3171 // and this approach is far more likely to get the corner cases right.
3172 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003173 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003174
Sebastian Redla9351792012-02-11 23:51:47 +00003175 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003176 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003177 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003178}
3179
3180MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003181Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003182 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003183 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003184 SourceLocation BaseLoc
3185 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003186
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003187 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3188 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3189 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3190
3191 // C++ [class.base.init]p2:
3192 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003193 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003194 // of that class, the mem-initializer is ill-formed. A
3195 // mem-initializer-list can initialize a base class using any
3196 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003197 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003198
Sebastian Redla9351792012-02-11 23:51:47 +00003199 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003200 if (EllipsisLoc.isValid()) {
3201 // This is a pack expansion.
3202 if (!BaseType->containsUnexpandedParameterPack()) {
3203 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003204 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003205
Douglas Gregor44e7df62011-01-04 00:32:56 +00003206 EllipsisLoc = SourceLocation();
3207 }
3208 } else {
3209 // Check for any unexpanded parameter packs.
3210 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3211 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003212
Sebastian Redla9351792012-02-11 23:51:47 +00003213 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003214 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003215 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003216
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003217 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003218 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3219 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003220 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003221 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3222 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003223 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003224
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003225 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3226 VirtualBaseSpec);
3227
3228 // C++ [base.class.init]p2:
3229 // Unless the mem-initializer-id names a nonstatic data member of the
3230 // constructor's class or a direct or virtual base of that class, the
3231 // mem-initializer is ill-formed.
3232 if (!DirectBaseSpec && !VirtualBaseSpec) {
3233 // If the class has any dependent bases, then it's possible that
3234 // one of those types will resolve to the same type as
3235 // BaseType. Therefore, just treat this as a dependent base
3236 // class initialization. FIXME: Should we try to check the
3237 // initialization anyway? It seems odd.
3238 if (ClassDecl->hasAnyDependentBases())
3239 Dependent = true;
3240 else
3241 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3242 << BaseType << Context.getTypeDeclType(ClassDecl)
3243 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3244 }
3245 }
3246
3247 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003248 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003249
Sebastian Redla74948d2011-09-24 17:48:25 +00003250 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3251 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003252 InitRange.getBegin(), Init,
3253 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003254 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003255
3256 // C++ [base.class.init]p2:
3257 // If a mem-initializer-id is ambiguous because it designates both
3258 // a direct non-virtual base class and an inherited virtual base
3259 // class, the mem-initializer is ill-formed.
3260 if (DirectBaseSpec && VirtualBaseSpec)
3261 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003262 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003263
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003264 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003265 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003266 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003267
3268 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003269 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003270 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003271 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003272 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003273 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003274 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003275
3276 InitializedEntity BaseEntity =
3277 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3278 InitializationKind Kind =
3279 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3280 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3281 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003282 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003283 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003284 if (BaseInit.isInvalid())
3285 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003286
Richard Smith945f8d32013-01-14 22:39:08 +00003287 // C++11 [class.base.init]p7:
3288 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003289 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003290 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003291 if (BaseInit.isInvalid())
3292 return true;
3293
3294 // If we are in a dependent context, template instantiation will
3295 // perform this type-checking again. Just save the arguments that we
3296 // received in a ParenListExpr.
3297 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3298 // of the information that we have about the base
3299 // initializer. However, deconstructing the ASTs is a dicey process,
3300 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003301 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003302 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003303
Alexis Hunt1d792652011-01-08 20:30:50 +00003304 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003305 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003306 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003307 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003308 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003309}
3310
Sebastian Redl22653ba2011-08-30 19:58:05 +00003311// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003312static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3313 if (T.isNull()) T = E->getType();
3314 QualType TargetType = SemaRef.BuildReferenceType(
3315 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003316 SourceLocation ExprLoc = E->getLocStart();
3317 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3318 TargetType, ExprLoc);
3319
3320 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3321 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003322 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003323}
3324
Anders Carlsson1b00e242010-04-23 03:10:23 +00003325/// ImplicitInitializerKind - How an implicit base or member initializer should
3326/// initialize its base or member.
3327enum ImplicitInitializerKind {
3328 IIK_Default,
3329 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003330 IIK_Move,
3331 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003332};
3333
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003334static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003335BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003336 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003337 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003338 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003339 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003340 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003341 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3342 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003343
John McCalldadc5752010-08-24 06:29:42 +00003344 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003345
3346 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003347 case IIK_Inherit: {
3348 const CXXRecordDecl *Inherited =
3349 Constructor->getInheritedConstructor()->getParent();
3350 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3351 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3352 // C++11 [class.inhctor]p8:
3353 // Each expression in the expression-list is of the form
3354 // static_cast<T&&>(p), where p is the name of the corresponding
3355 // constructor parameter and T is the declared type of p.
3356 SmallVector<Expr*, 16> Args;
3357 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3358 ParmVarDecl *PD = Constructor->getParamDecl(I);
3359 ExprResult ArgExpr =
3360 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3361 VK_LValue, SourceLocation());
3362 if (ArgExpr.isInvalid())
3363 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003364 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003365 }
3366
3367 InitializationKind InitKind = InitializationKind::CreateDirect(
3368 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003369 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003370 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3371 break;
3372 }
3373 }
3374 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003375 case IIK_Default: {
3376 InitializationKind InitKind
3377 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003378 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3379 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003380 break;
3381 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003382
Sebastian Redl22653ba2011-08-30 19:58:05 +00003383 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003384 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003385 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003386 ParmVarDecl *Param = Constructor->getParamDecl(0);
3387 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003388
Anders Carlsson1b00e242010-04-23 03:10:23 +00003389 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003390 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003391 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003392 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003393 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003394
Eli Friedmanfa0df832012-02-02 03:46:19 +00003395 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3396
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003397 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003398 QualType ArgTy =
3399 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3400 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003401
Sebastian Redl22653ba2011-08-30 19:58:05 +00003402 if (Moving) {
3403 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3404 }
3405
John McCallcf142162010-08-07 06:22:56 +00003406 CXXCastPath BasePath;
3407 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003408 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3409 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003410 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003411 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003412
Anders Carlsson1b00e242010-04-23 03:10:23 +00003413 InitializationKind InitKind
3414 = InitializationKind::CreateDirect(Constructor->getLocation(),
3415 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003416 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3417 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003418 break;
3419 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003420 }
John McCallb268a282010-08-23 23:25:46 +00003421
Douglas Gregora40433a2010-12-07 00:41:46 +00003422 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003423 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003424 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003425
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003426 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003427 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003428 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3429 SourceLocation()),
3430 BaseSpec->isVirtual(),
3431 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003432 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003433 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003434 SourceLocation());
3435
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003436 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003437}
3438
Sebastian Redl22653ba2011-08-30 19:58:05 +00003439static bool RefersToRValueRef(Expr *MemRef) {
3440 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3441 return Referenced->getType()->isRValueReferenceType();
3442}
3443
Anders Carlsson3c1db572010-04-23 02:15:47 +00003444static bool
3445BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003446 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003447 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003448 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003449 if (Field->isInvalidDecl())
3450 return true;
3451
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003452 SourceLocation Loc = Constructor->getLocation();
3453
Sebastian Redl22653ba2011-08-30 19:58:05 +00003454 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3455 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003456 ParmVarDecl *Param = Constructor->getParamDecl(0);
3457 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003458
3459 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003460 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3461 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003462
Anders Carlsson423f5d82010-04-23 16:04:08 +00003463 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003464 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003465 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003466 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003467
Eli Friedmanfa0df832012-02-02 03:46:19 +00003468 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3469
Sebastian Redl22653ba2011-08-30 19:58:05 +00003470 if (Moving) {
3471 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3472 }
3473
Douglas Gregor94f9a482010-05-05 05:51:00 +00003474 // Build a reference to this field within the parameter.
3475 CXXScopeSpec SS;
3476 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3477 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003478 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3479 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003480 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003481 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003482 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003483 ParamType, Loc,
3484 /*IsArrow=*/false,
3485 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003486 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003487 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003488 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003489 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003490 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003491 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003492
3493 // C++11 [class.copy]p15:
3494 // - if a member m has rvalue reference type T&&, it is direct-initialized
3495 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003496 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003497 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003498 }
3499
Douglas Gregor94f9a482010-05-05 05:51:00 +00003500 // When the field we are copying is an array, create index variables for
3501 // each dimension of the array. We use these index variables to subscript
3502 // the source array, and other clients (e.g., CodeGen) will perform the
3503 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003504 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003505 QualType BaseType = Field->getType();
3506 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003507 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003508 while (const ConstantArrayType *Array
3509 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003510 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003511 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003513 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003514 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003515 llvm::raw_svector_ostream OS(Str);
3516 OS << "__i" << IndexVariables.size();
3517 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3518 }
3519 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003520 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003521 IterationVarName, SizeType,
3522 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003523 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003524 IndexVariables.push_back(IterationVar);
3525
3526 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003527 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003528 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003529 assert(!IterationVarRef.isInvalid() &&
3530 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003531 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003532 assert(!IterationVarRef.isInvalid() &&
3533 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003534
Douglas Gregor94f9a482010-05-05 05:51:00 +00003535 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003536 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3537 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003538 Loc);
3539 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003540 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003541
Douglas Gregor94f9a482010-05-05 05:51:00 +00003542 BaseType = Array->getElementType();
3543 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003544
3545 // The array subscript expression is an lvalue, which is wrong for moving.
3546 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003547 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003548
Douglas Gregor94f9a482010-05-05 05:51:00 +00003549 // Construct the entity that we will be initializing. For an array, this
3550 // will be first element in the array, which may require several levels
3551 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003552 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003553 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003554 if (Indirect)
3555 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3556 else
3557 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003558 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3559 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3560 0,
3561 Entities.back()));
3562
3563 // Direct-initialize to use the copy constructor.
3564 InitializationKind InitKind =
3565 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3566
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003567 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00003568 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3569 CtorArgE);
3570
John McCalldadc5752010-08-24 06:29:42 +00003571 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003572 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003573 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003574 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003575 if (MemberInit.isInvalid())
3576 return true;
3577
Douglas Gregor493627b2011-08-10 15:22:55 +00003578 if (Indirect) {
3579 assert(IndexVariables.size() == 0 &&
3580 "Indirect field improperly initialized");
3581 CXXMemberInit
3582 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3583 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003584 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003585 Loc);
3586 } else
3587 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003588 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003589 Loc,
3590 IndexVariables.data(),
3591 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003592 return false;
3593 }
3594
Richard Smithc2bc61b2013-03-18 21:12:30 +00003595 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3596 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003597
Anders Carlsson3c1db572010-04-23 02:15:47 +00003598 QualType FieldBaseElementType =
3599 SemaRef.Context.getBaseElementType(Field->getType());
3600
Anders Carlsson3c1db572010-04-23 02:15:47 +00003601 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003602 InitializedEntity InitEntity
3603 = Indirect? InitializedEntity::InitializeMember(Indirect)
3604 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003605 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003606 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003607
3608 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3609 ExprResult MemberInit =
3610 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003611
Douglas Gregora40433a2010-12-07 00:41:46 +00003612 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003613 if (MemberInit.isInvalid())
3614 return true;
3615
Douglas Gregor493627b2011-08-10 15:22:55 +00003616 if (Indirect)
3617 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3618 Indirect, Loc,
3619 Loc,
3620 MemberInit.get(),
3621 Loc);
3622 else
3623 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3624 Field, Loc, Loc,
3625 MemberInit.get(),
3626 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003627 return false;
3628 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003629
Alexis Hunt8b455182011-05-17 00:19:05 +00003630 if (!Field->getParent()->isUnion()) {
3631 if (FieldBaseElementType->isReferenceType()) {
3632 SemaRef.Diag(Constructor->getLocation(),
3633 diag::err_uninitialized_member_in_ctor)
3634 << (int)Constructor->isImplicit()
3635 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3636 << 0 << Field->getDeclName();
3637 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3638 return true;
3639 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003640
Alexis Hunt8b455182011-05-17 00:19:05 +00003641 if (FieldBaseElementType.isConstQualified()) {
3642 SemaRef.Diag(Constructor->getLocation(),
3643 diag::err_uninitialized_member_in_ctor)
3644 << (int)Constructor->isImplicit()
3645 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3646 << 1 << Field->getDeclName();
3647 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3648 return true;
3649 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003650 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003651
David Blaikiebbafb8a2012-03-11 07:00:24 +00003652 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003653 FieldBaseElementType->isObjCRetainableType() &&
3654 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3655 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003656 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003657 // Default-initialize Objective-C pointers to NULL.
3658 CXXMemberInit
3659 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3660 Loc, Loc,
3661 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3662 Loc);
3663 return false;
3664 }
3665
Anders Carlsson3c1db572010-04-23 02:15:47 +00003666 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003667 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003668 return false;
3669}
John McCallbc83b3f2010-05-20 23:23:51 +00003670
3671namespace {
3672struct BaseAndFieldInfo {
3673 Sema &S;
3674 CXXConstructorDecl *Ctor;
3675 bool AnyErrorsInInits;
3676 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003677 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003678 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003679 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003680
3681 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3682 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003683 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3684 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003685 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003686 else if (Generated && Ctor->isMoveConstructor())
3687 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003688 else if (Ctor->getInheritedConstructor())
3689 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003690 else
3691 IIK = IIK_Default;
3692 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003693
3694 bool isImplicitCopyOrMove() const {
3695 switch (IIK) {
3696 case IIK_Copy:
3697 case IIK_Move:
3698 return true;
3699
3700 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003701 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003702 return false;
3703 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003704
3705 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003706 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003707
3708 bool addFieldInitializer(CXXCtorInitializer *Init) {
3709 AllToInit.push_back(Init);
3710
3711 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003712 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003713 S.UnusedPrivateFields.remove(Init->getAnyMember());
3714
3715 return false;
3716 }
John McCallbc83b3f2010-05-20 23:23:51 +00003717
Richard Smithab44d5b2013-12-10 08:25:00 +00003718 bool isInactiveUnionMember(FieldDecl *Field) {
3719 RecordDecl *Record = Field->getParent();
3720 if (!Record->isUnion())
3721 return false;
3722
Richard Smith8d183852013-12-10 20:56:03 +00003723 if (FieldDecl *Active =
3724 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003725 return Active != Field->getCanonicalDecl();
3726
3727 // In an implicit copy or move constructor, ignore any in-class initializer.
3728 if (isImplicitCopyOrMove())
3729 return true;
3730
3731 // If there's no explicit initialization, the field is active only if it
3732 // has an in-class initializer...
3733 if (Field->hasInClassInitializer())
3734 return false;
3735 // ... or it's an anonymous struct or union whose class has an in-class
3736 // initializer.
3737 if (!Field->isAnonymousStructOrUnion())
3738 return true;
3739 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3740 return !FieldRD->hasInClassInitializer();
3741 }
3742
3743 /// \brief Determine whether the given field is, or is within, a union member
3744 /// that is inactive (because there was an initializer given for a different
3745 /// member of the union, or because the union was not initialized at all).
3746 bool isWithinInactiveUnionMember(FieldDecl *Field,
3747 IndirectFieldDecl *Indirect) {
3748 if (!Indirect)
3749 return isInactiveUnionMember(Field);
3750
Aaron Ballman29c94602014-03-07 18:36:15 +00003751 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003752 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003753 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003754 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003755 }
3756 return false;
3757 }
3758};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003759}
Richard Smithc94ec842011-09-19 13:34:43 +00003760
Douglas Gregor10f939c2011-11-02 23:04:16 +00003761/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3762/// array type.
3763static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3764 if (T->isIncompleteArrayType())
3765 return true;
3766
3767 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3768 if (!ArrayT->getSize())
3769 return true;
3770
3771 T = ArrayT->getElementType();
3772 }
3773
3774 return false;
3775}
3776
Richard Smith938f40b2011-06-11 17:19:42 +00003777static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003778 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003779 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003780 if (Field->isInvalidDecl())
3781 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003782
Chandler Carruth139e9622010-06-30 02:59:29 +00003783 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003784 if (CXXCtorInitializer *Init =
3785 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003786 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003787
Richard Smithab44d5b2013-12-10 08:25:00 +00003788 // C++11 [class.base.init]p8:
3789 // if the entity is a non-static data member that has a
3790 // brace-or-equal-initializer and either
3791 // -- the constructor's class is a union and no other variant member of that
3792 // union is designated by a mem-initializer-id or
3793 // -- the constructor's class is not a union, and, if the entity is a member
3794 // of an anonymous union, no other member of that union is designated by
3795 // a mem-initializer-id,
3796 // the entity is initialized as specified in [dcl.init].
3797 //
3798 // We also apply the same rules to handle anonymous structs within anonymous
3799 // unions.
3800 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3801 return false;
3802
Douglas Gregor7db3e952011-11-28 20:03:15 +00003803 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003804 ExprResult DIE =
3805 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3806 if (DIE.isInvalid())
3807 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003808 CXXCtorInitializer *Init;
3809 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003810 Init = new (SemaRef.Context)
3811 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3812 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003813 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003814 Init = new (SemaRef.Context)
3815 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3816 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003817 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003818 }
3819
Douglas Gregor10f939c2011-11-02 23:04:16 +00003820 // Don't initialize incomplete or zero-length arrays.
3821 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3822 return false;
3823
John McCallbc83b3f2010-05-20 23:23:51 +00003824 // Don't try to build an implicit initializer if there were semantic
3825 // errors in any of the initializers (and therefore we might be
3826 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003827 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003828 return false;
3829
Craig Topperc3ec1492014-05-26 06:22:03 +00003830 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003831 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3832 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003833 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003834
Richard Smith0a8cfc72012-08-07 21:30:42 +00003835 if (!Init)
3836 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003837
Richard Smith0a8cfc72012-08-07 21:30:42 +00003838 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003839}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003840
3841bool
3842Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3843 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003844 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003845 Constructor->setNumCtorInitializers(1);
3846 CXXCtorInitializer **initializer =
3847 new (Context) CXXCtorInitializer*[1];
3848 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3849 Constructor->setCtorInitializers(initializer);
3850
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003851 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003852 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003853 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3854 }
3855
Alexis Hunte2622992011-05-05 00:05:47 +00003856 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003857
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003858 DiagnoseUninitializedFields(*this, Constructor);
3859
Alexis Hunt61bc1732011-05-01 07:04:31 +00003860 return false;
3861}
Douglas Gregor493627b2011-08-10 15:22:55 +00003862
David Blaikie3fc2f912013-01-17 05:26:25 +00003863bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3864 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003865 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003866 // Just store the initializers as written, they will be checked during
3867 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003868 if (!Initializers.empty()) {
3869 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003870 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003871 new (Context) CXXCtorInitializer*[Initializers.size()];
3872 memcpy(baseOrMemberInitializers, Initializers.data(),
3873 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003874 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003875 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003876
3877 // Let template instantiation know whether we had errors.
3878 if (AnyErrors)
3879 Constructor->setInvalidDecl();
3880
Anders Carlssondb0a9652010-04-02 06:26:44 +00003881 return false;
3882 }
3883
John McCallbc83b3f2010-05-20 23:23:51 +00003884 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003885
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003886 // We need to build the initializer AST according to order of construction
3887 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003888 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003889 if (!ClassDecl)
3890 return true;
3891
Eli Friedman9cf6b592009-11-09 19:20:36 +00003892 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003893
David Blaikie3fc2f912013-01-17 05:26:25 +00003894 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003895 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003896
Anders Carlssondb0a9652010-04-02 06:26:44 +00003897 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003898 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003899 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003900 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003901
3902 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003903 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003904 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003905 if (FD && FD->getParent()->isUnion())
3906 Info.ActiveUnionMember.insert(std::make_pair(
3907 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3908 }
3909 } else if (FieldDecl *FD = Member->getMember()) {
3910 if (FD->getParent()->isUnion())
3911 Info.ActiveUnionMember.insert(std::make_pair(
3912 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3913 }
3914 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003915 }
3916
Anders Carlsson43c64af2010-04-21 19:52:01 +00003917 // Keep track of the direct virtual bases.
3918 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003919 for (auto &I : ClassDecl->bases()) {
3920 if (I.isVirtual())
3921 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003922 }
3923
Anders Carlssondb0a9652010-04-02 06:26:44 +00003924 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003925 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003926 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003927 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003928 // [class.base.init]p7, per DR257:
3929 // A mem-initializer where the mem-initializer-id names a virtual base
3930 // class is ignored during execution of a constructor of any class that
3931 // is not the most derived class.
3932 if (ClassDecl->isAbstract()) {
3933 // FIXME: Provide a fixit to remove the base specifier. This requires
3934 // tracking the location of the associated comma for a base specifier.
3935 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003936 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003937 DiagnoseAbstractType(ClassDecl);
3938 }
3939
John McCallbc83b3f2010-05-20 23:23:51 +00003940 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003941 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3942 // [class.base.init]p8, per DR257:
3943 // If a given [...] base class is not named by a mem-initializer-id
3944 // [...] and the entity is not a virtual base class of an abstract
3945 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003946 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003947 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003948 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003949 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003950 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003951 HadError = true;
3952 continue;
3953 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003954
John McCallbc83b3f2010-05-20 23:23:51 +00003955 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003956 }
3957 }
Mike Stump11289f42009-09-09 15:08:12 +00003958
John McCallbc83b3f2010-05-20 23:23:51 +00003959 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003960 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003961 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003962 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003963 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003964
Alexis Hunt1d792652011-01-08 20:30:50 +00003965 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003966 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003967 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003968 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003969 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003970 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003971 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003972 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003973 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003974 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003975 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003976
John McCallbc83b3f2010-05-20 23:23:51 +00003977 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003978 }
3979 }
Mike Stump11289f42009-09-09 15:08:12 +00003980
John McCallbc83b3f2010-05-20 23:23:51 +00003981 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003982 for (auto *Mem : ClassDecl->decls()) {
3983 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003984 // C++ [class.bit]p2:
3985 // A declaration for a bit-field that omits the identifier declares an
3986 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3987 // initialized.
3988 if (F->isUnnamedBitfield())
3989 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003990
Sebastian Redl22653ba2011-08-30 19:58:05 +00003991 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003992 // handle anonymous struct/union fields based on their individual
3993 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003994 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003995 continue;
3996
3997 if (CollectFieldInitializer(*this, Info, F))
3998 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003999 continue;
4000 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004001
4002 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004003 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004004 continue;
4005
Aaron Ballman629afae2014-03-07 19:56:05 +00004006 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004007 if (F->getType()->isIncompleteArrayType()) {
4008 assert(ClassDecl->hasFlexibleArrayMember() &&
4009 "Incomplete array type is not valid");
4010 continue;
4011 }
4012
Douglas Gregor493627b2011-08-10 15:22:55 +00004013 // Initialize each field of an anonymous struct individually.
4014 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4015 HadError = true;
4016
4017 continue;
4018 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004019 }
Mike Stump11289f42009-09-09 15:08:12 +00004020
David Blaikie3fc2f912013-01-17 05:26:25 +00004021 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004022 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004023 Constructor->setNumCtorInitializers(NumInitializers);
4024 CXXCtorInitializer **baseOrMemberInitializers =
4025 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004026 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004027 NumInitializers * sizeof(CXXCtorInitializer*));
4028 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004029
John McCalla6309952010-03-16 21:39:52 +00004030 // Constructors implicitly reference the base and member
4031 // destructors.
4032 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4033 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004034 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004035
4036 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004037}
4038
David Blaikieb61b8152013-01-17 08:49:22 +00004039static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004040 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004041 const RecordDecl *RD = RT->getDecl();
4042 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004043 for (auto *Field : RD->fields())
4044 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004045 return;
4046 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004047 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004048 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004049}
4050
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004051static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4052 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004053}
4054
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004055static const void *GetKeyForMember(ASTContext &Context,
4056 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004057 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004058 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004059
Richard Smithcd45dbc2014-04-19 03:48:30 +00004060 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004061}
4062
David Blaikie3fc2f912013-01-17 05:26:25 +00004063static void DiagnoseBaseOrMemInitializerOrder(
4064 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4065 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004066 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004067 return;
Mike Stump11289f42009-09-09 15:08:12 +00004068
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004069 // Don't check initializers order unless the warning is enabled at the
4070 // location of at least one initializer.
4071 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004072 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004073 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004074 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4075 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004076 ShouldCheckOrder = true;
4077 break;
4078 }
4079 }
4080 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004081 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004082
John McCallbb7b6582010-04-10 07:37:23 +00004083 // Build the list of bases and members in the order that they'll
4084 // actually be initialized. The explicit initializers should be in
4085 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004086 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004087
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004088 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4089
John McCallbb7b6582010-04-10 07:37:23 +00004090 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004091 for (const auto &VBase : ClassDecl->vbases())
4092 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004093
John McCallbb7b6582010-04-10 07:37:23 +00004094 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004095 for (const auto &Base : ClassDecl->bases()) {
4096 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004097 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004098 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004099 }
Mike Stump11289f42009-09-09 15:08:12 +00004100
John McCallbb7b6582010-04-10 07:37:23 +00004101 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004102 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004103 if (Field->isUnnamedBitfield())
4104 continue;
4105
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004106 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004107 }
4108
John McCallbb7b6582010-04-10 07:37:23 +00004109 unsigned NumIdealInits = IdealInitKeys.size();
4110 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004111
Craig Topperc3ec1492014-05-26 06:22:03 +00004112 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004113 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004114 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004115 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004116
4117 // Scan forward to try to find this initializer in the idealized
4118 // initializers list.
4119 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4120 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004121 break;
John McCallbb7b6582010-04-10 07:37:23 +00004122
4123 // If we didn't find this initializer, it must be because we
4124 // scanned past it on a previous iteration. That can only
4125 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004126 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004127 Sema::SemaDiagnosticBuilder D =
4128 SemaRef.Diag(PrevInit->getSourceLocation(),
4129 diag::warn_initializer_out_of_order);
4130
Francois Pichetd583da02010-12-04 09:14:42 +00004131 if (PrevInit->isAnyMemberInitializer())
4132 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004133 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004134 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004135
Francois Pichetd583da02010-12-04 09:14:42 +00004136 if (Init->isAnyMemberInitializer())
4137 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004138 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004139 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004140
4141 // Move back to the initializer's location in the ideal list.
4142 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4143 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004144 break;
John McCallbb7b6582010-04-10 07:37:23 +00004145
4146 assert(IdealIndex != NumIdealInits &&
4147 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004148 }
John McCallbb7b6582010-04-10 07:37:23 +00004149
4150 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004151 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004152}
4153
John McCall23eebd92010-04-10 09:28:51 +00004154namespace {
4155bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004156 CXXCtorInitializer *Init,
4157 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004158 if (!PrevInit) {
4159 PrevInit = Init;
4160 return false;
4161 }
4162
Douglas Gregorea306a12013-03-25 23:28:23 +00004163 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004164 S.Diag(Init->getSourceLocation(),
4165 diag::err_multiple_mem_initialization)
4166 << Field->getDeclName()
4167 << Init->getSourceRange();
4168 else {
John McCall424cec92011-01-19 06:33:43 +00004169 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004170 assert(BaseClass && "neither field nor base");
4171 S.Diag(Init->getSourceLocation(),
4172 diag::err_multiple_base_initialization)
4173 << QualType(BaseClass, 0)
4174 << Init->getSourceRange();
4175 }
4176 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4177 << 0 << PrevInit->getSourceRange();
4178
4179 return true;
4180}
4181
Alexis Hunt1d792652011-01-08 20:30:50 +00004182typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004183typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4184
4185bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004186 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004187 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004188 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004189 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004190 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004191
4192 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004193 if (Parent->isUnion()) {
4194 UnionEntry &En = Unions[Parent];
4195 if (En.first && En.first != Child) {
4196 S.Diag(Init->getSourceLocation(),
4197 diag::err_multiple_mem_union_initialization)
4198 << Field->getDeclName()
4199 << Init->getSourceRange();
4200 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4201 << 0 << En.second->getSourceRange();
4202 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004203 }
4204 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004205 En.first = Child;
4206 En.second = Init;
4207 }
David Blaikie0f65d592011-11-17 06:01:57 +00004208 if (!Parent->isAnonymousStructOrUnion())
4209 return false;
John McCall23eebd92010-04-10 09:28:51 +00004210 }
4211
4212 Child = Parent;
4213 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004214 }
John McCall23eebd92010-04-10 09:28:51 +00004215
4216 return false;
4217}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004218}
John McCall23eebd92010-04-10 09:28:51 +00004219
Anders Carlssone857b292010-04-02 03:37:03 +00004220/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004221void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004222 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004223 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004224 bool AnyErrors) {
4225 if (!ConstructorDecl)
4226 return;
4227
4228 AdjustDeclIfTemplate(ConstructorDecl);
4229
4230 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004231 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004232
4233 if (!Constructor) {
4234 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4235 return;
4236 }
4237
John McCall23eebd92010-04-10 09:28:51 +00004238 // Mapping for the duplicate initializers check.
4239 // For member initializers, this is keyed with a FieldDecl*.
4240 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004241 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004242
4243 // Mapping for the inconsistent anonymous-union initializers check.
4244 RedundantUnionMap MemberUnions;
4245
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004246 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004247 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004248 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004249
Abramo Bagnara341d7832010-05-26 18:09:23 +00004250 // Set the source order index.
4251 Init->setSourceOrder(i);
4252
Francois Pichetd583da02010-12-04 09:14:42 +00004253 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004254 const void *Key = GetKeyForMember(Context, Init);
4255 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004256 CheckRedundantUnionInit(*this, Init, MemberUnions))
4257 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004258 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004259 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004260 if (CheckRedundantInit(*this, Init, Members[Key]))
4261 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004262 } else {
4263 assert(Init->isDelegatingInitializer());
4264 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004265 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004266 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004267 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004268 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004269 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004270 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004271 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004272 // Return immediately as the initializer is set.
4273 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004274 }
Anders Carlssone857b292010-04-02 03:37:03 +00004275 }
4276
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004277 if (HadError)
4278 return;
4279
David Blaikie3fc2f912013-01-17 05:26:25 +00004280 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004281
David Blaikie3fc2f912013-01-17 05:26:25 +00004282 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004283
Richard Trieuef64e942013-10-25 00:56:00 +00004284 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004285}
4286
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004287void
John McCalla6309952010-03-16 21:39:52 +00004288Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4289 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004290 // Ignore dependent contexts. Also ignore unions, since their members never
4291 // have destructors implicitly called.
4292 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004293 return;
John McCall1064d7e2010-03-16 05:22:47 +00004294
4295 // FIXME: all the access-control diagnostics are positioned on the
4296 // field/base declaration. That's probably good; that said, the
4297 // user might reasonably want to know why the destructor is being
4298 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004299
Anders Carlssondee9a302009-11-17 04:44:12 +00004300 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004301 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004302 if (Field->isInvalidDecl())
4303 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004304
4305 // Don't destroy incomplete or zero-length arrays.
4306 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4307 continue;
4308
Anders Carlssondee9a302009-11-17 04:44:12 +00004309 QualType FieldType = Context.getBaseElementType(Field->getType());
4310
4311 const RecordType* RT = FieldType->getAs<RecordType>();
4312 if (!RT)
4313 continue;
4314
4315 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004316 if (FieldClassDecl->isInvalidDecl())
4317 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004318 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004319 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004320 // The destructor for an implicit anonymous union member is never invoked.
4321 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4322 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004323
Douglas Gregore71edda2010-07-01 22:47:18 +00004324 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004325 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004326 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004327 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004328 << Field->getDeclName()
4329 << FieldType);
4330
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004331 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004332 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004333 }
4334
John McCall1064d7e2010-03-16 05:22:47 +00004335 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4336
Anders Carlssondee9a302009-11-17 04:44:12 +00004337 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004338 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004339 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004340 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004341
4342 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004343 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004344 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004345
John McCall1064d7e2010-03-16 05:22:47 +00004346 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004347 // If our base class is invalid, we probably can't get its dtor anyway.
4348 if (BaseClassDecl->isInvalidDecl())
4349 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004350 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004351 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004352
Douglas Gregore71edda2010-07-01 22:47:18 +00004353 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004354 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004355
4356 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004357 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004358 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004359 << Base.getType()
4360 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004361 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004362
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004363 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004364 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004365 }
4366
4367 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004368 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004369 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004370 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004371
4372 // Ignore direct virtual bases.
4373 if (DirectVirtualBases.count(RT))
4374 continue;
4375
John McCall1064d7e2010-03-16 05:22:47 +00004376 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004377 // If our base class is invalid, we probably can't get its dtor anyway.
4378 if (BaseClassDecl->isInvalidDecl())
4379 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004380 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004381 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004382
Douglas Gregore71edda2010-07-01 22:47:18 +00004383 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004384 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004385 if (CheckDestructorAccess(
4386 ClassDecl->getLocation(), Dtor,
4387 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004388 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004389 Context.getTypeDeclType(ClassDecl)) ==
4390 AR_accessible) {
4391 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004392 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004393 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004394 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004395 }
John McCall1064d7e2010-03-16 05:22:47 +00004396
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004397 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004398 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004399 }
4400}
4401
John McCall48871652010-08-21 09:40:31 +00004402void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004403 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004404 return;
Mike Stump11289f42009-09-09 15:08:12 +00004405
Mike Stump11289f42009-09-09 15:08:12 +00004406 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004407 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004408 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004409 DiagnoseUninitializedFields(*this, Constructor);
4410 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004411}
4412
Mike Stump11289f42009-09-09 15:08:12 +00004413bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004414 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004415 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4416 unsigned DiagID;
4417 AbstractDiagSelID SelID;
4418
4419 public:
4420 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4421 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004422
Craig Toppera798a9d2014-03-02 09:32:10 +00004423 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004424 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004425 if (SelID == -1)
4426 S.Diag(Loc, DiagID) << T;
4427 else
4428 S.Diag(Loc, DiagID) << SelID << T;
4429 }
4430 } Diagnoser(DiagID, SelID);
4431
4432 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004433}
4434
Anders Carlssoneabf7702009-08-27 00:13:57 +00004435bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004436 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004437 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004438 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004439
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004440 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004441 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004442
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004443 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004444 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004445 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004446 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004447
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004448 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004449 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004450 }
Mike Stump11289f42009-09-09 15:08:12 +00004451
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004452 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004453 if (!RT)
4454 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004455
John McCall67da35c2010-02-04 22:26:26 +00004456 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004457
John McCall02db245d2010-08-18 09:41:07 +00004458 // We can't answer whether something is abstract until it has a
4459 // definition. If it's currently being defined, we'll walk back
4460 // over all the declarations when we have a full definition.
4461 const CXXRecordDecl *Def = RD->getDefinition();
4462 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004463 return false;
4464
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004465 if (!RD->isAbstract())
4466 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004467
Douglas Gregorae298422012-05-04 17:09:59 +00004468 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004469 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004470
John McCall02db245d2010-08-18 09:41:07 +00004471 return true;
4472}
4473
4474void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4475 // Check if we've already emitted the list of pure virtual functions
4476 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004477 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004478 return;
Mike Stump11289f42009-09-09 15:08:12 +00004479
Richard Smithbc46e432013-07-22 02:56:56 +00004480 // If the diagnostic is suppressed, don't emit the notes. We're only
4481 // going to emit them once, so try to attach them to a diagnostic we're
4482 // actually going to show.
4483 if (Diags.isLastDiagnosticIgnored())
4484 return;
4485
Douglas Gregor4165bd62010-03-23 23:47:56 +00004486 CXXFinalOverriderMap FinalOverriders;
4487 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004488
Anders Carlssona2f74f32010-06-03 01:00:02 +00004489 // Keep a set of seen pure methods so we won't diagnose the same method
4490 // more than once.
4491 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4492
Douglas Gregor4165bd62010-03-23 23:47:56 +00004493 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4494 MEnd = FinalOverriders.end();
4495 M != MEnd;
4496 ++M) {
4497 for (OverridingMethods::iterator SO = M->second.begin(),
4498 SOEnd = M->second.end();
4499 SO != SOEnd; ++SO) {
4500 // C++ [class.abstract]p4:
4501 // A class is abstract if it contains or inherits at least one
4502 // pure virtual function for which the final overrider is pure
4503 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004504
Douglas Gregor4165bd62010-03-23 23:47:56 +00004505 //
4506 if (SO->second.size() != 1)
4507 continue;
4508
4509 if (!SO->second.front().Method->isPure())
4510 continue;
4511
David Blaikie82e95a32014-11-19 07:49:47 +00004512 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004513 continue;
4514
Douglas Gregor4165bd62010-03-23 23:47:56 +00004515 Diag(SO->second.front().Method->getLocation(),
4516 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004517 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004518 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004519 }
4520
4521 if (!PureVirtualClassDiagSet)
4522 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4523 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004524}
4525
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004526namespace {
John McCall02db245d2010-08-18 09:41:07 +00004527struct AbstractUsageInfo {
4528 Sema &S;
4529 CXXRecordDecl *Record;
4530 CanQualType AbstractType;
4531 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004532
John McCall02db245d2010-08-18 09:41:07 +00004533 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4534 : S(S), Record(Record),
4535 AbstractType(S.Context.getCanonicalType(
4536 S.Context.getTypeDeclType(Record))),
4537 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004538
John McCall02db245d2010-08-18 09:41:07 +00004539 void DiagnoseAbstractType() {
4540 if (Invalid) return;
4541 S.DiagnoseAbstractType(Record);
4542 Invalid = true;
4543 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004544
John McCall02db245d2010-08-18 09:41:07 +00004545 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4546};
4547
4548struct CheckAbstractUsage {
4549 AbstractUsageInfo &Info;
4550 const NamedDecl *Ctx;
4551
4552 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4553 : Info(Info), Ctx(Ctx) {}
4554
4555 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4556 switch (TL.getTypeLocClass()) {
4557#define ABSTRACT_TYPELOC(CLASS, PARENT)
4558#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004559 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004560#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004561 }
John McCall02db245d2010-08-18 09:41:07 +00004562 }
Mike Stump11289f42009-09-09 15:08:12 +00004563
John McCall02db245d2010-08-18 09:41:07 +00004564 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004565 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004566 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4567 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004568 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004569
4570 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004571 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004572 }
John McCall02db245d2010-08-18 09:41:07 +00004573 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004574
John McCall02db245d2010-08-18 09:41:07 +00004575 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4576 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4577 }
Mike Stump11289f42009-09-09 15:08:12 +00004578
John McCall02db245d2010-08-18 09:41:07 +00004579 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4580 // Visit the type parameters from a permissive context.
4581 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4582 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4583 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4584 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4585 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4586 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004587 }
John McCall02db245d2010-08-18 09:41:07 +00004588 }
Mike Stump11289f42009-09-09 15:08:12 +00004589
John McCall02db245d2010-08-18 09:41:07 +00004590 // Visit pointee types from a permissive context.
4591#define CheckPolymorphic(Type) \
4592 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4593 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4594 }
4595 CheckPolymorphic(PointerTypeLoc)
4596 CheckPolymorphic(ReferenceTypeLoc)
4597 CheckPolymorphic(MemberPointerTypeLoc)
4598 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004599 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004600
John McCall02db245d2010-08-18 09:41:07 +00004601 /// Handle all the types we haven't given a more specific
4602 /// implementation for above.
4603 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4604 // Every other kind of type that we haven't called out already
4605 // that has an inner type is either (1) sugar or (2) contains that
4606 // inner type in some way as a subobject.
4607 if (TypeLoc Next = TL.getNextTypeLoc())
4608 return Visit(Next, Sel);
4609
4610 // If there's no inner type and we're in a permissive context,
4611 // don't diagnose.
4612 if (Sel == Sema::AbstractNone) return;
4613
4614 // Check whether the type matches the abstract type.
4615 QualType T = TL.getType();
4616 if (T->isArrayType()) {
4617 Sel = Sema::AbstractArrayType;
4618 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004619 }
John McCall02db245d2010-08-18 09:41:07 +00004620 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4621 if (CT != Info.AbstractType) return;
4622
4623 // It matched; do some magic.
4624 if (Sel == Sema::AbstractArrayType) {
4625 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4626 << T << TL.getSourceRange();
4627 } else {
4628 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4629 << Sel << T << TL.getSourceRange();
4630 }
4631 Info.DiagnoseAbstractType();
4632 }
4633};
4634
4635void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4636 Sema::AbstractDiagSelID Sel) {
4637 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4638}
4639
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004640}
John McCall02db245d2010-08-18 09:41:07 +00004641
4642/// Check for invalid uses of an abstract type in a method declaration.
4643static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4644 CXXMethodDecl *MD) {
4645 // No need to do the check on definitions, which require that
4646 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004647 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004648 return;
4649
4650 // For safety's sake, just ignore it if we don't have type source
4651 // information. This should never happen for non-implicit methods,
4652 // but...
4653 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4654 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4655}
4656
4657/// Check for invalid uses of an abstract type within a class definition.
4658static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4659 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004660 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004661 if (D->isImplicit()) continue;
4662
4663 // Methods and method templates.
4664 if (isa<CXXMethodDecl>(D)) {
4665 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4666 } else if (isa<FunctionTemplateDecl>(D)) {
4667 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4668 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4669
4670 // Fields and static variables.
4671 } else if (isa<FieldDecl>(D)) {
4672 FieldDecl *FD = cast<FieldDecl>(D);
4673 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4674 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4675 } else if (isa<VarDecl>(D)) {
4676 VarDecl *VD = cast<VarDecl>(D);
4677 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4678 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4679
4680 // Nested classes and class templates.
4681 } else if (isa<CXXRecordDecl>(D)) {
4682 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4683 } else if (isa<ClassTemplateDecl>(D)) {
4684 CheckAbstractClassUsage(Info,
4685 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4686 }
4687 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004688}
4689
Hans Wennborg853ae942014-05-30 16:59:42 +00004690/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004691void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004692 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004693
4694 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004695 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00004696 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4697 if (Attr *TemplateAttr =
4698 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004699 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00004700 A->setInherited(true);
4701 ClassAttr = A;
4702 }
4703 }
4704 }
4705
Hans Wennborg853ae942014-05-30 16:59:42 +00004706 if (!ClassAttr)
4707 return;
4708
Hans Wennborg8313c762014-11-03 16:09:16 +00004709 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004710 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00004711 << Class << ClassAttr;
4712 return;
4713 }
4714
Hans Wennborg17f9b442015-05-27 00:06:45 +00004715 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004716 !ClassAttr->isInherited()) {
4717 // Diagnose dll attributes on members of class with dll attribute.
4718 for (Decl *Member : Class->decls()) {
4719 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4720 continue;
4721 InheritableAttr *MemberAttr = getDLLAttr(Member);
4722 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4723 continue;
4724
Hans Wennborg17f9b442015-05-27 00:06:45 +00004725 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004726 diag::err_attribute_dll_member_of_dll_class)
4727 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00004728 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004729 Member->setInvalidDecl();
4730 }
4731 }
4732
4733 if (Class->getDescribedClassTemplate())
4734 // Don't inherit dll attribute until the template is instantiated.
4735 return;
4736
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004737 // The class is either imported or exported.
4738 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4739 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004740
Hans Wennborgfd76d912015-01-15 21:18:30 +00004741 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4742
Hans Wennborgbb1983c2015-06-09 00:39:03 +00004743 // Ignore explicit dllexport on explicit class template instantiation declarations.
4744 if (ClassExported && !ClassAttr->isInherited() &&
4745 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00004746 Class->dropAttr<DLLExportAttr>();
4747 return;
4748 }
4749
Hans Wennborg853ae942014-05-30 16:59:42 +00004750 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004751 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00004752
4753 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4754 // seem to be true in practice?
4755
Hans Wennborg853ae942014-05-30 16:59:42 +00004756 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004757 VarDecl *VD = dyn_cast<VarDecl>(Member);
4758 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4759
4760 // Only methods and static fields inherit the attributes.
4761 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004762 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004763
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004764 if (MD) {
4765 // Don't process deleted methods.
4766 if (MD->isDeleted())
4767 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004768
David Majnemer30f058a2015-05-11 03:00:22 +00004769 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00004770 // MinGW does not import or export inline methods.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004771 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemer30f058a2015-05-11 03:00:22 +00004772 continue;
4773
4774 // MSVC versions before 2015 don't export the move assignment operators,
4775 // so don't attempt to import them if we have a definition.
4776 if (ClassImported && MD->isMoveAssignmentOperator() &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00004777 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00004778 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004779 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004780 }
4781
Hans Wennborg287231c2015-04-22 04:05:17 +00004782 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4783 continue;
4784
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004785 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004786 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00004787 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00004788 NewAttr->setInherited(true);
4789 Member->addAttr(NewAttr);
4790 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004791
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004792 if (MD && ClassExported) {
Hans Wennborgbb1983c2015-06-09 00:39:03 +00004793 if (TSK == TSK_ExplicitInstantiationDeclaration)
4794 // Don't go any further if this is just an explicit instantiation
4795 // declaration.
4796 continue;
4797
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004798 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004799 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004800
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004801 // .. except for certain kinds of template specializations.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004802 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4803 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004804
Hans Wennborg17f9b442015-05-27 00:06:45 +00004805 MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004806
4807 // The function will be passed to the consumer when its definition is
4808 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004809 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4810 MD->isCopyAssignmentOperator() ||
4811 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004812 // Synthesize and instantiate non-trivial implicit methods, explicitly
4813 // defaulted methods, and the copy and move assignment operators. The
4814 // latter are exported even if they are trivial, because the address of
4815 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004816 DiagnosticErrorTrap Trap(Diags);
4817 MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg58703732015-02-21 01:07:24 +00004818 if (Trap.hasErrorOccurred()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004819 Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4820 << Class->getName() << !getLangOpts().CPlusPlus11;
Hans Wennborg58703732015-02-21 01:07:24 +00004821 break;
4822 }
Hans Wennborg45810b42014-12-16 01:15:01 +00004823
4824 // There is no later point when we will see the definition of this
4825 // function, so pass it to the consumer now.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004826 Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004827 }
4828 }
4829 }
4830}
4831
Hans Wennborgfce87ca2015-06-09 00:39:09 +00004832/// \brief Perform propagation of DLL attributes from a derived class to a
4833/// templated base class for MS compatibility.
4834void Sema::propagateDLLAttrToBaseClassTemplate(
4835 CXXRecordDecl *Class, Attr *ClassAttr,
4836 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4837 if (getDLLAttr(
4838 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4839 // If the base class template has a DLL attribute, don't try to change it.
4840 return;
4841 }
4842
4843 auto TSK = BaseTemplateSpec->getSpecializationKind();
4844 if (!getDLLAttr(BaseTemplateSpec) &&
4845 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4846 TSK == TSK_ImplicitInstantiation)) {
4847 // The template hasn't been instantiated yet (or it has, but only as an
4848 // explicit instantiation declaration or implicit instantiation, which means
4849 // we haven't codegenned any members yet), so propagate the attribute.
4850 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4851 NewAttr->setInherited(true);
4852 BaseTemplateSpec->addAttr(NewAttr);
4853
4854 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4855 // needs to be run again to work see the new attribute. Otherwise this will
4856 // get run whenever the template is instantiated.
4857 if (TSK != TSK_Undeclared)
4858 checkClassLevelDLLAttribute(BaseTemplateSpec);
4859
4860 return;
4861 }
4862
4863 if (getDLLAttr(BaseTemplateSpec)) {
4864 // The template has already been specialized or instantiated with an
4865 // attribute, explicitly or through propagation. We should not try to change
4866 // it.
4867 return;
4868 }
4869
4870 // The template was previously instantiated or explicitly specialized without
4871 // a dll attribute, It's too late for us to add an attribute, so warn that
4872 // this is unsupported.
4873 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4874 << BaseTemplateSpec->isExplicitSpecialization();
4875 Diag(ClassAttr->getLocation(), diag::note_attribute);
4876 if (BaseTemplateSpec->isExplicitSpecialization()) {
4877 Diag(BaseTemplateSpec->getLocation(),
4878 diag::note_template_class_explicit_specialization_was_here)
4879 << BaseTemplateSpec;
4880 } else {
4881 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4882 diag::note_template_class_instantiation_was_here)
4883 << BaseTemplateSpec;
4884 }
4885}
4886
Douglas Gregorc99f1552009-12-03 18:33:45 +00004887/// \brief Perform semantic checks on a class definition that has been
4888/// completing, introducing implicitly-declared members, checking for
4889/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004890void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004891 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004892 return;
4893
John McCall02db245d2010-08-18 09:41:07 +00004894 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4895 AbstractUsageInfo Info(*this, Record);
4896 CheckAbstractClassUsage(Info, Record);
4897 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004898
4899 // If this is not an aggregate type and has no user-declared constructor,
4900 // complain about any non-static data members of reference or const scalar
4901 // type, since they will never get initializers.
4902 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004903 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4904 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004905 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004906 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004907 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004908 continue;
4909
Douglas Gregor454a5b62010-04-15 00:00:53 +00004910 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004911 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004912 if (!Complained) {
4913 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4914 << Record->getTagKind() << Record;
4915 Complained = true;
4916 }
4917
4918 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4919 << F->getType()->isReferenceType()
4920 << F->getDeclName();
4921 }
4922 }
4923 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004924
Douglas Gregor36c22a22010-10-15 13:21:21 +00004925 if (Record->getIdentifier()) {
4926 // C++ [class.mem]p13:
4927 // If T is the name of a class, then each of the following shall have a
4928 // name different from T:
4929 // - every member of every anonymous union that is a member of class T.
4930 //
4931 // C++ [class.mem]p14:
4932 // In addition, if class T has a user-declared constructor (12.1), every
4933 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004934 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4935 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4936 ++I) {
4937 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004938 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4939 isa<IndirectFieldDecl>(D)) {
4940 Diag(D->getLocation(), diag::err_member_name_of_class)
4941 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004942 break;
4943 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004944 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004945 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004946
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004947 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004948 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004949 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004950 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4951 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004952 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4953 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4954 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004955
David Majnemera5433082013-10-18 00:33:31 +00004956 if (Record->isAbstract()) {
4957 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4958 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4959 << FA->isSpelledAsSealed();
4960 DiagnoseAbstractType(Record);
4961 }
David Blaikie348df502012-09-21 03:21:07 +00004962 }
4963
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004964 bool HasMethodWithOverrideControl = false,
4965 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004966 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004967 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004968 // See if a method overloads virtual methods in a base
4969 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004970 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004971 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004972 if (M->hasAttr<OverrideAttr>())
4973 HasMethodWithOverrideControl = true;
4974 else if (M->size_overridden_methods() > 0)
4975 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004976 // Check whether the explicitly-defaulted special members are valid.
4977 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004978 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004979
4980 // For an explicitly defaulted or deleted special member, we defer
4981 // determining triviality until the class is complete. That time is now!
4982 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004983 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004984 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004985 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004986
4987 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004988 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004989 }
4990 }
4991 }
4992 }
4993
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004994 if (HasMethodWithOverrideControl &&
4995 HasOverridingMethodWithoutOverrideControl) {
4996 // At least one method has the 'override' control declared.
4997 // Diagnose all other overridden methods which do not have 'override' specified on them.
4998 for (auto *M : Record->methods())
4999 DiagnoseAbsenceOfOverrideControl(M);
5000 }
Sebastian Redl08905022011-02-05 19:23:19 +00005001
John McCall95833f32014-02-27 20:30:49 +00005002 // ms_struct is a request to use the same ABI rules as MSVC. Check
5003 // whether this class uses any C++ features that are implemented
5004 // completely differently in MSVC, and if so, emit a diagnostic.
5005 // That diagnostic defaults to an error, but we allow projects to
5006 // map it down to a warning (or ignore it). It's a fairly common
5007 // practice among users of the ms_struct pragma to mass-annotate
5008 // headers, sweeping up a bunch of types that the project doesn't
5009 // really rely on MSVC-compatible layout for. We must therefore
5010 // support "ms_struct except for C++ stuff" as a secondary ABI.
5011 if (Record->isMsStruct(Context) &&
5012 (Record->isPolymorphic() || Record->getNumBases())) {
5013 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005014 }
5015
Richard Smithc2bc61b2013-03-18 21:12:30 +00005016 // Declare inheriting constructors. We do this eagerly here because:
5017 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00005018 // constructors from different classes.
5019 // - The lazy declaration of the other implicit constructors is so as to not
5020 // waste space and performance on classes that are not meant to be
5021 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00005022 // have inheriting constructors.
5023 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00005024
Hans Wennborg17f9b442015-05-27 00:06:45 +00005025 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005026}
5027
Richard Smith41c35d62013-11-27 03:39:20 +00005028/// Look up the special member function that would be called by a special
5029/// member function for a subobject of class type.
5030///
5031/// \param Class The class type of the subobject.
5032/// \param CSM The kind of special member function.
5033/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5034/// \param ConstRHS True if this is a copy operation with a const object
5035/// on its RHS, that is, if the argument to the outer special member
5036/// function is 'const' and this is not a field marked 'mutable'.
5037static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5038 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5039 unsigned FieldQuals, bool ConstRHS) {
5040 unsigned LHSQuals = 0;
5041 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5042 LHSQuals = FieldQuals;
5043
5044 unsigned RHSQuals = FieldQuals;
5045 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5046 RHSQuals = 0;
5047 else if (ConstRHS)
5048 RHSQuals |= Qualifiers::Const;
5049
5050 return S.LookupSpecialMember(Class, CSM,
5051 RHSQuals & Qualifiers::Const,
5052 RHSQuals & Qualifiers::Volatile,
5053 false,
5054 LHSQuals & Qualifiers::Const,
5055 LHSQuals & Qualifiers::Volatile);
5056}
5057
Richard Smithb5800092012-06-10 05:43:50 +00005058/// Is the special member function which would be selected to perform the
5059/// specified operation on the specified class type a constexpr constructor?
5060static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5061 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005062 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005063 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005064 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005065 if (!SMOR || !SMOR->getMethod())
5066 // A constructor we wouldn't select can't be "involved in initializing"
5067 // anything.
5068 return true;
5069 return SMOR->getMethod()->isConstexpr();
5070}
5071
5072/// Determine whether the specified special member function would be constexpr
5073/// if it were implicitly defined.
5074static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5075 Sema::CXXSpecialMember CSM,
5076 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005077 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005078 return false;
5079
5080 // C++11 [dcl.constexpr]p4:
5081 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005082 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005083 switch (CSM) {
5084 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005085 // Since default constructor lookup is essentially trivial (and cannot
5086 // involve, for instance, template instantiation), we compute whether a
5087 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5088 //
5089 // This is important for performance; we need to know whether the default
5090 // constructor is constexpr to determine whether the type is a literal type.
5091 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5092
Richard Smithb5800092012-06-10 05:43:50 +00005093 case Sema::CXXCopyConstructor:
5094 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005095 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005096 break;
5097
5098 case Sema::CXXCopyAssignment:
5099 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005100 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005101 return false;
5102 // In C++1y, we need to perform overload resolution.
5103 Ctor = false;
5104 break;
5105
Richard Smithb5800092012-06-10 05:43:50 +00005106 case Sema::CXXDestructor:
5107 case Sema::CXXInvalid:
5108 return false;
5109 }
5110
5111 // -- if the class is a non-empty union, or for each non-empty anonymous
5112 // union member of a non-union class, exactly one non-static data member
5113 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005114 //
5115 // If we squint, this is guaranteed, since exactly one non-static data member
5116 // will be initialized (if the constructor isn't deleted), we just don't know
5117 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005118 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005119 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005120
5121 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005122 if (Ctor && ClassDecl->getNumVBases())
5123 return false;
5124
5125 // C++1y [class.copy]p26:
5126 // -- [the class] is a literal type, and
5127 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005128 return false;
5129
5130 // -- every constructor involved in initializing [...] base class
5131 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005132 // -- the assignment operator selected to copy/move each direct base
5133 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005134 for (const auto &B : ClassDecl->bases()) {
5135 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005136 if (!BaseType) continue;
5137
5138 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005139 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005140 return false;
5141 }
5142
5143 // -- every constructor involved in initializing non-static data members
5144 // [...] shall be a constexpr constructor;
5145 // -- every non-static data member and base class sub-object shall be
5146 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005147 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005148 // thereof), the assignment operator selected to copy/move that member is
5149 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005150 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005151 if (F->isInvalidDecl())
5152 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005153 QualType BaseType = S.Context.getBaseElementType(F->getType());
5154 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005155 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005156 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5157 BaseType.getCVRQualifiers(),
5158 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005159 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005160 }
5161 }
5162
5163 // All OK, it's constexpr!
5164 return true;
5165}
5166
Richard Smithd3b5c9082012-07-27 04:22:15 +00005167static Sema::ImplicitExceptionSpecification
5168computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5169 switch (S.getSpecialMember(MD)) {
5170 case Sema::CXXDefaultConstructor:
5171 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5172 case Sema::CXXCopyConstructor:
5173 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5174 case Sema::CXXCopyAssignment:
5175 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5176 case Sema::CXXMoveConstructor:
5177 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5178 case Sema::CXXMoveAssignment:
5179 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5180 case Sema::CXXDestructor:
5181 return S.ComputeDefaultedDtorExceptionSpec(MD);
5182 case Sema::CXXInvalid:
5183 break;
5184 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005185 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5186 "only special members have implicit exception specs");
5187 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005188}
5189
Reid Kleckner78af0702013-08-27 23:08:25 +00005190static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5191 CXXMethodDecl *MD) {
5192 FunctionProtoType::ExtProtoInfo EPI;
5193
5194 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005195 EPI.ExceptionSpec.Type = EST_Unevaluated;
5196 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005197
5198 // Set the calling convention to the default for C++ instance methods.
5199 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5200 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5201 /*IsCXXMethod=*/true));
5202 return EPI;
5203}
5204
Richard Smithd3b5c9082012-07-27 04:22:15 +00005205void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5206 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5207 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5208 return;
5209
Richard Smith7f782272012-07-30 23:48:14 +00005210 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005211 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005212
Richard Smith7f782272012-07-30 23:48:14 +00005213 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005214 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005215
5216 // A user-provided destructor can be defined outside the class. When that
5217 // happens, be sure to update the exception specification on both
5218 // declarations.
5219 const FunctionProtoType *CanonicalFPT =
5220 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5221 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005222 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005223}
5224
Richard Smithb9e90b12012-05-15 04:39:51 +00005225void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5226 CXXRecordDecl *RD = MD->getParent();
5227 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005228
Richard Smithb9e90b12012-05-15 04:39:51 +00005229 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5230 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005231
5232 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005233 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005234 bool First = MD == MD->getCanonicalDecl();
5235
5236 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005237
5238 // C++11 [dcl.fct.def.default]p1:
5239 // A function that is explicitly defaulted shall
5240 // -- be a special member function (checked elsewhere),
5241 // -- have the same type (except for ref-qualifiers, and except that a
5242 // copy operation can take a non-const reference) as an implicit
5243 // declaration, and
5244 // -- not have default arguments.
5245 unsigned ExpectedParams = 1;
5246 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5247 ExpectedParams = 0;
5248 if (MD->getNumParams() != ExpectedParams) {
5249 // This also checks for default arguments: a copy or move constructor with a
5250 // default argument is classified as a default constructor, and assignment
5251 // operations and destructors can't have default arguments.
5252 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5253 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005254 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005255 } else if (MD->isVariadic()) {
5256 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5257 << CSM << MD->getSourceRange();
5258 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005259 }
5260
Richard Smithb9e90b12012-05-15 04:39:51 +00005261 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005262
Richard Smithb5800092012-06-10 05:43:50 +00005263 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005264 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005265 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005266 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005267 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005268
Richard Smithb9e90b12012-05-15 04:39:51 +00005269 QualType ReturnType = Context.VoidTy;
5270 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5271 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005272 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005273 QualType ExpectedReturnType =
5274 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5275 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5276 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5277 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5278 HadError = true;
5279 }
5280
5281 // A defaulted special member cannot have cv-qualifiers.
5282 if (Type->getTypeQuals()) {
5283 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005284 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005285 HadError = true;
5286 }
5287 }
5288
5289 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005290 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005291 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005292 if (ExpectedParams && ArgType->isReferenceType()) {
5293 // Argument must be reference to possibly-const T.
5294 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005295 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005296
5297 if (ReferentType.isVolatileQualified()) {
5298 Diag(MD->getLocation(),
5299 diag::err_defaulted_special_member_volatile_param) << CSM;
5300 HadError = true;
5301 }
5302
Richard Smithb5800092012-06-10 05:43:50 +00005303 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005304 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5305 Diag(MD->getLocation(),
5306 diag::err_defaulted_special_member_copy_const_param)
5307 << (CSM == CXXCopyAssignment);
5308 // FIXME: Explain why this special member can't be const.
5309 } else {
5310 Diag(MD->getLocation(),
5311 diag::err_defaulted_special_member_move_const_param)
5312 << (CSM == CXXMoveAssignment);
5313 }
5314 HadError = true;
5315 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005316 } else if (ExpectedParams) {
5317 // A copy assignment operator can take its argument by value, but a
5318 // defaulted one cannot.
5319 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005320 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005321 HadError = true;
5322 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005323
Richard Smithcc36f692011-12-22 02:22:31 +00005324 // C++11 [dcl.fct.def.default]p2:
5325 // An explicitly-defaulted function may be declared constexpr only if it
5326 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005327 // Do not apply this rule to members of class templates, since core issue 1358
5328 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005329 // functions which cannot be constexpr (for non-constructors in C++11 and for
5330 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005331 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5332 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005333 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005334 : isa<CXXConstructorDecl>(MD)) &&
5335 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005336 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5337 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005338 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005339 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005340 }
Richard Smithbd305122012-12-11 01:14:52 +00005341
Richard Smithcc36f692011-12-22 02:22:31 +00005342 // and may have an explicit exception-specification only if it is compatible
5343 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005344 if (Type->hasExceptionSpec()) {
5345 // Delay the check if this is the first declaration of the special member,
5346 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005347 if (First) {
5348 // If the exception specification needs to be instantiated, do so now,
5349 // before we clobber it with an EST_Unevaluated specification below.
5350 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5351 InstantiateExceptionSpec(MD->getLocStart(), MD);
5352 Type = MD->getType()->getAs<FunctionProtoType>();
5353 }
Richard Smithbd305122012-12-11 01:14:52 +00005354 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005355 } else
Richard Smithbd305122012-12-11 01:14:52 +00005356 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5357 }
Richard Smithcc36f692011-12-22 02:22:31 +00005358
5359 // If a function is explicitly defaulted on its first declaration,
5360 if (First) {
5361 // -- it is implicitly considered to be constexpr if the implicit
5362 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005363 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005364
Richard Smithb9e90b12012-05-15 04:39:51 +00005365 // -- it is implicitly considered to have the same exception-specification
5366 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005367 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005368 EPI.ExceptionSpec.Type = EST_Unevaluated;
5369 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005370 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005371 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005372 ExpectedParams),
5373 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005374 }
5375
Richard Smithb9e90b12012-05-15 04:39:51 +00005376 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005377 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005378 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005379 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005380 // C++11 [dcl.fct.def.default]p4:
5381 // [For a] user-provided explicitly-defaulted function [...] if such a
5382 // function is implicitly defined as deleted, the program is ill-formed.
5383 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005384 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005385 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005386 }
5387 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005388
Richard Smithb9e90b12012-05-15 04:39:51 +00005389 if (HadError)
5390 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005391}
5392
Richard Smithbd305122012-12-11 01:14:52 +00005393/// Check whether the exception specification provided for an
5394/// explicitly-defaulted special member matches the exception specification
5395/// that would have been generated for an implicit special member, per
5396/// C++11 [dcl.fct.def.default]p2.
5397void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5398 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005399 // If the exception specification was explicitly specified but hadn't been
5400 // parsed when the method was defaulted, grab it now.
5401 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5402 SpecifiedType =
5403 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5404
Richard Smithbd305122012-12-11 01:14:52 +00005405 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005406 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5407 /*IsCXXMethod=*/true);
5408 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005409 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5410 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005411 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005412 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005413
5414 // Ensure that it matches.
5415 CheckEquivalentExceptionSpec(
5416 PDiag(diag::err_incorrect_defaulted_exception_spec)
5417 << getSpecialMember(MD), PDiag(),
5418 ImplicitType, SourceLocation(),
5419 SpecifiedType, MD->getLocation());
5420}
5421
Alp Tokerae3a9442013-10-18 05:54:19 +00005422void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005423 decltype(DelayedExceptionSpecChecks) Checks;
5424 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005425
Richard Smith88f45492014-11-22 03:09:05 +00005426 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005427 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5428
5429 // Perform any deferred checking of exception specifications for virtual
5430 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005431 for (auto &Check : Checks)
5432 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005433
5434 // Check that any explicitly-defaulted methods have exception specifications
5435 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005436 for (auto &Spec : Specs)
5437 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005438}
5439
Richard Smithd951a1d2012-02-18 02:02:13 +00005440namespace {
5441struct SpecialMemberDeletionInfo {
5442 Sema &S;
5443 CXXMethodDecl *MD;
5444 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005445 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005446
5447 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005448 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005449 SourceLocation Loc;
5450
5451 bool AllFieldsAreConst;
5452
5453 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005454 Sema::CXXSpecialMember CSM, bool Diagnose)
5455 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005456 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005457 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005458 AllFieldsAreConst(true) {
5459 switch (CSM) {
5460 case Sema::CXXDefaultConstructor:
5461 case Sema::CXXCopyConstructor:
5462 IsConstructor = true;
5463 break;
5464 case Sema::CXXMoveConstructor:
5465 IsConstructor = true;
5466 IsMove = true;
5467 break;
5468 case Sema::CXXCopyAssignment:
5469 IsAssignment = true;
5470 break;
5471 case Sema::CXXMoveAssignment:
5472 IsAssignment = true;
5473 IsMove = true;
5474 break;
5475 case Sema::CXXDestructor:
5476 break;
5477 case Sema::CXXInvalid:
5478 llvm_unreachable("invalid special member kind");
5479 }
5480
5481 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005482 if (const ReferenceType *RT =
5483 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5484 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005485 }
5486 }
5487
5488 bool inUnion() const { return MD->getParent()->isUnion(); }
5489
5490 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005491 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005492 unsigned Quals, bool IsMutable) {
5493 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5494 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005495 }
5496
Richard Smith852265f2012-03-30 20:53:28 +00005497 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005498
Richard Smith852265f2012-03-30 20:53:28 +00005499 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005500 bool shouldDeleteForField(FieldDecl *FD);
5501 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005502
Richard Smithaf136f82012-07-18 03:51:16 +00005503 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5504 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005505 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5506 Sema::SpecialMemberOverloadResult *SMOR,
5507 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005508
5509 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005510};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005511}
Richard Smithd951a1d2012-02-18 02:02:13 +00005512
John McCalld4274212012-04-09 20:53:23 +00005513/// Is the given special member inaccessible when used on the given
5514/// sub-object.
5515bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5516 CXXMethodDecl *target) {
5517 /// If we're operating on a base class, the object type is the
5518 /// type of this special member.
5519 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005520 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005521 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5522 objectTy = S.Context.getTypeDeclType(MD->getParent());
5523 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5524
5525 // If we're operating on a field, the object type is the type of the field.
5526 } else {
5527 objectTy = S.Context.getTypeDeclType(target->getParent());
5528 }
5529
5530 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5531}
5532
Richard Smith852265f2012-03-30 20:53:28 +00005533/// Check whether we should delete a special member due to the implicit
5534/// definition containing a call to a special member of a subobject.
5535bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5536 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5537 bool IsDtorCallInCtor) {
5538 CXXMethodDecl *Decl = SMOR->getMethod();
5539 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5540
5541 int DiagKind = -1;
5542
5543 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5544 DiagKind = !Decl ? 0 : 1;
5545 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5546 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005547 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005548 DiagKind = 3;
5549 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5550 !Decl->isTrivial()) {
5551 // A member of a union must have a trivial corresponding special member.
5552 // As a weird special case, a destructor call from a union's constructor
5553 // must be accessible and non-deleted, but need not be trivial. Such a
5554 // destructor is never actually called, but is semantically checked as
5555 // if it were.
5556 DiagKind = 4;
5557 }
5558
5559 if (DiagKind == -1)
5560 return false;
5561
5562 if (Diagnose) {
5563 if (Field) {
5564 S.Diag(Field->getLocation(),
5565 diag::note_deleted_special_member_class_subobject)
5566 << CSM << MD->getParent() << /*IsField*/true
5567 << Field << DiagKind << IsDtorCallInCtor;
5568 } else {
5569 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5570 S.Diag(Base->getLocStart(),
5571 diag::note_deleted_special_member_class_subobject)
5572 << CSM << MD->getParent() << /*IsField*/false
5573 << Base->getType() << DiagKind << IsDtorCallInCtor;
5574 }
5575
5576 if (DiagKind == 1)
5577 S.NoteDeletedFunction(Decl);
5578 // FIXME: Explain inaccessibility if DiagKind == 3.
5579 }
5580
5581 return true;
5582}
5583
Richard Smith921bd202012-02-26 09:11:52 +00005584/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005585/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005586bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005587 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005588 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005589 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005590
5591 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005592 // -- any direct or virtual base class, or non-static data member with no
5593 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005594 // either M has no default constructor or overload resolution as applied
5595 // to M's default constructor results in an ambiguity or in a function
5596 // that is deleted or inaccessible
5597 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5598 // -- a direct or virtual base class B that cannot be copied/moved because
5599 // overload resolution, as applied to B's corresponding special member,
5600 // results in an ambiguity or a function that is deleted or inaccessible
5601 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005602 // C++11 [class.dtor]p5:
5603 // -- any direct or virtual base class [...] has a type with a destructor
5604 // that is deleted or inaccessible
5605 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005606 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005607 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5608 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005609 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005610
Richard Smith852265f2012-03-30 20:53:28 +00005611 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5612 // -- any direct or virtual base class or non-static data member has a
5613 // type with a destructor that is deleted or inaccessible
5614 if (IsConstructor) {
5615 Sema::SpecialMemberOverloadResult *SMOR =
5616 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5617 false, false, false, false, false);
5618 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5619 return true;
5620 }
5621
Richard Smith921bd202012-02-26 09:11:52 +00005622 return false;
5623}
5624
5625/// Check whether we should delete a special member function due to the class
5626/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005627bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005628 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005629 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005630}
5631
5632/// Check whether we should delete a special member function due to the class
5633/// having a particular non-static data member.
5634bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5635 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5636 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5637
5638 if (CSM == Sema::CXXDefaultConstructor) {
5639 // For a default constructor, all references must be initialized in-class
5640 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005641 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5642 if (Diagnose)
5643 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5644 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005645 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005646 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005647 // C++11 [class.ctor]p5: any non-variant non-static data member of
5648 // const-qualified type (or array thereof) with no
5649 // brace-or-equal-initializer does not have a user-provided default
5650 // constructor.
5651 if (!inUnion() && FieldType.isConstQualified() &&
5652 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005653 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5654 if (Diagnose)
5655 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005656 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005657 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005658 }
5659
5660 if (inUnion() && !FieldType.isConstQualified())
5661 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005662 } else if (CSM == Sema::CXXCopyConstructor) {
5663 // For a copy constructor, data members must not be of rvalue reference
5664 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005665 if (FieldType->isRValueReferenceType()) {
5666 if (Diagnose)
5667 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5668 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005669 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005670 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005671 } else if (IsAssignment) {
5672 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005673 if (FieldType->isReferenceType()) {
5674 if (Diagnose)
5675 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5676 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005677 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005678 }
5679 if (!FieldRecord && FieldType.isConstQualified()) {
5680 // C++11 [class.copy]p23:
5681 // -- a non-static data member of const non-class type (or array thereof)
5682 if (Diagnose)
5683 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005684 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005685 return true;
5686 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005687 }
5688
5689 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005690 // Some additional restrictions exist on the variant members.
5691 if (!inUnion() && FieldRecord->isUnion() &&
5692 FieldRecord->isAnonymousStructOrUnion()) {
5693 bool AllVariantFieldsAreConst = true;
5694
Richard Smith5704fe82012-03-29 19:00:10 +00005695 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005696 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005697 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005698
5699 if (!UnionFieldType.isConstQualified())
5700 AllVariantFieldsAreConst = false;
5701
Richard Smith921bd202012-02-26 09:11:52 +00005702 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5703 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005704 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005705 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005706 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005707 }
5708
5709 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005710 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005711 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005712 if (Diagnose)
5713 S.Diag(FieldRecord->getLocation(),
5714 diag::note_deleted_default_ctor_all_const)
5715 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005716 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005717 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005718
Richard Smith5704fe82012-03-29 19:00:10 +00005719 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005720 // This is technically non-conformant, but sanity demands it.
5721 return false;
5722 }
5723
Richard Smithaf136f82012-07-18 03:51:16 +00005724 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5725 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005726 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005727 }
5728
5729 return false;
5730}
5731
5732/// C++11 [class.ctor] p5:
5733/// A defaulted default constructor for a class X is defined as deleted if
5734/// X is a union and all of its variant members are of const-qualified type.
5735bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005736 // This is a silly definition, because it gives an empty union a deleted
5737 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005738 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005739 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005740 if (Diagnose)
5741 S.Diag(MD->getParent()->getLocation(),
5742 diag::note_deleted_default_ctor_all_const)
5743 << MD->getParent() << /*not anonymous union*/0;
5744 return true;
5745 }
5746 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005747}
5748
5749/// Determine whether a defaulted special member function should be defined as
5750/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5751/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005752bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5753 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005754 if (MD->isInvalidDecl())
5755 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005756 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005757 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005758 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005759 return false;
5760
Richard Smithd951a1d2012-02-18 02:02:13 +00005761 // C++11 [expr.lambda.prim]p19:
5762 // The closure type associated with a lambda-expression has a
5763 // deleted (8.4.3) default constructor and a deleted copy
5764 // assignment operator.
5765 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005766 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5767 if (Diagnose)
5768 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005769 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005770 }
5771
Richard Smith6f1e2c62012-04-02 20:59:25 +00005772 // For an anonymous struct or union, the copy and assignment special members
5773 // will never be used, so skip the check. For an anonymous union declared at
5774 // namespace scope, the constructor and destructor are used.
5775 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5776 RD->isAnonymousStructOrUnion())
5777 return false;
5778
Richard Smith852265f2012-03-30 20:53:28 +00005779 // C++11 [class.copy]p7, p18:
5780 // If the class definition declares a move constructor or move assignment
5781 // operator, an implicitly declared copy constructor or copy assignment
5782 // operator is defined as deleted.
5783 if (MD->isImplicit() &&
5784 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005785 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005786
5787 // In Microsoft mode, a user-declared move only causes the deletion of the
5788 // corresponding copy operation, not both copy operations.
5789 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005790 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005791 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005792
5793 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005794 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005795 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005796 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005797 break;
5798 }
5799 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005800 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005801 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005802 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005803 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005804
5805 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005806 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005807 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005808 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005809 break;
5810 }
5811 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005812 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005813 }
5814
5815 if (UserDeclaredMove) {
5816 Diag(UserDeclaredMove->getLocation(),
5817 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005818 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005819 << UserDeclaredMove->isMoveAssignmentOperator();
5820 return true;
5821 }
5822 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005823
Richard Smith6f1e2c62012-04-02 20:59:25 +00005824 // Do access control from the special member function
5825 ContextRAII MethodContext(*this, MD);
5826
Richard Smith921bd202012-02-26 09:11:52 +00005827 // C++11 [class.dtor]p5:
5828 // -- for a virtual destructor, lookup of the non-array deallocation function
5829 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005830 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005831 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005832 DeclarationName Name =
5833 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5834 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005835 OperatorDelete, false)) {
5836 if (Diagnose)
5837 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005838 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005839 }
Richard Smith921bd202012-02-26 09:11:52 +00005840 }
5841
Richard Smith852265f2012-03-30 20:53:28 +00005842 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005843
Aaron Ballman574705e2014-03-13 15:41:46 +00005844 for (auto &BI : RD->bases())
5845 if (!BI.isVirtual() &&
5846 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005847 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005848
Richard Smithd1627032013-07-22 18:06:23 +00005849 // Per DR1611, do not consider virtual bases of constructors of abstract
5850 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005851 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005852 for (auto &BI : RD->vbases())
5853 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005854 return true;
5855 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005856
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005857 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005858 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005859 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005860 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005861
Richard Smithd951a1d2012-02-18 02:02:13 +00005862 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005863 return true;
5864
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005865 if (getLangOpts().CUDA) {
5866 // We should delete the special member in CUDA mode if target inference
5867 // failed.
5868 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5869 Diagnose);
5870 }
5871
Alexis Huntea6f0322011-05-11 22:34:38 +00005872 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005873}
5874
Richard Smith92f241f2012-12-08 02:53:02 +00005875/// Perform lookup for a special member of the specified kind, and determine
5876/// whether it is trivial. If the triviality can be determined without the
5877/// lookup, skip it. This is intended for use when determining whether a
5878/// special member of a containing object is trivial, and thus does not ever
5879/// perform overload resolution for default constructors.
5880///
5881/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5882/// member that was most likely to be intended to be trivial, if any.
5883static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5884 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005885 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005886 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005887 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005888
5889 switch (CSM) {
5890 case Sema::CXXInvalid:
5891 llvm_unreachable("not a special member");
5892
5893 case Sema::CXXDefaultConstructor:
5894 // C++11 [class.ctor]p5:
5895 // A default constructor is trivial if:
5896 // - all the [direct subobjects] have trivial default constructors
5897 //
5898 // Note, no overload resolution is performed in this case.
5899 if (RD->hasTrivialDefaultConstructor())
5900 return true;
5901
5902 if (Selected) {
5903 // If there's a default constructor which could have been trivial, dig it
5904 // out. Otherwise, if there's any user-provided default constructor, point
5905 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005906 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005907 if (RD->needsImplicitDefaultConstructor())
5908 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005909 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005910 if (!CI->isDefaultConstructor())
5911 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005912 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005913 if (!DefCtor->isUserProvided())
5914 break;
5915 }
5916
5917 *Selected = DefCtor;
5918 }
5919
5920 return false;
5921
5922 case Sema::CXXDestructor:
5923 // C++11 [class.dtor]p5:
5924 // A destructor is trivial if:
5925 // - all the direct [subobjects] have trivial destructors
5926 if (RD->hasTrivialDestructor())
5927 return true;
5928
5929 if (Selected) {
5930 if (RD->needsImplicitDestructor())
5931 S.DeclareImplicitDestructor(RD);
5932 *Selected = RD->getDestructor();
5933 }
5934
5935 return false;
5936
5937 case Sema::CXXCopyConstructor:
5938 // C++11 [class.copy]p12:
5939 // A copy constructor is trivial if:
5940 // - the constructor selected to copy each direct [subobject] is trivial
5941 if (RD->hasTrivialCopyConstructor()) {
5942 if (Quals == Qualifiers::Const)
5943 // We must either select the trivial copy constructor or reach an
5944 // ambiguity; no need to actually perform overload resolution.
5945 return true;
5946 } else if (!Selected) {
5947 return false;
5948 }
5949 // In C++98, we are not supposed to perform overload resolution here, but we
5950 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5951 // cases like B as having a non-trivial copy constructor:
5952 // struct A { template<typename T> A(T&); };
5953 // struct B { mutable A a; };
5954 goto NeedOverloadResolution;
5955
5956 case Sema::CXXCopyAssignment:
5957 // C++11 [class.copy]p25:
5958 // A copy assignment operator is trivial if:
5959 // - the assignment operator selected to copy each direct [subobject] is
5960 // trivial
5961 if (RD->hasTrivialCopyAssignment()) {
5962 if (Quals == Qualifiers::Const)
5963 return true;
5964 } else if (!Selected) {
5965 return false;
5966 }
5967 // In C++98, we are not supposed to perform overload resolution here, but we
5968 // treat that as a language defect.
5969 goto NeedOverloadResolution;
5970
5971 case Sema::CXXMoveConstructor:
5972 case Sema::CXXMoveAssignment:
5973 NeedOverloadResolution:
5974 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005975 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005976
5977 // The standard doesn't describe how to behave if the lookup is ambiguous.
5978 // We treat it as not making the member non-trivial, just like the standard
5979 // mandates for the default constructor. This should rarely matter, because
5980 // the member will also be deleted.
5981 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5982 return true;
5983
5984 if (!SMOR->getMethod()) {
5985 assert(SMOR->getKind() ==
5986 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5987 return false;
5988 }
5989
5990 // We deliberately don't check if we found a deleted special member. We're
5991 // not supposed to!
5992 if (Selected)
5993 *Selected = SMOR->getMethod();
5994 return SMOR->getMethod()->isTrivial();
5995 }
5996
5997 llvm_unreachable("unknown special method kind");
5998}
5999
Benjamin Kramer3e350262013-02-15 12:30:38 +00006000static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006001 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006002 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006003 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006004
6005 // Look for constructor templates.
6006 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6007 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6008 if (CXXConstructorDecl *CD =
6009 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6010 return CD;
6011 }
6012
Craig Topperc3ec1492014-05-26 06:22:03 +00006013 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006014}
6015
6016/// The kind of subobject we are checking for triviality. The values of this
6017/// enumeration are used in diagnostics.
6018enum TrivialSubobjectKind {
6019 /// The subobject is a base class.
6020 TSK_BaseClass,
6021 /// The subobject is a non-static data member.
6022 TSK_Field,
6023 /// The object is actually the complete object.
6024 TSK_CompleteObject
6025};
6026
6027/// Check whether the special member selected for a given type would be trivial.
6028static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006029 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006030 Sema::CXXSpecialMember CSM,
6031 TrivialSubobjectKind Kind,
6032 bool Diagnose) {
6033 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6034 if (!SubRD)
6035 return true;
6036
6037 CXXMethodDecl *Selected;
6038 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006039 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006040 return true;
6041
6042 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006043 if (ConstRHS)
6044 SubType.addConst();
6045
Richard Smith92f241f2012-12-08 02:53:02 +00006046 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6047 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6048 << Kind << SubType.getUnqualifiedType();
6049 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6050 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6051 } else if (!Selected)
6052 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6053 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6054 else if (Selected->isUserProvided()) {
6055 if (Kind == TSK_CompleteObject)
6056 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6057 << Kind << SubType.getUnqualifiedType() << CSM;
6058 else {
6059 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6060 << Kind << SubType.getUnqualifiedType() << CSM;
6061 S.Diag(Selected->getLocation(), diag::note_declared_at);
6062 }
6063 } else {
6064 if (Kind != TSK_CompleteObject)
6065 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6066 << Kind << SubType.getUnqualifiedType() << CSM;
6067
6068 // Explain why the defaulted or deleted special member isn't trivial.
6069 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6070 }
6071 }
6072
6073 return false;
6074}
6075
6076/// Check whether the members of a class type allow a special member to be
6077/// trivial.
6078static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6079 Sema::CXXSpecialMember CSM,
6080 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006081 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006082 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6083 continue;
6084
6085 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6086
6087 // Pretend anonymous struct or union members are members of this class.
6088 if (FI->isAnonymousStructOrUnion()) {
6089 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6090 CSM, ConstArg, Diagnose))
6091 return false;
6092 continue;
6093 }
6094
6095 // C++11 [class.ctor]p5:
6096 // A default constructor is trivial if [...]
6097 // -- no non-static data member of its class has a
6098 // brace-or-equal-initializer
6099 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6100 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006101 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006102 return false;
6103 }
6104
6105 // Objective C ARC 4.3.5:
6106 // [...] nontrivally ownership-qualified types are [...] not trivially
6107 // default constructible, copy constructible, move constructible, copy
6108 // assignable, move assignable, or destructible [...]
6109 if (S.getLangOpts().ObjCAutoRefCount &&
6110 FieldType.hasNonTrivialObjCLifetime()) {
6111 if (Diagnose)
6112 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6113 << RD << FieldType.getObjCLifetime();
6114 return false;
6115 }
6116
Richard Smith41c35d62013-11-27 03:39:20 +00006117 bool ConstRHS = ConstArg && !FI->isMutable();
6118 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6119 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006120 return false;
6121 }
6122
6123 return true;
6124}
6125
6126/// Diagnose why the specified class does not have a trivial special member of
6127/// the given kind.
6128void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6129 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006130
Richard Smith41c35d62013-11-27 03:39:20 +00006131 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6132 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006133 TSK_CompleteObject, /*Diagnose*/true);
6134}
6135
6136/// Determine whether a defaulted or deleted special member function is trivial,
6137/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6138/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6139bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6140 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006141 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6142
6143 CXXRecordDecl *RD = MD->getParent();
6144
6145 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006146
Richard Smith2002bfe2013-11-04 02:02:27 +00006147 // C++11 [class.copy]p12, p25: [DR1593]
6148 // A [special member] is trivial if [...] its parameter-type-list is
6149 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006150 switch (CSM) {
6151 case CXXDefaultConstructor:
6152 case CXXDestructor:
6153 // Trivial default constructors and destructors cannot have parameters.
6154 break;
6155
6156 case CXXCopyConstructor:
6157 case CXXCopyAssignment: {
6158 // Trivial copy operations always have const, non-volatile parameter types.
6159 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006160 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006161 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6162 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6163 if (Diagnose)
6164 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6165 << Param0->getSourceRange() << Param0->getType()
6166 << Context.getLValueReferenceType(
6167 Context.getRecordType(RD).withConst());
6168 return false;
6169 }
6170 break;
6171 }
6172
6173 case CXXMoveConstructor:
6174 case CXXMoveAssignment: {
6175 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006176 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006177 const RValueReferenceType *RT =
6178 Param0->getType()->getAs<RValueReferenceType>();
6179 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6180 if (Diagnose)
6181 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6182 << Param0->getSourceRange() << Param0->getType()
6183 << Context.getRValueReferenceType(Context.getRecordType(RD));
6184 return false;
6185 }
6186 break;
6187 }
6188
6189 case CXXInvalid:
6190 llvm_unreachable("not a special member");
6191 }
6192
Richard Smith92f241f2012-12-08 02:53:02 +00006193 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6194 if (Diagnose)
6195 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6196 diag::note_nontrivial_default_arg)
6197 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6198 return false;
6199 }
6200 if (MD->isVariadic()) {
6201 if (Diagnose)
6202 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6203 return false;
6204 }
6205
6206 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6207 // A copy/move [constructor or assignment operator] is trivial if
6208 // -- the [member] selected to copy/move each direct base class subobject
6209 // is trivial
6210 //
6211 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6212 // A [default constructor or destructor] is trivial if
6213 // -- all the direct base classes have trivial [default constructors or
6214 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006215 for (const auto &BI : RD->bases())
6216 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006217 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006218 return false;
6219
6220 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6221 // A copy/move [constructor or assignment operator] for a class X is
6222 // trivial if
6223 // -- for each non-static data member of X that is of class type (or array
6224 // thereof), the constructor selected to copy/move that member is
6225 // trivial
6226 //
6227 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6228 // A [default constructor or destructor] is trivial if
6229 // -- for all of the non-static data members of its class that are of class
6230 // type (or array thereof), each such class has a trivial [default
6231 // constructor or destructor]
6232 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6233 return false;
6234
6235 // C++11 [class.dtor]p5:
6236 // A destructor is trivial if [...]
6237 // -- the destructor is not virtual
6238 if (CSM == CXXDestructor && MD->isVirtual()) {
6239 if (Diagnose)
6240 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6241 return false;
6242 }
6243
6244 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6245 // A [special member] for class X is trivial if [...]
6246 // -- class X has no virtual functions and no virtual base classes
6247 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6248 if (!Diagnose)
6249 return false;
6250
6251 if (RD->getNumVBases()) {
6252 // Check for virtual bases. We already know that the corresponding
6253 // member in all bases is trivial, so vbases must all be direct.
6254 CXXBaseSpecifier &BS = *RD->vbases_begin();
6255 assert(BS.isVirtual());
6256 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6257 return false;
6258 }
6259
6260 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006261 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006262 if (MI->isVirtual()) {
6263 SourceLocation MLoc = MI->getLocStart();
6264 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6265 return false;
6266 }
6267 }
6268
6269 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6270 }
6271
6272 // Looks like it's trivial!
6273 return true;
6274}
6275
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006276/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006277namespace {
6278 struct FindHiddenVirtualMethodData {
6279 Sema *S;
6280 CXXMethodDecl *Method;
6281 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006282 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006283 };
6284}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006285
David Blaikie282c92a2012-10-19 00:53:08 +00006286/// \brief Check whether any most overriden method from MD in Methods
6287static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006288 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006289 if (MD->size_overridden_methods() == 0)
6290 return Methods.count(MD->getCanonicalDecl());
6291 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6292 E = MD->end_overridden_methods();
6293 I != E; ++I)
6294 if (CheckMostOverridenMethods(*I, Methods))
6295 return true;
6296 return false;
6297}
6298
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006299/// \brief Member lookup function that determines whether a given C++
6300/// method overloads virtual methods in a base class without overriding any,
6301/// to be used with CXXRecordDecl::lookupInBases().
6302static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6303 CXXBasePath &Path,
6304 void *UserData) {
6305 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6306
6307 FindHiddenVirtualMethodData &Data
6308 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6309
6310 DeclarationName Name = Data.Method->getDeclName();
6311 assert(Name.getNameKind() == DeclarationName::Identifier);
6312
6313 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006314 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006315 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006316 !Path.Decls.empty();
6317 Path.Decls = Path.Decls.slice(1)) {
6318 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006319 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006320 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006321 foundSameNameMethod = true;
6322 // Interested only in hidden virtual methods.
6323 if (!MD->isVirtual())
6324 continue;
6325 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006326 // don't warn about the other overloaded methods. Clang deviates from GCC
6327 // by only diagnosing overloads of inherited virtual functions that do not
6328 // override any other virtual functions in the base. GCC's
6329 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6330 // function from a base class. These cases may be better served by a
6331 // warning (not specific to virtual functions) on call sites when the call
6332 // would select a different function from the base class, were it visible.
6333 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006334 if (!Data.S->IsOverload(Data.Method, MD, false))
6335 return true;
6336 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006337 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006338 overloadedMethods.push_back(MD);
6339 }
6340 }
6341
6342 if (foundSameNameMethod)
6343 Data.OverloadedMethods.append(overloadedMethods.begin(),
6344 overloadedMethods.end());
6345 return foundSameNameMethod;
6346}
6347
David Blaikie282c92a2012-10-19 00:53:08 +00006348/// \brief Add the most overriden methods from MD to Methods
6349static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006350 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006351 if (MD->size_overridden_methods() == 0)
6352 Methods.insert(MD->getCanonicalDecl());
6353 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6354 E = MD->end_overridden_methods();
6355 I != E; ++I)
6356 AddMostOverridenMethods(*I, Methods);
6357}
6358
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006359/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006360/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006361void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6362 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006363 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006364 return;
6365
6366 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6367 /*bool RecordPaths=*/false,
6368 /*bool DetectVirtual=*/false);
6369 FindHiddenVirtualMethodData Data;
6370 Data.Method = MD;
6371 Data.S = this;
6372
6373 // Keep the base methods that were overriden or introduced in the subclass
6374 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006375 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006376 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6377 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6378 NamedDecl *ND = *I;
6379 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006380 ND = shad->getTargetDecl();
6381 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6382 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006383 }
6384
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006385 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6386 OverloadedMethods = Data.OverloadedMethods;
6387}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006388
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006389void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6390 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6391 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6392 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6393 PartialDiagnostic PD = PDiag(
6394 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6395 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6396 Diag(overloadedMD->getLocation(), PD);
6397 }
6398}
6399
6400/// \brief Diagnose methods which overload virtual methods in a base class
6401/// without overriding any.
6402void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6403 if (MD->isInvalidDecl())
6404 return;
6405
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006406 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006407 return;
6408
6409 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6410 FindHiddenVirtualMethods(MD, OverloadedMethods);
6411 if (!OverloadedMethods.empty()) {
6412 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6413 << MD << (OverloadedMethods.size() > 1);
6414
6415 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006416 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006417}
6418
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006419void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006420 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006421 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006422 SourceLocation RBrac,
6423 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006424 if (!TagDecl)
6425 return;
Mike Stump11289f42009-09-09 15:08:12 +00006426
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006427 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006428
Rafael Espindola06e1b132012-07-12 04:32:30 +00006429 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6430 if (l->getKind() != AttributeList::AT_Visibility)
6431 continue;
6432 l->setInvalid();
6433 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6434 l->getName();
6435 }
6436
David Blaikie751c5582011-09-22 02:58:26 +00006437 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006438 // strict aliasing violation!
6439 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006440 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006441
Douglas Gregor0be31a22010-07-02 17:43:08 +00006442 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006443 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006444}
6445
Douglas Gregor05379422008-11-03 17:51:48 +00006446/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6447/// special functions, such as the default constructor, copy
6448/// constructor, or destructor, to the given C++ class (C++
6449/// [special]p1). This routine can only be executed just before the
6450/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006451void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006452 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006453 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006454
Richard Smith6b02d462012-12-08 08:32:28 +00006455 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006456 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006457
Richard Smith6b02d462012-12-08 08:32:28 +00006458 // If the properties or semantics of the copy constructor couldn't be
6459 // determined while the class was being declared, force a declaration
6460 // of it now.
6461 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6462 DeclareImplicitCopyConstructor(ClassDecl);
6463 }
6464
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006465 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006466 ++ASTContext::NumImplicitMoveConstructors;
6467
Richard Smith6b02d462012-12-08 08:32:28 +00006468 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6469 DeclareImplicitMoveConstructor(ClassDecl);
6470 }
6471
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006472 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6473 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006474
6475 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006476 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006477 // it shows up in the right place in the vtable and that we diagnose
6478 // problems with the implicit exception specification.
6479 if (ClassDecl->isDynamicClass() ||
6480 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006481 DeclareImplicitCopyAssignment(ClassDecl);
6482 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006483
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006484 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006485 ++ASTContext::NumImplicitMoveAssignmentOperators;
6486
6487 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006488 if (ClassDecl->isDynamicClass() ||
6489 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006490 DeclareImplicitMoveAssignment(ClassDecl);
6491 }
6492
Douglas Gregor7454c562010-07-02 20:37:36 +00006493 if (!ClassDecl->hasUserDeclaredDestructor()) {
6494 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006495
6496 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006497 // have to declare the destructor immediately. This ensures that, e.g., it
6498 // shows up in the right place in the vtable and that we diagnose problems
6499 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006500 if (ClassDecl->isDynamicClass() ||
6501 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006502 DeclareImplicitDestructor(ClassDecl);
6503 }
Douglas Gregor05379422008-11-03 17:51:48 +00006504}
6505
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006506unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006507 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006508 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006509
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006510 // The order of template parameters is not important here. All names
6511 // get added to the same scope.
6512 SmallVector<TemplateParameterList *, 4> ParameterLists;
6513
6514 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6515 D = TD->getTemplatedDecl();
6516
6517 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6518 ParameterLists.push_back(PSD->getTemplateParameters());
6519
6520 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6521 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6522 ParameterLists.push_back(DD->getTemplateParameterList(i));
6523
6524 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6525 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6526 ParameterLists.push_back(FTD->getTemplateParameters());
6527 }
6528 }
6529
6530 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6531 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6532 ParameterLists.push_back(TD->getTemplateParameterList(i));
6533
6534 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6535 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6536 ParameterLists.push_back(CTD->getTemplateParameters());
6537 }
6538 }
6539
6540 unsigned Count = 0;
6541 for (TemplateParameterList *Params : ParameterLists) {
6542 if (Params->size() > 0)
6543 // Ignore explicit specializations; they don't contribute to the template
6544 // depth.
6545 ++Count;
6546 for (NamedDecl *Param : *Params) {
6547 if (Param->getDeclName()) {
6548 S->AddDecl(Param);
6549 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006550 }
6551 }
6552 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006553
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006554 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006555}
6556
John McCall48871652010-08-21 09:40:31 +00006557void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006558 if (!RecordD) return;
6559 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006560 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006561 PushDeclContext(S, Record);
6562}
6563
John McCall48871652010-08-21 09:40:31 +00006564void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006565 if (!RecordD) return;
6566 PopDeclContext();
6567}
6568
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006569/// This is used to implement the constant expression evaluation part of the
6570/// attribute enable_if extension. There is nothing in standard C++ which would
6571/// require reentering parameters.
6572void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6573 if (!Param)
6574 return;
6575
6576 S->AddDecl(Param);
6577 if (Param->getDeclName())
6578 IdResolver.AddDecl(Param);
6579}
6580
Douglas Gregor4d87df52008-12-16 21:30:33 +00006581/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6582/// parsing a top-level (non-nested) C++ class, and we are now
6583/// parsing those parts of the given Method declaration that could
6584/// not be parsed earlier (C++ [class.mem]p2), such as default
6585/// arguments. This action should enter the scope of the given
6586/// Method declaration as if we had just parsed the qualified method
6587/// name. However, it should not bring the parameters into scope;
6588/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006589void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006590}
6591
6592/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6593/// C++ method declaration. We're (re-)introducing the given
6594/// function parameter into scope for use in parsing later parts of
6595/// the method declaration. For example, we could see an
6596/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006597void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006598 if (!ParamD)
6599 return;
Mike Stump11289f42009-09-09 15:08:12 +00006600
John McCall48871652010-08-21 09:40:31 +00006601 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006602
6603 // If this parameter has an unparsed default argument, clear it out
6604 // to make way for the parsed default argument.
6605 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006606 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006607
John McCall48871652010-08-21 09:40:31 +00006608 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006609 if (Param->getDeclName())
6610 IdResolver.AddDecl(Param);
6611}
6612
6613/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6614/// processing the delayed method declaration for Method. The method
6615/// declaration is now considered finished. There may be a separate
6616/// ActOnStartOfFunctionDef action later (not necessarily
6617/// immediately!) for this method, if it was also defined inside the
6618/// class body.
John McCall48871652010-08-21 09:40:31 +00006619void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006620 if (!MethodD)
6621 return;
Mike Stump11289f42009-09-09 15:08:12 +00006622
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006623 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006624
John McCall48871652010-08-21 09:40:31 +00006625 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006626
6627 // Now that we have our default arguments, check the constructor
6628 // again. It could produce additional diagnostics or affect whether
6629 // the class has implicitly-declared destructors, among other
6630 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006631 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6632 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006633
6634 // Check the default arguments, which we may have added.
6635 if (!Method->isInvalidDecl())
6636 CheckCXXDefaultArguments(Method);
6637}
6638
Douglas Gregor831c93f2008-11-05 20:51:48 +00006639/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006640/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006641/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006642/// emit diagnostics and set the invalid bit to true. In any case, the type
6643/// will be updated to reflect a well-formed type for the constructor and
6644/// returned.
6645QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006646 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006647 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006648
6649 // C++ [class.ctor]p3:
6650 // A constructor shall not be virtual (10.3) or static (9.4). A
6651 // constructor can be invoked for a const, volatile or const
6652 // volatile object. A constructor shall not be declared const,
6653 // volatile, or const volatile (9.3.2).
6654 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006655 if (!D.isInvalidType())
6656 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6657 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6658 << SourceRange(D.getIdentifierLoc());
6659 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006660 }
John McCall8e7d6562010-08-26 03:08:43 +00006661 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006662 if (!D.isInvalidType())
6663 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6664 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6665 << SourceRange(D.getIdentifierLoc());
6666 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006667 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006668 }
Mike Stump11289f42009-09-09 15:08:12 +00006669
David Majnemer03f705f2014-07-08 18:18:04 +00006670 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6671 diagnoseIgnoredQualifiers(
6672 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6673 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6674 D.getDeclSpec().getRestrictSpecLoc(),
6675 D.getDeclSpec().getAtomicSpecLoc());
6676 D.setInvalidType();
6677 }
6678
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006679 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006680 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006681 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006682 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6683 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006684 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006685 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006687 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006688 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6689 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006690 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006691 }
Mike Stump11289f42009-09-09 15:08:12 +00006692
Douglas Gregordb9d6642011-01-26 05:01:58 +00006693 // C++0x [class.ctor]p4:
6694 // A constructor shall not be declared with a ref-qualifier.
6695 if (FTI.hasRefQualifier()) {
6696 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6697 << FTI.RefQualifierIsLValueRef
6698 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6699 D.setInvalidType();
6700 }
6701
Douglas Gregor831c93f2008-11-05 20:51:48 +00006702 // Rebuild the function type "R" without any type qualifiers (in
6703 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006704 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006705 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006706 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006707 return R;
6708
6709 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6710 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006711 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006712
6713 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006714}
6715
Douglas Gregor4d87df52008-12-16 21:30:33 +00006716/// CheckConstructor - Checks a fully-formed constructor for
6717/// well-formedness, issuing any diagnostics required. Returns true if
6718/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006719void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006720 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006721 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6722 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006723 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006724
6725 // C++ [class.copy]p3:
6726 // A declaration of a constructor for a class X is ill-formed if
6727 // its first parameter is of type (optionally cv-qualified) X and
6728 // either there are no other parameters or else all other
6729 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006730 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006731 ((Constructor->getNumParams() == 1) ||
6732 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006733 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6734 Constructor->getTemplateSpecializationKind()
6735 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006736 QualType ParamType = Constructor->getParamDecl(0)->getType();
6737 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6738 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006739 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006740 const char *ConstRef
6741 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6742 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006743 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006744 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006745
6746 // FIXME: Rather that making the constructor invalid, we should endeavor
6747 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006748 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006749 }
6750 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006751}
6752
John McCalldeb646e2010-08-04 01:04:25 +00006753/// CheckDestructor - Checks a fully-formed destructor definition for
6754/// well-formedness, issuing any diagnostics required. Returns true
6755/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006756bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006757 CXXRecordDecl *RD = Destructor->getParent();
6758
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006759 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006760 SourceLocation Loc;
6761
6762 if (!Destructor->isImplicit())
6763 Loc = Destructor->getLocation();
6764 else
6765 Loc = RD->getLocation();
6766
6767 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006768 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006769 DeclarationName Name =
6770 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006771 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006772 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006773 // If there's no class-specific operator delete, look up the global
6774 // non-array delete.
6775 if (!OperatorDelete)
6776 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006777
Eli Friedmanfa0df832012-02-02 03:46:19 +00006778 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006779
6780 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006781 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006782
6783 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006784}
6785
Douglas Gregor831c93f2008-11-05 20:51:48 +00006786/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6787/// the well-formednes of the destructor declarator @p D with type @p
6788/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006789/// emit diagnostics and set the declarator to invalid. Even if this happens,
6790/// will be updated to reflect a well-formed type for the destructor and
6791/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006792QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006793 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006794 // C++ [class.dtor]p1:
6795 // [...] A typedef-name that names a class is a class-name
6796 // (7.1.3); however, a typedef-name that names a class shall not
6797 // be used as the identifier in the declarator for a destructor
6798 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006799 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006800 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006801 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006802 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006803 else if (const TemplateSpecializationType *TST =
6804 DeclaratorType->getAs<TemplateSpecializationType>())
6805 if (TST->isTypeAlias())
6806 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6807 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006808
6809 // C++ [class.dtor]p2:
6810 // A destructor is used to destroy objects of its class type. A
6811 // destructor takes no parameters, and no return type can be
6812 // specified for it (not even void). The address of a destructor
6813 // shall not be taken. A destructor shall not be static. A
6814 // destructor can be invoked for a const, volatile or const
6815 // volatile object. A destructor shall not be declared const,
6816 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006817 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006818 if (!D.isInvalidType())
6819 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6820 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006821 << SourceRange(D.getIdentifierLoc())
6822 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6823
John McCall8e7d6562010-08-26 03:08:43 +00006824 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006825 }
David Majnemer03f705f2014-07-08 18:18:04 +00006826 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006827 // Destructors don't have return types, but the parser will
6828 // happily parse something like:
6829 //
6830 // class X {
6831 // float ~X();
6832 // };
6833 //
6834 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006835 if (D.getDeclSpec().hasTypeSpecifier())
6836 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6837 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6838 << SourceRange(D.getIdentifierLoc());
6839 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6840 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6841 SourceLocation(),
6842 D.getDeclSpec().getConstSpecLoc(),
6843 D.getDeclSpec().getVolatileSpecLoc(),
6844 D.getDeclSpec().getRestrictSpecLoc(),
6845 D.getDeclSpec().getAtomicSpecLoc());
6846 D.setInvalidType();
6847 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006848 }
Mike Stump11289f42009-09-09 15:08:12 +00006849
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006850 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006851 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006852 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006853 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6854 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006855 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006856 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006858 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006859 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6860 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006861 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006862 }
6863
Douglas Gregordb9d6642011-01-26 05:01:58 +00006864 // C++0x [class.dtor]p2:
6865 // A destructor shall not be declared with a ref-qualifier.
6866 if (FTI.hasRefQualifier()) {
6867 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6868 << FTI.RefQualifierIsLValueRef
6869 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6870 D.setInvalidType();
6871 }
6872
Douglas Gregor831c93f2008-11-05 20:51:48 +00006873 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006874 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006875 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6876
6877 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006878 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006879 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006880 }
6881
Mike Stump11289f42009-09-09 15:08:12 +00006882 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006883 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006884 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006885 D.setInvalidType();
6886 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006887
6888 // Rebuild the function type "R" without any type qualifiers or
6889 // parameters (in case any of the errors above fired) and with
6890 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006891 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006892 if (!D.isInvalidType())
6893 return R;
6894
Douglas Gregor95755162010-07-01 05:10:53 +00006895 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006896 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6897 EPI.Variadic = false;
6898 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006899 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006900 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006901}
6902
Richard Smitha865a162014-12-19 02:07:47 +00006903static void extendLeft(SourceRange &R, const SourceRange &Before) {
6904 if (Before.isInvalid())
6905 return;
6906 R.setBegin(Before.getBegin());
6907 if (R.getEnd().isInvalid())
6908 R.setEnd(Before.getEnd());
6909}
6910
6911static void extendRight(SourceRange &R, const SourceRange &After) {
6912 if (After.isInvalid())
6913 return;
6914 if (R.getBegin().isInvalid())
6915 R.setBegin(After.getBegin());
6916 R.setEnd(After.getEnd());
6917}
6918
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006919/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6920/// well-formednes of the conversion function declarator @p D with
6921/// type @p R. If there are any errors in the declarator, this routine
6922/// will emit diagnostics and return true. Otherwise, it will return
6923/// false. Either way, the type @p R will be updated to reflect a
6924/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006925void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006926 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006927 // C++ [class.conv.fct]p1:
6928 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006929 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006930 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006931 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006932 if (!D.isInvalidType())
6933 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006934 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6935 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006936 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006937 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006938 }
John McCall212fa2e2010-04-13 00:04:31 +00006939
Richard Smitha865a162014-12-19 02:07:47 +00006940 TypeSourceInfo *ConvTSI = nullptr;
6941 QualType ConvType =
6942 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006943
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006944 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006945 // Conversion functions don't have return types, but the parser will
6946 // happily parse something like:
6947 //
6948 // class X {
6949 // float operator bool();
6950 // };
6951 //
6952 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006953 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6954 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6955 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006956 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006957 }
6958
John McCall212fa2e2010-04-13 00:04:31 +00006959 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6960
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006961 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006962 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006963 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6964
6965 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006966 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006967 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006968 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006969 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006970 D.setInvalidType();
6971 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006972
John McCall212fa2e2010-04-13 00:04:31 +00006973 // Diagnose "&operator bool()" and other such nonsense. This
6974 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006975 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006976 bool NeedsTypedef = false;
6977 SourceRange Before, After;
6978
6979 // Walk the chunks and extract information on them for our diagnostic.
6980 bool PastFunctionChunk = false;
6981 for (auto &Chunk : D.type_objects()) {
6982 switch (Chunk.Kind) {
6983 case DeclaratorChunk::Function:
6984 if (!PastFunctionChunk) {
6985 if (Chunk.Fun.HasTrailingReturnType) {
6986 TypeSourceInfo *TRT = nullptr;
6987 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6988 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6989 }
6990 PastFunctionChunk = true;
6991 break;
6992 }
6993 // Fall through.
6994 case DeclaratorChunk::Array:
6995 NeedsTypedef = true;
6996 extendRight(After, Chunk.getSourceRange());
6997 break;
6998
6999 case DeclaratorChunk::Pointer:
7000 case DeclaratorChunk::BlockPointer:
7001 case DeclaratorChunk::Reference:
7002 case DeclaratorChunk::MemberPointer:
7003 extendLeft(Before, Chunk.getSourceRange());
7004 break;
7005
7006 case DeclaratorChunk::Paren:
7007 extendLeft(Before, Chunk.Loc);
7008 extendRight(After, Chunk.EndLoc);
7009 break;
7010 }
7011 }
7012
7013 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7014 After.isValid() ? After.getBegin() :
7015 D.getIdentifierLoc();
7016 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7017 DB << Before << After;
7018
7019 if (!NeedsTypedef) {
7020 DB << /*don't need a typedef*/0;
7021
7022 // If we can provide a correct fix-it hint, do so.
7023 if (After.isInvalid() && ConvTSI) {
7024 SourceLocation InsertLoc =
7025 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7026 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7027 << FixItHint::CreateInsertionFromRange(
7028 InsertLoc, CharSourceRange::getTokenRange(Before))
7029 << FixItHint::CreateRemoval(Before);
7030 }
7031 } else if (!Proto->getReturnType()->isDependentType()) {
7032 DB << /*typedef*/1 << Proto->getReturnType();
7033 } else if (getLangOpts().CPlusPlus11) {
7034 DB << /*alias template*/2 << Proto->getReturnType();
7035 } else {
7036 DB << /*might not be fixable*/3;
7037 }
7038
7039 // Recover by incorporating the other type chunks into the result type.
7040 // Note, this does *not* change the name of the function. This is compatible
7041 // with the GCC extension:
7042 // struct S { &operator int(); } s;
7043 // int &r = s.operator int(); // ok in GCC
7044 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007045 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007046 }
7047
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007048 // C++ [class.conv.fct]p4:
7049 // The conversion-type-id shall not represent a function type nor
7050 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007051 if (ConvType->isArrayType()) {
7052 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7053 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007054 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007055 } else if (ConvType->isFunctionType()) {
7056 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7057 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007058 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007059 }
7060
7061 // Rebuild the function type "R" without any parameters (in case any
7062 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007063 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007064 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007065 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007066
Douglas Gregor5fb53972009-01-14 15:45:31 +00007067 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007068 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007069 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007070 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007071 diag::warn_cxx98_compat_explicit_conversion_functions :
7072 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007073 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007074}
7075
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007076/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7077/// the declaration of the given C++ conversion function. This routine
7078/// is responsible for recording the conversion function in the C++
7079/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007080Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007081 assert(Conversion && "Expected to receive a conversion function declaration");
7082
Douglas Gregor4287b372008-12-12 08:25:50 +00007083 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007084
7085 // Make sure we aren't redeclaring the conversion function.
7086 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007087
7088 // C++ [class.conv.fct]p1:
7089 // [...] A conversion function is never used to convert a
7090 // (possibly cv-qualified) object to the (possibly cv-qualified)
7091 // same object type (or a reference to it), to a (possibly
7092 // cv-qualified) base class of that type (or a reference to it),
7093 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007094 // FIXME: Suppress this warning if the conversion function ends up being a
7095 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007096 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007097 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007098 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007099 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007100 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7101 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007102 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007103 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007104 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7105 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007106 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007107 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007108 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007109 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007110 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007111 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007112 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007113 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007114 }
7115
Douglas Gregor457104e2010-09-29 04:25:11 +00007116 if (FunctionTemplateDecl *ConversionTemplate
7117 = Conversion->getDescribedFunctionTemplate())
7118 return ConversionTemplate;
7119
John McCall48871652010-08-21 09:40:31 +00007120 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007121}
7122
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007123//===----------------------------------------------------------------------===//
7124// Namespace Handling
7125//===----------------------------------------------------------------------===//
7126
Richard Smith45bb8852012-10-04 22:13:39 +00007127/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7128/// reopened.
7129static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7130 SourceLocation Loc,
7131 IdentifierInfo *II, bool *IsInline,
7132 NamespaceDecl *PrevNS) {
7133 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007134
Richard Smithf501cc32012-10-05 01:46:25 +00007135 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7136 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7137 // inline namespaces, with the intention of bringing names into namespace std.
7138 //
7139 // We support this just well enough to get that case working; this is not
7140 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007141 if (*IsInline && II && II->getName().startswith("__atomic") &&
7142 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007143 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007144 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7145 NS = NS->getPreviousDecl())
7146 NS->setInline(*IsInline);
7147 // Patch up the lookup table for the containing namespace. This isn't really
7148 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007149 for (auto *I : PrevNS->decls())
7150 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007151 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7152 return;
7153 }
7154
7155 if (PrevNS->isInline())
7156 // The user probably just forgot the 'inline', so suggest that it
7157 // be added back.
7158 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7159 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7160 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007161 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007162
7163 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7164 *IsInline = PrevNS->isInline();
7165}
John McCallb1be5232010-08-26 09:15:37 +00007166
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007167/// ActOnStartNamespaceDef - This is called at the start of a namespace
7168/// definition.
John McCall48871652010-08-21 09:40:31 +00007169Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007170 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007171 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007172 SourceLocation IdentLoc,
7173 IdentifierInfo *II,
7174 SourceLocation LBrace,
7175 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007176 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7177 // For anonymous namespace, take the location of the left brace.
7178 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007179 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007180 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007181 bool IsStd = false;
7182 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007183 Scope *DeclRegionScope = NamespcScope->getParent();
7184
Craig Topperc3ec1492014-05-26 06:22:03 +00007185 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007186 if (II) {
7187 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007188 // The identifier in an original-namespace-definition shall not
7189 // have been previously defined in the declarative region in
7190 // which the original-namespace-definition appears. The
7191 // identifier in an original-namespace-definition is the name of
7192 // the namespace. Subsequently in that declarative region, it is
7193 // treated as an original-namespace-name.
7194 //
7195 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007196 // look through using directives, just look for any ordinary names.
7197
7198 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007199 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7200 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007201 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007202 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7203 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7204 ++I) {
7205 if ((*I)->getIdentifierNamespace() & IDNS) {
7206 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007207 break;
7208 }
7209 }
7210
Douglas Gregore57e7522012-01-07 09:11:48 +00007211 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7212
7213 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007214 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007215 if (IsInline != PrevNS->isInline())
7216 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7217 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007218 } else if (PrevDecl) {
7219 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007220 Diag(Loc, diag::err_redefinition_different_kind)
7221 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007222 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007223 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007224 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007225 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007226 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007227 // This is the first "real" definition of the namespace "std", so update
7228 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007229 PrevNS = getStdNamespace();
7230 IsStd = true;
7231 AddToKnown = !IsInline;
7232 } else {
7233 // We've seen this namespace for the first time.
7234 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007235 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007236 } else {
John McCall4fa53422009-10-01 00:25:31 +00007237 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007238
7239 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007240 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007241 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007242 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007243 } else {
7244 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007245 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007246 }
7247
Richard Smith45bb8852012-10-04 22:13:39 +00007248 if (PrevNS && IsInline != PrevNS->isInline())
7249 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7250 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007251 }
7252
7253 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7254 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007255 if (IsInvalid)
7256 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007257
7258 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007259
Douglas Gregore57e7522012-01-07 09:11:48 +00007260 // FIXME: Should we be merging attributes?
7261 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007262 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007263
7264 if (IsStd)
7265 StdNamespace = Namespc;
7266 if (AddToKnown)
7267 KnownNamespaces[Namespc] = false;
7268
7269 if (II) {
7270 PushOnScopeChains(Namespc, DeclRegionScope);
7271 } else {
7272 // Link the anonymous namespace into its parent.
7273 DeclContext *Parent = CurContext->getRedeclContext();
7274 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7275 TU->setAnonymousNamespace(Namespc);
7276 } else {
7277 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007278 }
John McCall4fa53422009-10-01 00:25:31 +00007279
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007280 CurContext->addDecl(Namespc);
7281
John McCall4fa53422009-10-01 00:25:31 +00007282 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7283 // behaves as if it were replaced by
7284 // namespace unique { /* empty body */ }
7285 // using namespace unique;
7286 // namespace unique { namespace-body }
7287 // where all occurrences of 'unique' in a translation unit are
7288 // replaced by the same identifier and this identifier differs
7289 // from all other identifiers in the entire program.
7290
7291 // We just create the namespace with an empty name and then add an
7292 // implicit using declaration, just like the standard suggests.
7293 //
7294 // CodeGen enforces the "universally unique" aspect by giving all
7295 // declarations semantically contained within an anonymous
7296 // namespace internal linkage.
7297
Douglas Gregore57e7522012-01-07 09:11:48 +00007298 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007299 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007300 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007301 /* 'using' */ LBrace,
7302 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007303 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007304 /* identifier */ SourceLocation(),
7305 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007306 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007307 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007308 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007309 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007310 }
7311
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007312 ActOnDocumentableDecl(Namespc);
7313
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007314 // Although we could have an invalid decl (i.e. the namespace name is a
7315 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007316 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7317 // for the namespace has the declarations that showed up in that particular
7318 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007319 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007320 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007321}
7322
Sebastian Redla6602e92009-11-23 15:34:23 +00007323/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7324/// is a namespace alias, returns the namespace it points to.
7325static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7326 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7327 return AD->getNamespace();
7328 return dyn_cast_or_null<NamespaceDecl>(D);
7329}
7330
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007331/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7332/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007333void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007334 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7335 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007336 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007337 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007338 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007339 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007340}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007341
John McCall28a0cf72010-08-25 07:42:41 +00007342CXXRecordDecl *Sema::getStdBadAlloc() const {
7343 return cast_or_null<CXXRecordDecl>(
7344 StdBadAlloc.get(Context.getExternalSource()));
7345}
7346
7347NamespaceDecl *Sema::getStdNamespace() const {
7348 return cast_or_null<NamespaceDecl>(
7349 StdNamespace.get(Context.getExternalSource()));
7350}
7351
Douglas Gregorcdf87022010-06-29 17:53:46 +00007352/// \brief Retrieve the special "std" namespace, which may require us to
7353/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007354NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007355 if (!StdNamespace) {
7356 // The "std" namespace has not yet been defined, so build one implicitly.
7357 StdNamespace = NamespaceDecl::Create(Context,
7358 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007359 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007360 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007361 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007362 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007363 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007364 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007365
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007366 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007367}
7368
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007369bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007370 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007371 "Looking for std::initializer_list outside of C++.");
7372
7373 // We're looking for implicit instantiations of
7374 // template <typename E> class std::initializer_list.
7375
7376 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7377 return false;
7378
Craig Topperc3ec1492014-05-26 06:22:03 +00007379 ClassTemplateDecl *Template = nullptr;
7380 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007381
Sebastian Redl43144e72012-01-17 22:49:58 +00007382 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007383
Sebastian Redl43144e72012-01-17 22:49:58 +00007384 ClassTemplateSpecializationDecl *Specialization =
7385 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7386 if (!Specialization)
7387 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007388
Sebastian Redl43144e72012-01-17 22:49:58 +00007389 Template = Specialization->getSpecializedTemplate();
7390 Arguments = Specialization->getTemplateArgs().data();
7391 } else if (const TemplateSpecializationType *TST =
7392 Ty->getAs<TemplateSpecializationType>()) {
7393 Template = dyn_cast_or_null<ClassTemplateDecl>(
7394 TST->getTemplateName().getAsTemplateDecl());
7395 Arguments = TST->getArgs();
7396 }
7397 if (!Template)
7398 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007399
7400 if (!StdInitializerList) {
7401 // Haven't recognized std::initializer_list yet, maybe this is it.
7402 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7403 if (TemplateClass->getIdentifier() !=
7404 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007405 !getStdNamespace()->InEnclosingNamespaceSetOf(
7406 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007407 return false;
7408 // This is a template called std::initializer_list, but is it the right
7409 // template?
7410 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007411 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007412 return false;
7413 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7414 return false;
7415
7416 // It's the right template.
7417 StdInitializerList = Template;
7418 }
7419
Richard Smith7d7dee72015-02-24 03:30:14 +00007420 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007421 return false;
7422
7423 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007424 if (Element)
7425 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007426 return true;
7427}
7428
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007429static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7430 NamespaceDecl *Std = S.getStdNamespace();
7431 if (!Std) {
7432 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007433 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007434 }
7435
7436 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7437 Loc, Sema::LookupOrdinaryName);
7438 if (!S.LookupQualifiedName(Result, Std)) {
7439 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007440 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007441 }
7442 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7443 if (!Template) {
7444 Result.suppressDiagnostics();
7445 // We found something weird. Complain about the first thing we found.
7446 NamedDecl *Found = *Result.begin();
7447 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007448 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007449 }
7450
7451 // We found some template called std::initializer_list. Now verify that it's
7452 // correct.
7453 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007454 if (Params->getMinRequiredArguments() != 1 ||
7455 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007456 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007457 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007458 }
7459
7460 return Template;
7461}
7462
7463QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7464 if (!StdInitializerList) {
7465 StdInitializerList = LookupStdInitializerList(*this, Loc);
7466 if (!StdInitializerList)
7467 return QualType();
7468 }
7469
7470 TemplateArgumentListInfo Args(Loc, Loc);
7471 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7472 Context.getTrivialTypeSourceInfo(Element,
7473 Loc)));
7474 return Context.getCanonicalType(
7475 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7476}
7477
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007478bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7479 // C++ [dcl.init.list]p2:
7480 // A constructor is an initializer-list constructor if its first parameter
7481 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7482 // std::initializer_list<E> for some type E, and either there are no other
7483 // parameters or else all other parameters have default arguments.
7484 if (Ctor->getNumParams() < 1 ||
7485 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7486 return false;
7487
7488 QualType ArgType = Ctor->getParamDecl(0)->getType();
7489 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7490 ArgType = RT->getPointeeType().getUnqualifiedType();
7491
Craig Topperc3ec1492014-05-26 06:22:03 +00007492 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007493}
7494
Douglas Gregora172e082011-03-26 22:25:30 +00007495/// \brief Determine whether a using statement is in a context where it will be
7496/// apply in all contexts.
7497static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7498 switch (CurContext->getDeclKind()) {
7499 case Decl::TranslationUnit:
7500 return true;
7501 case Decl::LinkageSpec:
7502 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7503 default:
7504 return false;
7505 }
7506}
7507
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007508namespace {
7509
7510// Callback to only accept typo corrections that are namespaces.
7511class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007512public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007513 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007514 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007515 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007516 return false;
7517 }
7518};
7519
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007520}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007521
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007522static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7523 CXXScopeSpec &SS,
7524 SourceLocation IdentLoc,
7525 IdentifierInfo *Ident) {
7526 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007527 if (TypoCorrection Corrected =
7528 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7529 llvm::make_unique<NamespaceValidatorCCC>(),
7530 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007531 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007532 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7533 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007534 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007535 S.diagnoseTypo(Corrected,
7536 S.PDiag(diag::err_using_directive_member_suggest)
7537 << Ident << DC << DroppedSpecifier << SS.getRange(),
7538 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007539 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007540 S.diagnoseTypo(Corrected,
7541 S.PDiag(diag::err_using_directive_suggest) << Ident,
7542 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007543 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007544 R.addDecl(Corrected.getCorrectionDecl());
7545 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007546 }
7547 return false;
7548}
7549
John McCall48871652010-08-21 09:40:31 +00007550Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007551 SourceLocation UsingLoc,
7552 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007553 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007554 SourceLocation IdentLoc,
7555 IdentifierInfo *NamespcName,
7556 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007557 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7558 assert(NamespcName && "Invalid NamespcName.");
7559 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007560
7561 // This can only happen along a recovery path.
7562 while (S->getFlags() & Scope::TemplateParamScope)
7563 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007564 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007565
Craig Topperc3ec1492014-05-26 06:22:03 +00007566 UsingDirectiveDecl *UDir = nullptr;
7567 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007568 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007569 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007570
Douglas Gregor34074322009-01-14 22:20:51 +00007571 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007572 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7573 LookupParsedName(R, S, &SS);
7574 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007575 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007576
Douglas Gregorcdf87022010-06-29 17:53:46 +00007577 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007578 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007579 // Allow "using namespace std;" or "using namespace ::std;" even if
7580 // "std" hasn't been defined yet, for GCC compatibility.
7581 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7582 NamespcName->isStr("std")) {
7583 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007584 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007585 R.resolveKind();
7586 }
7587 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007588 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007589 }
7590
John McCall9f3059a2009-10-09 21:13:30 +00007591 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007592 NamedDecl *Named = R.getFoundDecl();
7593 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7594 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007595
Nico Riecke50e59a2014-11-24 17:29:52 +00007596 // The use of a nested name specifier may trigger deprecation warnings.
7597 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007598
Douglas Gregor889ceb72009-02-03 19:21:40 +00007599 // C++ [namespace.udir]p1:
7600 // A using-directive specifies that the names in the nominated
7601 // namespace can be used in the scope in which the
7602 // using-directive appears after the using-directive. During
7603 // unqualified name lookup (3.4.1), the names appear as if they
7604 // were declared in the nearest enclosing namespace which
7605 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007606 // namespace. [Note: in this context, "contains" means "contains
7607 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007608
7609 // Find enclosing context containing both using-directive and
7610 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007611 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007612 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7613 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7614 CommonAncestor = CommonAncestor->getParent();
7615
Sebastian Redla6602e92009-11-23 15:34:23 +00007616 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007617 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007618 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007619
Douglas Gregora172e082011-03-26 22:25:30 +00007620 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007621 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007622 Diag(IdentLoc, diag::warn_using_directive_in_header);
7623 }
7624
Douglas Gregor889ceb72009-02-03 19:21:40 +00007625 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007626 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007627 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007628 }
7629
Richard Smith54ecd982013-02-20 19:22:51 +00007630 if (UDir)
7631 ProcessDeclAttributeList(S, UDir, AttrList);
7632
John McCall48871652010-08-21 09:40:31 +00007633 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007634}
7635
7636void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007637 // If the scope has an associated entity and the using directive is at
7638 // namespace or translation unit scope, add the UsingDirectiveDecl into
7639 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007640 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007641 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007642 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007643 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007644 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007645 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007646 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007647}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007648
Douglas Gregorfec52632009-06-20 00:51:54 +00007649
John McCall48871652010-08-21 09:40:31 +00007650Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007651 AccessSpecifier AS,
7652 bool HasUsingKeyword,
7653 SourceLocation UsingLoc,
7654 CXXScopeSpec &SS,
7655 UnqualifiedId &Name,
7656 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007657 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007658 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007659 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007660
Douglas Gregor220f4272009-11-04 16:30:06 +00007661 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007662 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007663 case UnqualifiedId::IK_Identifier:
7664 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007665 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007666 case UnqualifiedId::IK_ConversionFunctionId:
7667 break;
7668
7669 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007670 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007671 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007672 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007673 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007674 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007675 diag::err_using_decl_constructor)
7676 << SS.getRange();
7677
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007678 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007679
Craig Topperc3ec1492014-05-26 06:22:03 +00007680 return nullptr;
7681
Douglas Gregor220f4272009-11-04 16:30:06 +00007682 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007683 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007684 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007685 return nullptr;
7686
Douglas Gregor220f4272009-11-04 16:30:06 +00007687 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007688 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007689 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007690 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007691 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007692
7693 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7694 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007695 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007696 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007697
Richard Smithc2bc61b2013-03-18 21:12:30 +00007698 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007699 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007700 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007701 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7702 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007703 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007704 }
7705
Douglas Gregorc4356532010-12-16 00:46:58 +00007706 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7707 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007708 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007709
John McCall3f746822009-11-17 05:59:44 +00007710 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007711 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007712 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007713 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007714 if (UD)
7715 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007716
John McCall48871652010-08-21 09:40:31 +00007717 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007718}
7719
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007720/// \brief Determine whether a using declaration considers the given
7721/// declarations as "equivalent", e.g., if they are redeclarations of
7722/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007723static bool
7724IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7725 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007726 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007727
Richard Smithdda56e42011-04-15 14:24:37 +00007728 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007729 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007730 return Context.hasSameType(TD1->getUnderlyingType(),
7731 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007732
7733 return false;
7734}
7735
7736
John McCall84d87672009-12-10 09:41:52 +00007737/// Determines whether to create a using shadow decl for a particular
7738/// decl, given the set of decls existing prior to this using lookup.
7739bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007740 const LookupResult &Previous,
7741 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007742 // Diagnose finding a decl which is not from a base class of the
7743 // current class. We do this now because there are cases where this
7744 // function will silently decide not to build a shadow decl, which
7745 // will pre-empt further diagnostics.
7746 //
7747 // We don't need to do this in C++0x because we do the check once on
7748 // the qualifier.
7749 //
7750 // FIXME: diagnose the following if we care enough:
7751 // struct A { int foo; };
7752 // struct B : A { using A::foo; };
7753 // template <class T> struct C : A {};
7754 // template <class T> struct D : C<T> { using B::foo; } // <---
7755 // This is invalid (during instantiation) in C++03 because B::foo
7756 // resolves to the using decl in B, which is not a base class of D<T>.
7757 // We can't diagnose it immediately because C<T> is an unknown
7758 // specialization. The UsingShadowDecl in D<T> then points directly
7759 // to A::foo, which will look well-formed when we instantiate.
7760 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007761 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007762 DeclContext *OrigDC = Orig->getDeclContext();
7763
7764 // Handle enums and anonymous structs.
7765 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7766 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7767 while (OrigRec->isAnonymousStructOrUnion())
7768 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7769
7770 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7771 if (OrigDC == CurContext) {
7772 Diag(Using->getLocation(),
7773 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007774 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007775 Diag(Orig->getLocation(), diag::note_using_decl_target);
7776 return true;
7777 }
7778
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007779 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007780 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007781 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007782 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007783 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007784 Diag(Orig->getLocation(), diag::note_using_decl_target);
7785 return true;
7786 }
7787 }
7788
7789 if (Previous.empty()) return false;
7790
7791 NamedDecl *Target = Orig;
7792 if (isa<UsingShadowDecl>(Target))
7793 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7794
John McCalla17e83e2009-12-11 02:33:26 +00007795 // If the target happens to be one of the previous declarations, we
7796 // don't have a conflict.
7797 //
7798 // FIXME: but we might be increasing its access, in which case we
7799 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007800 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007801 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007802 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7803 I != E; ++I) {
7804 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007805 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7806 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7807 PrevShadow = Shadow;
7808 FoundEquivalentDecl = true;
7809 }
John McCalla17e83e2009-12-11 02:33:26 +00007810
7811 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7812 }
7813
Richard Smithfd8634a2013-10-23 02:17:46 +00007814 if (FoundEquivalentDecl)
7815 return false;
7816
Alp Tokera2794f92014-01-22 07:29:52 +00007817 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007818 NamedDecl *OldDecl = nullptr;
7819 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7820 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007821 case Ovl_Overload:
7822 return false;
7823
7824 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007825 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007826 break;
Richard Smith18819302014-02-06 01:31:33 +00007827
John McCall84d87672009-12-10 09:41:52 +00007828 // We found a decl with the exact signature.
7829 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007830 // If we're in a record, we want to hide the target, so we
7831 // return true (without a diagnostic) to tell the caller not to
7832 // build a shadow decl.
7833 if (CurContext->isRecord())
7834 return true;
7835
7836 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007837 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007838 break;
7839 }
7840
7841 Diag(Target->getLocation(), diag::note_using_decl_target);
7842 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7843 return true;
7844 }
7845
7846 // Target is not a function.
7847
John McCall84d87672009-12-10 09:41:52 +00007848 if (isa<TagDecl>(Target)) {
7849 // No conflict between a tag and a non-tag.
7850 if (!Tag) return false;
7851
John McCalle29c5cd2009-12-10 19:51:03 +00007852 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007853 Diag(Target->getLocation(), diag::note_using_decl_target);
7854 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7855 return true;
7856 }
7857
7858 // No conflict between a tag and a non-tag.
7859 if (!NonTag) return false;
7860
John McCalle29c5cd2009-12-10 19:51:03 +00007861 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007862 Diag(Target->getLocation(), diag::note_using_decl_target);
7863 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7864 return true;
7865}
7866
John McCall3f746822009-11-17 05:59:44 +00007867/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007868UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007869 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007870 NamedDecl *Orig,
7871 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007872
7873 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007874 NamedDecl *Target = Orig;
7875 if (isa<UsingShadowDecl>(Target)) {
7876 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7877 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007878 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007879
John McCall3f746822009-11-17 05:59:44 +00007880 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007881 = UsingShadowDecl::Create(Context, CurContext,
7882 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007883 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007884
Douglas Gregor457104e2010-09-29 04:25:11 +00007885 Shadow->setAccess(UD->getAccess());
7886 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7887 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007888
7889 Shadow->setPreviousDecl(PrevDecl);
7890
John McCall3f746822009-11-17 05:59:44 +00007891 if (S)
John McCall3969e302009-12-08 07:46:18 +00007892 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007893 else
John McCall3969e302009-12-08 07:46:18 +00007894 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007895
John McCall3969e302009-12-08 07:46:18 +00007896
John McCall84d87672009-12-10 09:41:52 +00007897 return Shadow;
7898}
John McCall3969e302009-12-08 07:46:18 +00007899
John McCall84d87672009-12-10 09:41:52 +00007900/// Hides a using shadow declaration. This is required by the current
7901/// using-decl implementation when a resolvable using declaration in a
7902/// class is followed by a declaration which would hide or override
7903/// one or more of the using decl's targets; for example:
7904///
7905/// struct Base { void foo(int); };
7906/// struct Derived : Base {
7907/// using Base::foo;
7908/// void foo(int);
7909/// };
7910///
7911/// The governing language is C++03 [namespace.udecl]p12:
7912///
7913/// When a using-declaration brings names from a base class into a
7914/// derived class scope, member functions in the derived class
7915/// override and/or hide member functions with the same name and
7916/// parameter types in a base class (rather than conflicting).
7917///
7918/// There are two ways to implement this:
7919/// (1) optimistically create shadow decls when they're not hidden
7920/// by existing declarations, or
7921/// (2) don't create any shadow decls (or at least don't make them
7922/// visible) until we've fully parsed/instantiated the class.
7923/// The problem with (1) is that we might have to retroactively remove
7924/// a shadow decl, which requires several O(n) operations because the
7925/// decl structures are (very reasonably) not designed for removal.
7926/// (2) avoids this but is very fiddly and phase-dependent.
7927void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007928 if (Shadow->getDeclName().getNameKind() ==
7929 DeclarationName::CXXConversionFunctionName)
7930 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7931
John McCall84d87672009-12-10 09:41:52 +00007932 // Remove it from the DeclContext...
7933 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007934
John McCall84d87672009-12-10 09:41:52 +00007935 // ...and the scope, if applicable...
7936 if (S) {
John McCall48871652010-08-21 09:40:31 +00007937 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007938 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007939 }
7940
John McCall84d87672009-12-10 09:41:52 +00007941 // ...and the using decl.
7942 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7943
7944 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007945 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007946}
7947
Richard Smith09d5b3a2014-05-01 00:35:04 +00007948/// Find the base specifier for a base class with the given type.
7949static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7950 QualType DesiredBase,
7951 bool &AnyDependentBases) {
7952 // Check whether the named type is a direct base class.
7953 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7954 for (auto &Base : Derived->bases()) {
7955 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7956 if (CanonicalDesiredBase == BaseType)
7957 return &Base;
7958 if (BaseType->isDependentType())
7959 AnyDependentBases = true;
7960 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007961 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007962}
7963
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007964namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007965class UsingValidatorCCC : public CorrectionCandidateCallback {
7966public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007967 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007968 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007969 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007970 IsInstantiation(IsInstantiation), OldNNS(NNS),
7971 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007972
Craig Toppera798a9d2014-03-02 09:32:10 +00007973 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007974 NamedDecl *ND = Candidate.getCorrectionDecl();
7975
7976 // Keywords are not valid here.
7977 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007978 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007979
7980 // Completely unqualified names are invalid for a 'using' declaration.
7981 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7982 return false;
7983
Richard Smith09d5b3a2014-05-01 00:35:04 +00007984 if (RequireMemberOf) {
7985 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7986 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7987 // No-one ever wants a using-declaration to name an injected-class-name
7988 // of a base class, unless they're declaring an inheriting constructor.
7989 ASTContext &Ctx = ND->getASTContext();
7990 if (!Ctx.getLangOpts().CPlusPlus11)
7991 return false;
7992 QualType FoundType = Ctx.getRecordType(FoundRecord);
7993
7994 // Check that the injected-class-name is named as a member of its own
7995 // type; we don't want to suggest 'using Derived::Base;', since that
7996 // means something else.
7997 NestedNameSpecifier *Specifier =
7998 Candidate.WillReplaceSpecifier()
7999 ? Candidate.getCorrectionSpecifier()
8000 : OldNNS;
8001 if (!Specifier->getAsType() ||
8002 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8003 return false;
8004
8005 // Check that this inheriting constructor declaration actually names a
8006 // direct base class of the current class.
8007 bool AnyDependentBases = false;
8008 if (!findDirectBaseWithType(RequireMemberOf,
8009 Ctx.getRecordType(FoundRecord),
8010 AnyDependentBases) &&
8011 !AnyDependentBases)
8012 return false;
8013 } else {
8014 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8015 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8016 return false;
8017
8018 // FIXME: Check that the base class member is accessible?
8019 }
8020 }
8021
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008022 if (isa<TypeDecl>(ND))
8023 return HasTypenameKeyword || !IsInstantiation;
8024
8025 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008026 }
8027
8028private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008029 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008030 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008031 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00008032 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008033};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008034} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008035
John McCalle61f2ba2009-11-18 02:36:19 +00008036/// Builds a using declaration.
8037///
8038/// \param IsInstantiation - Whether this call arises from an
8039/// instantiation of an unresolved using declaration. We treat
8040/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008041NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8042 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008043 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008044 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008045 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008046 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008047 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008048 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008049 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008050 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008051 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008052
Anders Carlssonf038fc22009-08-28 05:49:21 +00008053 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008054
Anders Carlsson59140b32009-08-28 03:16:11 +00008055 if (SS.isEmpty()) {
8056 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008057 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008058 }
Mike Stump11289f42009-09-09 15:08:12 +00008059
John McCall84d87672009-12-10 09:41:52 +00008060 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008061 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008062 ForRedeclaration);
8063 Previous.setHideTags(false);
8064 if (S) {
8065 LookupName(Previous, S);
8066
8067 // It is really dumb that we have to do this.
8068 LookupResult::Filter F = Previous.makeFilter();
8069 while (F.hasNext()) {
8070 NamedDecl *D = F.next();
8071 if (!isDeclInScope(D, CurContext, S))
8072 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008073 // If we found a local extern declaration that's not ordinarily visible,
8074 // and this declaration is being added to a non-block scope, ignore it.
8075 // We're only checking for scope conflicts here, not also for violations
8076 // of the linkage rules.
8077 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8078 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8079 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008080 }
8081 F.done();
8082 } else {
8083 assert(IsInstantiation && "no scope in non-instantiation");
8084 assert(CurContext->isRecord() && "scope not record in instantiation");
8085 LookupQualifiedName(Previous, CurContext);
8086 }
8087
John McCall84d87672009-12-10 09:41:52 +00008088 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008089 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8090 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008091 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008092
8093 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008094 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008095 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008096
John McCall84c16cf2009-11-12 03:15:40 +00008097 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008098 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008099 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008100 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008101 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008102 // FIXME: not all declaration name kinds are legal here
8103 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8104 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008105 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008106 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008107 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008108 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8109 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008110 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008111 D->setAccess(AS);
8112 CurContext->addDecl(D);
8113 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008114 }
John McCallb96ec562009-12-04 22:46:56 +00008115
Richard Smith09d5b3a2014-05-01 00:35:04 +00008116 auto Build = [&](bool Invalid) {
8117 UsingDecl *UD =
8118 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8119 HasTypenameKeyword);
8120 UD->setAccess(AS);
8121 CurContext->addDecl(UD);
8122 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008123 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008124 };
8125 auto BuildInvalid = [&]{ return Build(true); };
8126 auto BuildValid = [&]{ return Build(false); };
8127
8128 if (RequireCompleteDeclContext(SS, LookupContext))
8129 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008130
Richard Smith78163e22015-04-01 19:31:06 +00008131 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008132 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008133
John McCall3969e302009-12-08 07:46:18 +00008134 // Unlike most lookups, we don't always want to hide tag
8135 // declarations: tag names are visible through the using declaration
8136 // even if hidden by ordinary names, *except* in a dependent context
8137 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008138 if (!IsInstantiation)
8139 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008140
John McCall5dadb652012-04-07 03:04:20 +00008141 // For the purposes of this lookup, we have a base object type
8142 // equal to that of the current context.
8143 if (CurContext->isRecord()) {
8144 R.setBaseObjectType(
8145 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8146 }
8147
John McCall27b18f82009-11-17 02:14:36 +00008148 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008149
Richard Smith78163e22015-04-01 19:31:06 +00008150 // Try to correct typos if possible. If constructor name lookup finds no
8151 // results, that means the named class has no explicit constructors, and we
8152 // suppressed declaring implicit ones (probably because it's dependent or
8153 // invalid).
8154 if (R.empty() &&
8155 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008156 if (TypoCorrection Corrected = CorrectTypo(
8157 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8158 llvm::make_unique<UsingValidatorCCC>(
8159 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8160 dyn_cast<CXXRecordDecl>(CurContext)),
8161 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008162 // We reject any correction for which ND would be NULL.
8163 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008164
Richard Smithf9b15102013-08-17 00:46:16 +00008165 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008166 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008167 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8168 << NameInfo.getName() << LookupContext << 0
8169 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008170
8171 // If we corrected to an inheriting constructor, handle it as one.
8172 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8173 if (RD && RD->isInjectedClassName()) {
8174 // Fix up the information we'll use to build the using declaration.
8175 if (Corrected.WillReplaceSpecifier()) {
8176 NestedNameSpecifierLocBuilder Builder;
8177 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8178 QualifierLoc.getSourceRange());
8179 QualifierLoc = Builder.getWithLocInContext(Context);
8180 }
8181
8182 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8183 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008184 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00008185 for (auto *Ctor : LookupConstructors(RD))
8186 R.addDecl(Ctor);
8187 } else {
8188 // FIXME: Pick up all the declarations if we found an overloaded function.
8189 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008190 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008191 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008192 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008193 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008194 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008195 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008196 }
8197
Richard Smith09d5b3a2014-05-01 00:35:04 +00008198 if (R.isAmbiguous())
8199 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008200
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008201 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008202 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008203 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008204 Diag(IdentLoc, diag::err_using_typename_non_type);
8205 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8206 Diag((*I)->getUnderlyingDecl()->getLocation(),
8207 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008208 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008209 }
8210 } else {
8211 // If we asked for a non-typename and we got a type, error out,
8212 // but only if this is an instantiation of an unresolved using
8213 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008214 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008215 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8216 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008217 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008218 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008219 }
8220
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008221 // C++0x N2914 [namespace.udecl]p6:
8222 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008223 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008224 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8225 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008226 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008227 }
Mike Stump11289f42009-09-09 15:08:12 +00008228
Richard Smith09d5b3a2014-05-01 00:35:04 +00008229 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00008230
8231 // The normal rules do not apply to inheriting constructor declarations.
8232 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8233 // Suppress access diagnostics; the access check is instead performed at the
8234 // point of use for an inheriting constructor.
8235 R.suppressDiagnostics();
8236 CheckInheritingConstructorUsingDecl(UD);
8237 return UD;
8238 }
8239
8240 // Otherwise, look up the target name.
8241
John McCall84d87672009-12-10 09:41:52 +00008242 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008243 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008244 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8245 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008246 }
John McCall3f746822009-11-17 05:59:44 +00008247
8248 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008249}
8250
Sebastian Redl08905022011-02-05 19:23:19 +00008251/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008252bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008253 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008254
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008255 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008256 assert(SourceType &&
8257 "Using decl naming constructor doesn't have type in scope spec.");
8258 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8259
8260 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008261 bool AnyDependentBases = false;
8262 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8263 AnyDependentBases);
8264 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008265 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008266 diag::err_using_decl_constructor_not_in_direct_base)
8267 << UD->getNameInfo().getSourceRange()
8268 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008269 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008270 return true;
8271 }
8272
Richard Smith09d5b3a2014-05-01 00:35:04 +00008273 if (Base)
8274 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008275
8276 return false;
8277}
8278
John McCall84d87672009-12-10 09:41:52 +00008279/// Checks that the given using declaration is not an invalid
8280/// redeclaration. Note that this is checking only for the using decl
8281/// itself, not for any ill-formedness among the UsingShadowDecls.
8282bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008283 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008284 const CXXScopeSpec &SS,
8285 SourceLocation NameLoc,
8286 const LookupResult &Prev) {
8287 // C++03 [namespace.udecl]p8:
8288 // C++0x [namespace.udecl]p10:
8289 // A using-declaration is a declaration and can therefore be used
8290 // repeatedly where (and only where) multiple declarations are
8291 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008292 //
John McCall032092f2010-11-29 18:01:58 +00008293 // That's in non-member contexts.
8294 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008295 return false;
8296
Aaron Ballman4a979672014-01-03 13:56:08 +00008297 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008298
8299 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8300 NamedDecl *D = *I;
8301
8302 bool DTypename;
8303 NestedNameSpecifier *DQual;
8304 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008305 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008306 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008307 } else if (UnresolvedUsingValueDecl *UD
8308 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8309 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008310 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008311 } else if (UnresolvedUsingTypenameDecl *UD
8312 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8313 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008314 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008315 } else continue;
8316
8317 // using decls differ if one says 'typename' and the other doesn't.
8318 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008319 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008320
8321 // using decls differ if they name different scopes (but note that
8322 // template instantiation can cause this check to trigger when it
8323 // didn't before instantiation).
8324 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8325 Context.getCanonicalNestedNameSpecifier(DQual))
8326 continue;
8327
8328 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008329 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008330 return true;
8331 }
8332
8333 return false;
8334}
8335
John McCall3969e302009-12-08 07:46:18 +00008336
John McCallb96ec562009-12-04 22:46:56 +00008337/// Checks that the given nested-name qualifier used in a using decl
8338/// in the current context is appropriately related to the current
8339/// scope. If an error is found, diagnoses it and returns true.
8340bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8341 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008342 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008343 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008344 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008345
John McCall3969e302009-12-08 07:46:18 +00008346 if (!CurContext->isRecord()) {
8347 // C++03 [namespace.udecl]p3:
8348 // C++0x [namespace.udecl]p8:
8349 // A using-declaration for a class member shall be a member-declaration.
8350
8351 // If we weren't able to compute a valid scope, it must be a
8352 // dependent class scope.
8353 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008354 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008355 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008356 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008357
John McCall3969e302009-12-08 07:46:18 +00008358 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8359 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008360
8361 // If we have a complete, non-dependent source type, try to suggest a
8362 // way to get the same effect.
8363 if (!RD)
8364 return true;
8365
8366 // Find what this using-declaration was referring to.
8367 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8368 R.setHideTags(false);
8369 R.suppressDiagnostics();
8370 LookupQualifiedName(R, RD);
8371
8372 if (R.getAsSingle<TypeDecl>()) {
8373 if (getLangOpts().CPlusPlus11) {
8374 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8375 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8376 << 0 // alias declaration
8377 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8378 NameInfo.getName().getAsString() +
8379 " = ");
8380 } else {
8381 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8382 SourceLocation InsertLoc =
8383 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8384 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8385 << 1 // typedef declaration
8386 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8387 << FixItHint::CreateInsertion(
8388 InsertLoc, " " + NameInfo.getName().getAsString());
8389 }
8390 } else if (R.getAsSingle<VarDecl>()) {
8391 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8392 // repeating the type of the static data member here.
8393 FixItHint FixIt;
8394 if (getLangOpts().CPlusPlus11) {
8395 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8396 FixIt = FixItHint::CreateReplacement(
8397 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8398 }
8399
8400 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8401 << 2 // reference declaration
8402 << FixIt;
8403 }
John McCall3969e302009-12-08 07:46:18 +00008404 return true;
8405 }
8406
8407 // Otherwise, everything is known to be fine.
8408 return false;
8409 }
8410
8411 // The current scope is a record.
8412
8413 // If the named context is dependent, we can't decide much.
8414 if (!NamedContext) {
8415 // FIXME: in C++0x, we can diagnose if we can prove that the
8416 // nested-name-specifier does not refer to a base class, which is
8417 // still possible in some cases.
8418
8419 // Otherwise we have to conservatively report that things might be
8420 // okay.
8421 return false;
8422 }
8423
8424 if (!NamedContext->isRecord()) {
8425 // Ideally this would point at the last name in the specifier,
8426 // but we don't have that level of source info.
8427 Diag(SS.getRange().getBegin(),
8428 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008429 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008430 return true;
8431 }
8432
Douglas Gregor7c842292010-12-21 07:41:49 +00008433 if (!NamedContext->isDependentContext() &&
8434 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8435 return true;
8436
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008437 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008438 // C++0x [namespace.udecl]p3:
8439 // In a using-declaration used as a member-declaration, the
8440 // nested-name-specifier shall name a base class of the class
8441 // being defined.
8442
8443 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8444 cast<CXXRecordDecl>(NamedContext))) {
8445 if (CurContext == NamedContext) {
8446 Diag(NameLoc,
8447 diag::err_using_decl_nested_name_specifier_is_current_class)
8448 << SS.getRange();
8449 return true;
8450 }
8451
8452 Diag(SS.getRange().getBegin(),
8453 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008454 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008455 << cast<CXXRecordDecl>(CurContext)
8456 << SS.getRange();
8457 return true;
8458 }
8459
8460 return false;
8461 }
8462
8463 // C++03 [namespace.udecl]p4:
8464 // A using-declaration used as a member-declaration shall refer
8465 // to a member of a base class of the class being defined [etc.].
8466
8467 // Salient point: SS doesn't have to name a base class as long as
8468 // lookup only finds members from base classes. Therefore we can
8469 // diagnose here only if we can prove that that can't happen,
8470 // i.e. if the class hierarchies provably don't intersect.
8471
8472 // TODO: it would be nice if "definitely valid" results were cached
8473 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8474 // need to be repeated.
8475
8476 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008477 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008478
8479 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8480 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8481 Data->Bases.insert(Base);
8482 return true;
8483 }
8484
8485 bool hasDependentBases(const CXXRecordDecl *Class) {
8486 return !Class->forallBases(collect, this);
8487 }
8488
8489 /// Returns true if the base is dependent or is one of the
8490 /// accumulated base classes.
8491 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8492 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8493 return !Data->Bases.count(Base);
8494 }
8495
8496 bool mightShareBases(const CXXRecordDecl *Class) {
8497 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8498 }
8499 };
8500
8501 UserData Data;
8502
8503 // Returns false if we find a dependent base.
8504 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8505 return false;
8506
8507 // Returns false if the class has a dependent base or if it or one
8508 // of its bases is present in the base set of the current context.
8509 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8510 return false;
8511
8512 Diag(SS.getRange().getBegin(),
8513 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008514 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008515 << cast<CXXRecordDecl>(CurContext)
8516 << SS.getRange();
8517
8518 return true;
John McCallb96ec562009-12-04 22:46:56 +00008519}
8520
Richard Smithdda56e42011-04-15 14:24:37 +00008521Decl *Sema::ActOnAliasDeclaration(Scope *S,
8522 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008523 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008524 SourceLocation UsingLoc,
8525 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008526 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00008527 TypeResult Type,
8528 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008529 // Skip up to the relevant declaration scope.
8530 while (S->getFlags() & Scope::TemplateParamScope)
8531 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008532 assert((S->getFlags() & Scope::DeclScope) &&
8533 "got alias-declaration outside of declaration scope");
8534
8535 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008536 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008537
8538 bool Invalid = false;
8539 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008540 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008541 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008542
8543 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008544 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008545
8546 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008547 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008548 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008549 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8550 TInfo->getTypeLoc().getBeginLoc());
8551 }
Richard Smithdda56e42011-04-15 14:24:37 +00008552
8553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8554 LookupName(Previous, S);
8555
8556 // Warn about shadowing the name of a template parameter.
8557 if (Previous.isSingleResult() &&
8558 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008559 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008560 Previous.clear();
8561 }
8562
8563 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8564 "name in alias declaration must be an identifier");
8565 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8566 Name.StartLocation,
8567 Name.Identifier, TInfo);
8568
8569 NewTD->setAccess(AS);
8570
8571 if (Invalid)
8572 NewTD->setInvalidDecl();
8573
Richard Smith54ecd982013-02-20 19:22:51 +00008574 ProcessDeclAttributeList(S, NewTD, AttrList);
8575
Richard Smith3f1b5d02011-05-05 21:57:07 +00008576 CheckTypedefForVariablyModifiedType(S, NewTD);
8577 Invalid |= NewTD->isInvalidDecl();
8578
Richard Smithdda56e42011-04-15 14:24:37 +00008579 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008580
8581 NamedDecl *NewND;
8582 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008583 TypeAliasTemplateDecl *OldDecl = nullptr;
8584 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008585
8586 if (TemplateParamLists.size() != 1) {
8587 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008588 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8589 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008590 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008591 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008592
8593 // Only consider previous declarations in the same scope.
8594 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8595 /*ExplicitInstantiationOrSpecialization*/false);
8596 if (!Previous.empty()) {
8597 Redeclaration = true;
8598
8599 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8600 if (!OldDecl && !Invalid) {
8601 Diag(UsingLoc, diag::err_redefinition_different_kind)
8602 << Name.Identifier;
8603
8604 NamedDecl *OldD = Previous.getRepresentativeDecl();
8605 if (OldD->getLocation().isValid())
8606 Diag(OldD->getLocation(), diag::note_previous_definition);
8607
8608 Invalid = true;
8609 }
8610
8611 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8612 if (TemplateParameterListsAreEqual(TemplateParams,
8613 OldDecl->getTemplateParameters(),
8614 /*Complain=*/true,
8615 TPL_TemplateMatch))
8616 OldTemplateParams = OldDecl->getTemplateParameters();
8617 else
8618 Invalid = true;
8619
8620 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8621 if (!Invalid &&
8622 !Context.hasSameType(OldTD->getUnderlyingType(),
8623 NewTD->getUnderlyingType())) {
8624 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8625 // but we can't reasonably accept it.
8626 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8627 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8628 if (OldTD->getLocation().isValid())
8629 Diag(OldTD->getLocation(), diag::note_previous_definition);
8630 Invalid = true;
8631 }
8632 }
8633 }
8634
8635 // Merge any previous default template arguments into our parameters,
8636 // and check the parameter list.
8637 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8638 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008639 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008640
8641 TypeAliasTemplateDecl *NewDecl =
8642 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8643 Name.Identifier, TemplateParams,
8644 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008645 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008646
8647 NewDecl->setAccess(AS);
8648
8649 if (Invalid)
8650 NewDecl->setInvalidDecl();
8651 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008652 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008653
8654 NewND = NewDecl;
8655 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00008656 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8657 setTagNameForLinkagePurposes(TD, NewTD);
8658 handleTagNumbering(TD, S);
8659 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00008660 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8661 NewND = NewTD;
8662 }
Richard Smithdda56e42011-04-15 14:24:37 +00008663
8664 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008665 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008666
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008667 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008668 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008669}
8670
Richard Smithf4634362014-09-03 23:11:22 +00008671Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8672 SourceLocation AliasLoc,
8673 IdentifierInfo *Alias, CXXScopeSpec &SS,
8674 SourceLocation IdentLoc,
8675 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008676
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008677 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008678 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8679 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008680
John McCall27b18f82009-11-17 02:14:36 +00008681 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008682 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008683
John McCall9f3059a2009-10-09 21:13:30 +00008684 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008685 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008686 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008687 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008688 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008689 }
Richard Smithf4634362014-09-03 23:11:22 +00008690 assert(!R.isAmbiguous() && !R.empty());
8691
8692 // Check if we have a previous declaration with the same name.
8693 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8694 ForRedeclaration);
8695 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8696 PrevDecl = nullptr;
8697
Aaron Ballman43f40102014-11-14 22:34:56 +00008698 NamedDecl *ND = R.getFoundDecl();
8699
Richard Smithf4634362014-09-03 23:11:22 +00008700 if (PrevDecl) {
8701 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8702 // We already have an alias with the same name that points to the same
8703 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008704 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008705 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8706 << Alias;
8707 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8708 << AD->getNamespace();
8709 return nullptr;
8710 }
8711 } else {
8712 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8713 ? diag::err_redefinition
8714 : diag::err_redefinition_different_kind;
8715 Diag(AliasLoc, DiagID) << Alias;
8716 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8717 return nullptr;
8718 }
8719 }
Mike Stump11289f42009-09-09 15:08:12 +00008720
Nico Riecke50e59a2014-11-24 17:29:52 +00008721 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008722 DiagnoseUseOfDecl(ND, IdentLoc);
8723
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008724 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008725 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008726 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008727 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008728 if (PrevDecl)
8729 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008730
John McCalld8d0d432010-02-16 06:53:13 +00008731 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008732 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008733}
8734
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008735Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008736Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8737 CXXMethodDecl *MD) {
8738 CXXRecordDecl *ClassDecl = MD->getParent();
8739
Douglas Gregor6d880b12010-07-01 22:31:05 +00008740 // C++ [except.spec]p14:
8741 // An implicitly declared special member function (Clause 12) shall have an
8742 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008743 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008744 if (ClassDecl->isInvalidDecl())
8745 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008746
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008747 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008748 for (const auto &B : ClassDecl->bases()) {
8749 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008750 continue;
8751
Aaron Ballman574705e2014-03-13 15:41:46 +00008752 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008753 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008754 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8755 // If this is a deleted function, add it anyway. This might be conformant
8756 // with the standard. This might not. I'm not sure. It might not matter.
8757 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008758 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008759 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008760 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008761
8762 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008763 for (const auto &B : ClassDecl->vbases()) {
8764 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008765 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008766 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8767 // If this is a deleted function, add it anyway. This might be conformant
8768 // with the standard. This might not. I'm not sure. It might not matter.
8769 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008770 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008771 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008772 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008773
8774 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008775 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008776 if (F->hasInClassInitializer()) {
8777 if (Expr *E = F->getInClassInitializer())
8778 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008779 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008780 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008781 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8782 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8783 // If this is a deleted function, add it anyway. This might be conformant
8784 // with the standard. This might not. I'm not sure. It might not matter.
8785 // In particular, the problem is that this function never gets called. It
8786 // might just be ill-formed because this function attempts to refer to
8787 // a deleted function here.
8788 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008789 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008790 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008791 }
John McCalldb40c7f2010-12-14 08:05:40 +00008792
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008793 return ExceptSpec;
8794}
8795
Richard Smithc2bc61b2013-03-18 21:12:30 +00008796Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008797Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8798 CXXRecordDecl *ClassDecl = CD->getParent();
8799
8800 // C++ [except.spec]p14:
8801 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008802 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008803 if (ClassDecl->isInvalidDecl())
8804 return ExceptSpec;
8805
8806 // Inherited constructor.
8807 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8808 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8809 // FIXME: Copying or moving the parameters could add extra exceptions to the
8810 // set, as could the default arguments for the inherited constructor. This
8811 // will be addressed when we implement the resolution of core issue 1351.
8812 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8813
8814 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008815 for (const auto &B : ClassDecl->bases()) {
8816 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008817 continue;
8818
Aaron Ballman574705e2014-03-13 15:41:46 +00008819 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008820 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8821 if (BaseClassDecl == InheritedDecl)
8822 continue;
8823 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8824 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008825 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008826 }
8827 }
8828
8829 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008830 for (const auto &B : ClassDecl->vbases()) {
8831 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008832 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8833 if (BaseClassDecl == InheritedDecl)
8834 continue;
8835 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8836 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008837 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008838 }
8839 }
8840
8841 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008842 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008843 if (F->hasInClassInitializer()) {
8844 if (Expr *E = F->getInClassInitializer())
8845 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008846 } else if (const RecordType *RecordTy
8847 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8848 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8849 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8850 if (Constructor)
8851 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8852 }
8853 }
8854
Richard Smithc2bc61b2013-03-18 21:12:30 +00008855 return ExceptSpec;
8856}
8857
Richard Smith8bf22e52012-11-29 01:34:07 +00008858namespace {
8859/// RAII object to register a special member as being currently declared.
8860struct DeclaringSpecialMember {
8861 Sema &S;
8862 Sema::SpecialMemberDecl D;
8863 bool WasAlreadyBeingDeclared;
8864
8865 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8866 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008867 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008868 if (WasAlreadyBeingDeclared)
8869 // This almost never happens, but if it does, ensure that our cache
8870 // doesn't contain a stale result.
8871 S.SpecialMemberCache.clear();
8872
8873 // FIXME: Register a note to be produced if we encounter an error while
8874 // declaring the special member.
8875 }
8876 ~DeclaringSpecialMember() {
8877 if (!WasAlreadyBeingDeclared)
8878 S.SpecialMembersBeingDeclared.erase(D);
8879 }
8880
8881 /// \brief Are we already trying to declare this special member?
8882 bool isAlreadyBeingDeclared() const {
8883 return WasAlreadyBeingDeclared;
8884 }
8885};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008886}
Richard Smith8bf22e52012-11-29 01:34:07 +00008887
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008888CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8889 CXXRecordDecl *ClassDecl) {
8890 // C++ [class.ctor]p5:
8891 // A default constructor for a class X is a constructor of class X
8892 // that can be called without an argument. If there is no
8893 // user-declared constructor for class X, a default constructor is
8894 // implicitly declared. An implicitly-declared default constructor
8895 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008896 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008897 "Should not build implicit default constructor!");
8898
Richard Smith8bf22e52012-11-29 01:34:07 +00008899 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8900 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008901 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008902
Richard Smithb5800092012-06-10 05:43:50 +00008903 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8904 CXXDefaultConstructor,
8905 false);
8906
Douglas Gregor6d880b12010-07-01 22:31:05 +00008907 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008908 CanQualType ClassType
8909 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008910 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008911 DeclarationName Name
8912 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008913 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008914 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008915 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8916 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8917 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008918 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008919 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008920
8921 if (getLangOpts().CUDA) {
8922 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8923 DefaultCon,
8924 /* ConstRHS */ false,
8925 /* Diagnose */ false);
8926 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008927
8928 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008929 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008930 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008931
Richard Smith6b02d462012-12-08 08:32:28 +00008932 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8933 // constructors is easy to compute.
8934 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8935
8936 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008937 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008938
Douglas Gregor9672f922010-07-03 00:47:00 +00008939 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008940 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008941
Douglas Gregor0be31a22010-07-02 17:43:08 +00008942 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008943 PushOnScopeChains(DefaultCon, S, false);
8944 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008945
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008946 return DefaultCon;
8947}
8948
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008949void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8950 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008951 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008952 !Constructor->doesThisDeclarationHaveABody() &&
8953 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008954 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008955
Anders Carlsson423f5d82010-04-23 16:04:08 +00008956 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008957 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008958
Eli Friedmaneaf34142012-10-18 20:14:08 +00008959 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008960 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008961 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008962 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008963 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008964 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008965 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008966 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008967 }
Douglas Gregor73193272010-09-20 16:48:21 +00008968
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008969 // The exception specification is needed because we are defining the
8970 // function.
8971 ResolveExceptionSpec(CurrentLocation,
8972 Constructor->getType()->castAs<FunctionProtoType>());
8973
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008974 SourceLocation Loc = Constructor->getLocEnd().isValid()
8975 ? Constructor->getLocEnd()
8976 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008977 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008978
Eli Friedman276dd182013-09-05 00:02:25 +00008979 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008980 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008981
8982 if (ASTMutationListener *L = getASTMutationListener()) {
8983 L->CompletedImplicitDefinition(Constructor);
8984 }
Richard Trieuef64e942013-10-25 00:56:00 +00008985
8986 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008987}
8988
Richard Smith938f40b2011-06-11 17:19:42 +00008989void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008990 // Perform any delayed checks on exception specifications.
8991 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008992}
8993
Richard Smith185be182013-04-10 05:48:59 +00008994namespace {
8995/// Information on inheriting constructors to declare.
8996class InheritingConstructorInfo {
8997public:
8998 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8999 : SemaRef(SemaRef), Derived(Derived) {
9000 // Mark the constructors that we already have in the derived class.
9001 //
9002 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9003 // unless there is a user-declared constructor with the same signature in
9004 // the class where the using-declaration appears.
9005 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9006 }
9007
9008 void inheritAll(CXXRecordDecl *RD) {
9009 visitAll(RD, &InheritingConstructorInfo::inherit);
9010 }
9011
9012private:
9013 /// Information about an inheriting constructor.
9014 struct InheritingConstructor {
9015 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00009016 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00009017
9018 /// If \c true, a constructor with this signature is already declared
9019 /// in the derived class.
9020 bool DeclaredInDerived;
9021
9022 /// The constructor which is inherited.
9023 const CXXConstructorDecl *BaseCtor;
9024
9025 /// The derived constructor we declared.
9026 CXXConstructorDecl *DerivedCtor;
9027 };
9028
9029 /// Inheriting constructors with a given canonical type. There can be at
9030 /// most one such non-template constructor, and any number of templated
9031 /// constructors.
9032 struct InheritingConstructorsForType {
9033 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009034 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9035 Templates;
Richard Smith185be182013-04-10 05:48:59 +00009036
9037 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9038 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9039 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9040 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9041 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9042 false, S.TPL_TemplateMatch))
9043 return Templates[I].second;
9044 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9045 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009046 }
Richard Smith185be182013-04-10 05:48:59 +00009047
9048 return NonTemplate;
9049 }
9050 };
9051
9052 /// Get or create the inheriting constructor record for a constructor.
9053 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9054 QualType CtorType) {
9055 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9056 .getEntry(SemaRef, Ctor);
9057 }
9058
9059 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9060
9061 /// Process all constructors for a class.
9062 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009063 for (const auto *Ctor : RD->ctors())
9064 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009065 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9066 I(RD->decls_begin()), E(RD->decls_end());
9067 I != E; ++I) {
9068 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9069 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9070 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009071 }
9072 }
Richard Smith185be182013-04-10 05:48:59 +00009073
9074 /// Note that a constructor (or constructor template) was declared in Derived.
9075 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9076 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9077 }
9078
9079 /// Inherit a single constructor.
9080 void inherit(const CXXConstructorDecl *Ctor) {
9081 const FunctionProtoType *CtorType =
9082 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009083 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009084 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9085
9086 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9087
9088 // Core issue (no number yet): the ellipsis is always discarded.
9089 if (EPI.Variadic) {
9090 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9091 SemaRef.Diag(Ctor->getLocation(),
9092 diag::note_using_decl_constructor_ellipsis);
9093 EPI.Variadic = false;
9094 }
9095
9096 // Declare a constructor for each number of parameters.
9097 //
9098 // C++11 [class.inhctor]p1:
9099 // The candidate set of inherited constructors from the class X named in
9100 // the using-declaration consists of [... modulo defects ...] for each
9101 // constructor or constructor template of X, the set of constructors or
9102 // constructor templates that results from omitting any ellipsis parameter
9103 // specification and successively omitting parameters with a default
9104 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009105 unsigned MinParams = minParamsToInherit(Ctor);
9106 unsigned Params = Ctor->getNumParams();
9107 if (Params >= MinParams) {
9108 do
9109 declareCtor(UsingLoc, Ctor,
9110 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009111 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009112 while (Params > MinParams &&
9113 Ctor->getParamDecl(--Params)->hasDefaultArg());
9114 }
Richard Smith185be182013-04-10 05:48:59 +00009115 }
9116
9117 /// Find the using-declaration which specified that we should inherit the
9118 /// constructors of \p Base.
9119 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9120 // No fancy lookup required; just look for the base constructor name
9121 // directly within the derived class.
9122 ASTContext &Context = SemaRef.Context;
9123 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9124 Context.getCanonicalType(Context.getRecordType(Base)));
Richard Smithcf4bdde2015-02-21 02:45:19 +00009125 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith185be182013-04-10 05:48:59 +00009126 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9127 }
9128
9129 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9130 // C++11 [class.inhctor]p3:
9131 // [F]or each constructor template in the candidate set of inherited
9132 // constructors, a constructor template is implicitly declared
9133 if (Ctor->getDescribedFunctionTemplate())
9134 return 0;
9135
9136 // For each non-template constructor in the candidate set of inherited
9137 // constructors other than a constructor having no parameters or a
9138 // copy/move constructor having a single parameter, a constructor is
9139 // implicitly declared [...]
9140 if (Ctor->getNumParams() == 0)
9141 return 1;
9142 if (Ctor->isCopyOrMoveConstructor())
9143 return 2;
9144
9145 // Per discussion on core reflector, never inherit a constructor which
9146 // would become a default, copy, or move constructor of Derived either.
9147 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9148 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9149 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9150 }
9151
9152 /// Declare a single inheriting constructor, inheriting the specified
9153 /// constructor, with the given type.
9154 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9155 QualType DerivedType) {
9156 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9157
9158 // C++11 [class.inhctor]p3:
9159 // ... a constructor is implicitly declared with the same constructor
9160 // characteristics unless there is a user-declared constructor with
9161 // the same signature in the class where the using-declaration appears
9162 if (Entry.DeclaredInDerived)
9163 return;
9164
9165 // C++11 [class.inhctor]p7:
9166 // If two using-declarations declare inheriting constructors with the
9167 // same signature, the program is ill-formed
9168 if (Entry.DerivedCtor) {
9169 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9170 // Only diagnose this once per constructor.
9171 if (Entry.DerivedCtor->isInvalidDecl())
9172 return;
9173 Entry.DerivedCtor->setInvalidDecl();
9174
9175 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9176 SemaRef.Diag(BaseCtor->getLocation(),
9177 diag::note_using_decl_constructor_conflict_current_ctor);
9178 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9179 diag::note_using_decl_constructor_conflict_previous_ctor);
9180 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9181 diag::note_using_decl_constructor_conflict_previous_using);
9182 } else {
9183 // Core issue (no number): if the same inheriting constructor is
9184 // produced by multiple base class constructors from the same base
9185 // class, the inheriting constructor is defined as deleted.
9186 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9187 }
9188
9189 return;
9190 }
9191
9192 ASTContext &Context = SemaRef.Context;
9193 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9194 Context.getCanonicalType(Context.getRecordType(Derived)));
9195 DeclarationNameInfo NameInfo(Name, UsingLoc);
9196
Craig Topperc3ec1492014-05-26 06:22:03 +00009197 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009198 if (const FunctionTemplateDecl *FTD =
9199 BaseCtor->getDescribedFunctionTemplate()) {
9200 TemplateParams = FTD->getTemplateParameters();
9201 // We're reusing template parameters from a different DeclContext. This
9202 // is questionable at best, but works out because the template depth in
9203 // both places is guaranteed to be 0.
9204 // FIXME: Rebuild the template parameters in the new context, and
9205 // transform the function type to refer to them.
9206 }
9207
9208 // Build type source info pointing at the using-declaration. This is
9209 // required by template instantiation.
9210 TypeSourceInfo *TInfo =
9211 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9212 FunctionProtoTypeLoc ProtoLoc =
9213 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9214
9215 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9216 Context, Derived, UsingLoc, NameInfo, DerivedType,
9217 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9218 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9219
9220 // Build an unevaluated exception specification for this constructor.
9221 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9222 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009223 EPI.ExceptionSpec.Type = EST_Unevaluated;
9224 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009225 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009226 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009227
9228 // Build the parameter declarations.
9229 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009230 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009231 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009232 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009233 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009234 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9235 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009236 PD->setScopeInfo(0, I);
9237 PD->setImplicit();
9238 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009239 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009240 }
9241
9242 // Set up the new constructor.
9243 DerivedCtor->setAccess(BaseCtor->getAccess());
9244 DerivedCtor->setParams(ParamDecls);
9245 DerivedCtor->setInheritedConstructor(BaseCtor);
9246 if (BaseCtor->isDeleted())
9247 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9248
9249 // If this is a constructor template, build the template declaration.
9250 if (TemplateParams) {
9251 FunctionTemplateDecl *DerivedTemplate =
9252 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9253 TemplateParams, DerivedCtor);
9254 DerivedTemplate->setAccess(BaseCtor->getAccess());
9255 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9256 Derived->addDecl(DerivedTemplate);
9257 } else {
9258 Derived->addDecl(DerivedCtor);
9259 }
9260
9261 Entry.BaseCtor = BaseCtor;
9262 Entry.DerivedCtor = DerivedCtor;
9263 }
9264
9265 Sema &SemaRef;
9266 CXXRecordDecl *Derived;
9267 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9268 MapType Map;
9269};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009270}
Richard Smith185be182013-04-10 05:48:59 +00009271
9272void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9273 // Defer declaring the inheriting constructors until the class is
9274 // instantiated.
9275 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009276 return;
9277
Richard Smith185be182013-04-10 05:48:59 +00009278 // Find base classes from which we might inherit constructors.
9279 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009280 for (const auto &BaseIt : ClassDecl->bases())
9281 if (BaseIt.getInheritConstructors())
9282 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009283
Richard Smith185be182013-04-10 05:48:59 +00009284 // Go no further if we're not inheriting any constructors.
9285 if (InheritedBases.empty())
9286 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009287
Richard Smith185be182013-04-10 05:48:59 +00009288 // Declare the inherited constructors.
9289 InheritingConstructorInfo ICI(*this, ClassDecl);
9290 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9291 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009292}
9293
Richard Smithc2bc61b2013-03-18 21:12:30 +00009294void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9295 CXXConstructorDecl *Constructor) {
9296 CXXRecordDecl *ClassDecl = Constructor->getParent();
9297 assert(Constructor->getInheritedConstructor() &&
9298 !Constructor->doesThisDeclarationHaveABody() &&
9299 !Constructor->isDeleted());
9300
9301 SynthesizedFunctionScope Scope(*this, Constructor);
9302 DiagnosticErrorTrap Trap(Diags);
9303 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9304 Trap.hasErrorOccurred()) {
9305 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9306 << Context.getTagDeclType(ClassDecl);
9307 Constructor->setInvalidDecl();
9308 return;
9309 }
9310
9311 SourceLocation Loc = Constructor->getLocation();
9312 Constructor->setBody(new (Context) CompoundStmt(Loc));
9313
Eli Friedman276dd182013-09-05 00:02:25 +00009314 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009315 MarkVTableUsed(CurrentLocation, ClassDecl);
9316
9317 if (ASTMutationListener *L = getASTMutationListener()) {
9318 L->CompletedImplicitDefinition(Constructor);
9319 }
9320}
9321
9322
Alexis Huntf91729462011-05-12 22:46:25 +00009323Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009324Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9325 CXXRecordDecl *ClassDecl = MD->getParent();
9326
Douglas Gregorf1203042010-07-01 19:09:28 +00009327 // C++ [except.spec]p14:
9328 // An implicitly declared special member function (Clause 12) shall have
9329 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009330 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009331 if (ClassDecl->isInvalidDecl())
9332 return ExceptSpec;
9333
Douglas Gregorf1203042010-07-01 19:09:28 +00009334 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009335 for (const auto &B : ClassDecl->bases()) {
9336 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009337 continue;
9338
Aaron Ballman574705e2014-03-13 15:41:46 +00009339 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9340 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009341 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009342 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009343
Douglas Gregorf1203042010-07-01 19:09:28 +00009344 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009345 for (const auto &B : ClassDecl->vbases()) {
9346 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9347 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009348 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009349 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009350
Douglas Gregorf1203042010-07-01 19:09:28 +00009351 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009352 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009353 if (const RecordType *RecordTy
9354 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009355 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009356 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009357 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009358
Alexis Huntf91729462011-05-12 22:46:25 +00009359 return ExceptSpec;
9360}
9361
9362CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9363 // C++ [class.dtor]p2:
9364 // If a class has no user-declared destructor, a destructor is
9365 // declared implicitly. An implicitly-declared destructor is an
9366 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009367 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009368
Richard Smith8bf22e52012-11-29 01:34:07 +00009369 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9370 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009371 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009372
Douglas Gregor7454c562010-07-02 20:37:36 +00009373 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009374 CanQualType ClassType
9375 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009376 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009377 DeclarationName Name
9378 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009379 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009380 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009381 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009382 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009383 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009384 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009385 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009386
9387 if (getLangOpts().CUDA) {
9388 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9389 Destructor,
9390 /* ConstRHS */ false,
9391 /* Diagnose */ false);
9392 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009393
9394 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009395 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009396 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009397
Richard Smith6b02d462012-12-08 08:32:28 +00009398 AddOverriddenMethods(ClassDecl, Destructor);
9399
9400 // We don't need to use SpecialMemberIsTrivial here; triviality for
9401 // destructors is easy to compute.
9402 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9403
9404 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009405 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009406
Douglas Gregor7454c562010-07-02 20:37:36 +00009407 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009408 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009409
Douglas Gregor7454c562010-07-02 20:37:36 +00009410 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009411 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009412 PushOnScopeChains(Destructor, S, false);
9413 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009414
Douglas Gregorf1203042010-07-01 19:09:28 +00009415 return Destructor;
9416}
9417
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009418void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009419 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009420 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009421 !Destructor->doesThisDeclarationHaveABody() &&
9422 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009423 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009424 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009425 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009426
Douglas Gregor54818f02010-05-12 16:39:35 +00009427 if (Destructor->isInvalidDecl())
9428 return;
9429
Eli Friedmaneaf34142012-10-18 20:14:08 +00009430 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009431
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009432 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009433 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9434 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009435
Douglas Gregor54818f02010-05-12 16:39:35 +00009436 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009437 Diag(CurrentLocation, diag::note_member_synthesized_at)
9438 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9439
9440 Destructor->setInvalidDecl();
9441 return;
9442 }
9443
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009444 // The exception specification is needed because we are defining the
9445 // function.
9446 ResolveExceptionSpec(CurrentLocation,
9447 Destructor->getType()->castAs<FunctionProtoType>());
9448
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009449 SourceLocation Loc = Destructor->getLocEnd().isValid()
9450 ? Destructor->getLocEnd()
9451 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009452 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009453 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009454 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009455
9456 if (ASTMutationListener *L = getASTMutationListener()) {
9457 L->CompletedImplicitDefinition(Destructor);
9458 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009459}
9460
Richard Smith84973e52012-04-21 18:42:51 +00009461/// \brief Perform any semantic analysis which needs to be delayed until all
9462/// pending class member declarations have been parsed.
9463void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009464 // If the context is an invalid C++ class, just suppress these checks.
9465 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9466 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009467 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009468 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009469 return;
9470 }
9471 }
Richard Smith84973e52012-04-21 18:42:51 +00009472}
9473
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009474static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9475 // Don't do anything for template patterns.
9476 if (Class->getDescribedClassTemplate())
9477 return;
9478
9479 for (Decl *Member : Class->decls()) {
9480 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9481 if (!CD) {
9482 // Recurse on nested classes.
9483 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9484 getDefaultArgExprsForConstructors(S, NestedRD);
9485 continue;
9486 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9487 continue;
9488 }
9489
9490 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9491 // Skip any default arguments that we've already instantiated.
9492 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9493 continue;
9494
9495 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9496 CD->getParamDecl(I)).get();
David Majnemer9321f922015-06-11 02:38:06 +00009497 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009498 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9499 }
9500 }
9501}
9502
Reid Kleckner93f661a2015-03-17 21:51:43 +00009503void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009504 auto *RD = dyn_cast<CXXRecordDecl>(D);
9505
9506 // Default constructors that are annotated with __declspec(dllexport) which
9507 // have default arguments or don't use the standard calling convention are
9508 // wrapped with a thunk called the default constructor closure.
9509 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9510 getDefaultArgExprsForConstructors(*this, RD);
9511}
9512
Richard Smithd3b5c9082012-07-27 04:22:15 +00009513void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9514 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009515 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009516 "adjusting dtor exception specs was introduced in c++11");
9517
Sebastian Redl623ea822011-05-19 05:13:44 +00009518 // C++11 [class.dtor]p3:
9519 // A declaration of a destructor that does not have an exception-
9520 // specification is implicitly considered to have the same exception-
9521 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009522 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009523 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009524 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009525 return;
9526
Chandler Carruth9a797572011-09-20 04:55:26 +00009527 // Replace the destructor's type, building off the existing one. Fortunately,
9528 // the only thing of interest in the destructor type is its extended info.
9529 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009530 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009531 EPI.ExceptionSpec.Type = EST_Unevaluated;
9532 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009533 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009534
Sebastian Redl623ea822011-05-19 05:13:44 +00009535 // FIXME: If the destructor has a body that could throw, and the newly created
9536 // spec doesn't allow exceptions, we should emit a warning, because this
9537 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009538 // However, we don't have a body or an exception specification yet, so it
9539 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009540}
9541
Pavel Labath58934982013-08-30 08:52:28 +00009542namespace {
9543/// \brief An abstract base class for all helper classes used in building the
9544// copy/move operators. These classes serve as factory functions and help us
9545// avoid using the same Expr* in the AST twice.
9546class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +00009547 ExprBuilder(const ExprBuilder&) = delete;
9548 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +00009549
9550protected:
9551 static Expr *assertNotNull(Expr *E) {
9552 assert(E && "Expression construction must not fail.");
9553 return E;
9554 }
9555
9556public:
9557 ExprBuilder() {}
9558 virtual ~ExprBuilder() {}
9559
9560 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9561};
9562
9563class RefBuilder: public ExprBuilder {
9564 VarDecl *Var;
9565 QualType VarType;
9566
9567public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009568 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009569 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009570 }
9571
9572 RefBuilder(VarDecl *Var, QualType VarType)
9573 : Var(Var), VarType(VarType) {}
9574};
9575
9576class ThisBuilder: public ExprBuilder {
9577public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009578 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009579 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009580 }
9581};
9582
9583class CastBuilder: public ExprBuilder {
9584 const ExprBuilder &Builder;
9585 QualType Type;
9586 ExprValueKind Kind;
9587 const CXXCastPath &Path;
9588
9589public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009590 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009591 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9592 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009593 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009594 }
9595
9596 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9597 const CXXCastPath &Path)
9598 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9599};
9600
9601class DerefBuilder: public ExprBuilder {
9602 const ExprBuilder &Builder;
9603
9604public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009605 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009606 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009607 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009608 }
9609
9610 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9611};
9612
9613class MemberBuilder: public ExprBuilder {
9614 const ExprBuilder &Builder;
9615 QualType Type;
9616 CXXScopeSpec SS;
9617 bool IsArrow;
9618 LookupResult &MemberLookup;
9619
9620public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009621 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009622 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009623 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009624 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009625 }
9626
9627 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9628 LookupResult &MemberLookup)
9629 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9630 MemberLookup(MemberLookup) {}
9631};
9632
9633class MoveCastBuilder: public ExprBuilder {
9634 const ExprBuilder &Builder;
9635
9636public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009637 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009638 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9639 }
9640
9641 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9642};
9643
9644class LvalueConvBuilder: public ExprBuilder {
9645 const ExprBuilder &Builder;
9646
9647public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009648 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009649 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009650 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009651 }
9652
9653 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9654};
9655
9656class SubscriptBuilder: public ExprBuilder {
9657 const ExprBuilder &Base;
9658 const ExprBuilder &Index;
9659
9660public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009661 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009662 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009663 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009664 }
9665
9666 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9667 : Base(Base), Index(Index) {}
9668};
9669
9670} // end anonymous namespace
9671
Richard Smith41ae3282012-11-14 00:50:40 +00009672/// When generating a defaulted copy or move assignment operator, if a field
9673/// should be copied with __builtin_memcpy rather than via explicit assignments,
9674/// do so. This optimization only applies for arrays of scalars, and for arrays
9675/// of class type where the selected copy/move-assignment operator is trivial.
9676static StmtResult
9677buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009678 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009679 // Compute the size of the memory buffer to be copied.
9680 QualType SizeType = S.Context.getSizeType();
9681 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9682 S.Context.getTypeSizeInChars(T).getQuantity());
9683
9684 // Take the address of the field references for "from" and "to". We
9685 // directly construct UnaryOperators here because semantic analysis
9686 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009687 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009688 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9689 S.Context.getPointerType(From->getType()),
9690 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009691 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009692 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9693 S.Context.getPointerType(To->getType()),
9694 VK_RValue, OK_Ordinary, Loc);
9695
9696 const Type *E = T->getBaseElementTypeUnsafe();
9697 bool NeedsCollectableMemCpy =
9698 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9699
9700 // Create a reference to the __builtin_objc_memmove_collectable function
9701 StringRef MemCpyName = NeedsCollectableMemCpy ?
9702 "__builtin_objc_memmove_collectable" :
9703 "__builtin_memcpy";
9704 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9705 Sema::LookupOrdinaryName);
9706 S.LookupName(R, S.TUScope, true);
9707
9708 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9709 if (!MemCpy)
9710 // Something went horribly wrong earlier, and we will have complained
9711 // about it.
9712 return StmtError();
9713
9714 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009715 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009716 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9717
9718 Expr *CallArgs[] = {
9719 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9720 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009721 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009722 Loc, CallArgs, Loc);
9723
9724 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009725 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009726}
9727
Sebastian Redl22653ba2011-08-30 19:58:05 +00009728/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009729/// \c To.
9730///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009731/// This routine is used to copy/move the members of a class with an
9732/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009733/// copied are arrays, this routine builds for loops to copy them.
9734///
9735/// \param S The Sema object used for type-checking.
9736///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009737/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009738///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009739/// \param T The type of the expressions being copied/moved. Both expressions
9740/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009741///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009742/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009743///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009744/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009745///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009746/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009747/// Otherwise, it's a non-static member subobject.
9748///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009749/// \param Copying Whether we're copying or moving.
9750///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009751/// \param Depth Internal parameter recording the depth of the recursion.
9752///
Richard Smith41ae3282012-11-14 00:50:40 +00009753/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9754/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009755static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009756buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009757 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009758 bool CopyingBaseSubobject, bool Copying,
9759 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009760 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009761 // Each subobject is assigned in the manner appropriate to its type:
9762 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009763 // - if the subobject is of class type, as if by a call to operator= with
9764 // the subobject as the object expression and the corresponding
9765 // subobject of x as a single function argument (as if by explicit
9766 // qualification; that is, ignoring any possible virtual overriding
9767 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009768 //
9769 // C++03 [class.copy]p13:
9770 // - if the subobject is of class type, the copy assignment operator for
9771 // the class is used (as if by explicit qualification; that is,
9772 // ignoring any possible virtual overriding functions in more derived
9773 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009774 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9775 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009776
Douglas Gregorb139cd52010-05-01 20:49:11 +00009777 // Look for operator=.
9778 DeclarationName Name
9779 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9780 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9781 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009782
Richard Smith52c0b582012-11-13 00:54:12 +00009783 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9784 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009785 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009786 LookupResult::Filter F = OpLookup.makeFilter();
9787 while (F.hasNext()) {
9788 NamedDecl *D = F.next();
9789 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9790 if (Method->isCopyAssignmentOperator() ||
9791 (!Copying && Method->isMoveAssignmentOperator()))
9792 continue;
9793
9794 F.erase();
9795 }
9796 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009797 }
Richard Smith52c0b582012-11-13 00:54:12 +00009798
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009799 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009800 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009801 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009802 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009803 // ambiguities), we need to cast "this" to that subobject type; to
9804 // ensure that we don't go through the virtual call mechanism, we need
9805 // to qualify the operator= name with the base class (see below). However,
9806 // this means that if the base class has a protected copy assignment
9807 // operator, the protected member access check will fail. So, we
9808 // rewrite "protected" access to "public" access in this case, since we
9809 // know by construction that we're calling from a derived class.
9810 if (CopyingBaseSubobject) {
9811 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9812 L != LEnd; ++L) {
9813 if (L.getAccess() == AS_protected)
9814 L.setAccess(AS_public);
9815 }
9816 }
Richard Smith52c0b582012-11-13 00:54:12 +00009817
Douglas Gregorb139cd52010-05-01 20:49:11 +00009818 // Create the nested-name-specifier that will be used to qualify the
9819 // reference to operator=; this is required to suppress the virtual
9820 // call mechanism.
9821 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009822 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009823 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009824 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009825 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009826 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009827
Douglas Gregorb139cd52010-05-01 20:49:11 +00009828 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009829 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009830 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9831 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009832 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009833 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009834 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009835 /*SuppressQualifierCheck=*/true);
9836 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009837 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009838
Douglas Gregorb139cd52010-05-01 20:49:11 +00009839 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009840
Pavel Labath58934982013-08-30 08:52:28 +00009841 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009842 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009843 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009844 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009845 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009846 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009847
Richard Smith41ae3282012-11-14 00:50:40 +00009848 // If we built a call to a trivial 'operator=' while copying an array,
9849 // bail out. We'll replace the whole shebang with a memcpy.
9850 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9851 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009852 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009853
Richard Smith52c0b582012-11-13 00:54:12 +00009854 // Convert to an expression-statement, and clean up any produced
9855 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009856 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009857 }
John McCallab8c2732010-03-16 06:11:48 +00009858
Richard Smith52c0b582012-11-13 00:54:12 +00009859 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009860 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009861 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009862 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009863 ExprResult Assignment = S.CreateBuiltinBinOp(
9864 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009865 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009866 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009867 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009868 }
Richard Smith52c0b582012-11-13 00:54:12 +00009869
9870 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009871 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009872
Douglas Gregorb139cd52010-05-01 20:49:11 +00009873 // Construct a loop over the array bounds, e.g.,
9874 //
9875 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9876 //
9877 // that will copy each of the array elements.
9878 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009879
Douglas Gregorb139cd52010-05-01 20:49:11 +00009880 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009881 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009882 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009883 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009884 llvm::raw_svector_ostream OS(Str);
9885 OS << "__i" << Depth;
9886 IterationVarName = &S.Context.Idents.get(OS.str());
9887 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009888 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009889 IterationVarName, SizeType,
9890 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009891 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009892
Douglas Gregorb139cd52010-05-01 20:49:11 +00009893 // Initialize the iteration variable to zero.
9894 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009895 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009896
Pavel Labath58934982013-08-30 08:52:28 +00009897 // Creates a reference to the iteration variable.
9898 RefBuilder IterationVarRef(IterationVar, SizeType);
9899 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009900
Douglas Gregorb139cd52010-05-01 20:49:11 +00009901 // Create the DeclStmt that holds the iteration variable.
9902 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009903
Douglas Gregorb139cd52010-05-01 20:49:11 +00009904 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009905 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9906 MoveCastBuilder FromIndexMove(FromIndexCopy);
9907 const ExprBuilder *FromIndex;
9908 if (Copying)
9909 FromIndex = &FromIndexCopy;
9910 else
9911 FromIndex = &FromIndexMove;
9912
9913 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009914
9915 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009916 StmtResult Copy =
9917 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009918 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009919 Copying, Depth + 1);
9920 // Bail out if copying fails or if we determined that we should use memcpy.
9921 if (Copy.isInvalid() || !Copy.get())
9922 return Copy;
9923
9924 // Create the comparison against the array bound.
9925 llvm::APInt Upper
9926 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9927 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009928 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009929 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9930 BO_NE, S.Context.BoolTy,
9931 VK_RValue, OK_Ordinary, Loc, false);
9932
9933 // Create the pre-increment of the iteration variable.
9934 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009935 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9936 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009937
Douglas Gregorb139cd52010-05-01 20:49:11 +00009938 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009939 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009940 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009941 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009942 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009943}
9944
Richard Smith41ae3282012-11-14 00:50:40 +00009945static StmtResult
9946buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009947 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009948 bool CopyingBaseSubobject, bool Copying) {
9949 // Maybe we should use a memcpy?
9950 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9951 T.isTriviallyCopyableType(S.Context))
9952 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9953
9954 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9955 CopyingBaseSubobject,
9956 Copying, 0));
9957
9958 // If we ended up picking a trivial assignment operator for an array of a
9959 // non-trivially-copyable class type, just emit a memcpy.
9960 if (!Result.isInvalid() && !Result.get())
9961 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9962
9963 return Result;
9964}
9965
Richard Smithd3b5c9082012-07-27 04:22:15 +00009966Sema::ImplicitExceptionSpecification
9967Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9968 CXXRecordDecl *ClassDecl = MD->getParent();
9969
9970 ImplicitExceptionSpecification ExceptSpec(*this);
9971 if (ClassDecl->isInvalidDecl())
9972 return ExceptSpec;
9973
9974 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009975 assert(T->getNumParams() == 1 && "not a copy assignment op");
9976 unsigned ArgQuals =
9977 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009978
Douglas Gregor68e11362010-07-01 17:48:08 +00009979 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009980 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009981 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009982
9983 // It is unspecified whether or not an implicit copy assignment operator
9984 // attempts to deduplicate calls to assignment operators of virtual bases are
9985 // made. As such, this exception specification is effectively unspecified.
9986 // Based on a similar decision made for constness in C++0x, we're erring on
9987 // the side of assuming such calls to be made regardless of whether they
9988 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009989 for (const auto &Base : ClassDecl->bases()) {
9990 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009991 continue;
9992
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009993 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009994 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009995 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9996 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009997 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009998 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009999
Aaron Ballman445a9392014-03-13 16:15:17 +000010000 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010001 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010002 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010003 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10004 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010005 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010006 }
10007
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010008 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010009 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010010 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10011 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010012 LookupCopyingAssignment(FieldClassDecl,
10013 ArgQuals | FieldType.getCVRQualifiers(),
10014 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010015 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010016 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010017 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010018
Richard Smithd3b5c9082012-07-27 04:22:15 +000010019 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010020}
10021
10022CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10023 // Note: The following rules are largely analoguous to the copy
10024 // constructor rules. Note that virtual bases are not taken into account
10025 // for determining the argument type of the operator. Note also that
10026 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010027 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010028
Richard Smith8bf22e52012-11-29 01:34:07 +000010029 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10030 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010031 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010032
Alexis Hunt119f3652011-05-14 05:23:20 +000010033 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10034 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010035 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10036 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010037 ArgType = ArgType.withConst();
10038 ArgType = Context.getLValueReferenceType(ArgType);
10039
Richard Smith99005e62013-05-07 03:19:20 +000010040 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10041 CXXCopyAssignment,
10042 Const);
10043
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010044 // An implicitly-declared copy assignment operator is an inline public
10045 // member of its class.
10046 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010047 SourceLocation ClassLoc = ClassDecl->getLocation();
10048 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010049 CXXMethodDecl *CopyAssignment =
10050 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010051 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10052 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010053 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010054 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010055 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010056
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010057 if (getLangOpts().CUDA) {
10058 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10059 CopyAssignment,
10060 /* ConstRHS */ Const,
10061 /* Diagnose */ false);
10062 }
10063
Richard Smithd3b5c9082012-07-27 04:22:15 +000010064 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010065 FunctionProtoType::ExtProtoInfo EPI =
10066 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010067 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010068
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010069 // Add the parameter to the operator.
10070 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010071 ClassLoc, ClassLoc,
10072 /*Id=*/nullptr, ArgType,
10073 /*TInfo=*/nullptr, SC_None,
10074 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010075 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010076
Richard Smith6b02d462012-12-08 08:32:28 +000010077 AddOverriddenMethods(ClassDecl, CopyAssignment);
10078
10079 CopyAssignment->setTrivial(
10080 ClassDecl->needsOverloadResolutionForCopyAssignment()
10081 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10082 : ClassDecl->hasTrivialCopyAssignment());
10083
Richard Smith852265f2012-03-30 20:53:28 +000010084 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +000010085 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010086
Richard Smith6b02d462012-12-08 08:32:28 +000010087 // Note that we have added this copy-assignment operator.
10088 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10089
10090 if (Scope *S = getScopeForContext(ClassDecl))
10091 PushOnScopeChains(CopyAssignment, S, false);
10092 ClassDecl->addDecl(CopyAssignment);
10093
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010094 return CopyAssignment;
10095}
10096
Richard Smithd577fbb2013-06-13 03:23:42 +000010097/// Diagnose an implicit copy operation for a class which is odr-used, but
10098/// which is deprecated because the class has a user-declared copy constructor,
10099/// copy assignment operator, or destructor.
10100static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10101 SourceLocation UseLoc) {
10102 assert(CopyOp->isImplicit());
10103
10104 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010105 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010106
10107 // In Microsoft mode, assignment operations don't affect constructors and
10108 // vice versa.
10109 if (RD->hasUserDeclaredDestructor()) {
10110 UserDeclaredOperation = RD->getDestructor();
10111 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10112 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010113 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010114 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010115 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010116 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010117 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010118 break;
10119 }
10120 }
10121 assert(UserDeclaredOperation);
10122 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10123 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010124 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010125 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010126 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010127 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010128 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010129 break;
10130 }
10131 }
10132 assert(UserDeclaredOperation);
10133 }
10134
10135 if (UserDeclaredOperation) {
10136 S.Diag(UserDeclaredOperation->getLocation(),
10137 diag::warn_deprecated_copy_operation)
10138 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10139 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10140 S.Diag(UseLoc, diag::note_member_synthesized_at)
10141 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10142 : Sema::CXXCopyAssignment)
10143 << RD;
10144 }
10145}
10146
Douglas Gregorb139cd52010-05-01 20:49:11 +000010147void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10148 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010149 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010150 CopyAssignOperator->isOverloadedOperator() &&
10151 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010152 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10153 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010154 "DefineImplicitCopyAssignment called for wrong function");
10155
10156 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10157
10158 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10159 CopyAssignOperator->setInvalidDecl();
10160 return;
10161 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010162
10163 // C++11 [class.copy]p18:
10164 // The [definition of an implicitly declared copy assignment operator] is
10165 // deprecated if the class has a user-declared copy constructor or a
10166 // user-declared destructor.
10167 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10168 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10169
Eli Friedman276dd182013-09-05 00:02:25 +000010170 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010171
Eli Friedmaneaf34142012-10-18 20:14:08 +000010172 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010173 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010174
10175 // C++0x [class.copy]p30:
10176 // The implicitly-defined or explicitly-defaulted copy assignment operator
10177 // for a non-union class X performs memberwise copy assignment of its
10178 // subobjects. The direct base classes of X are assigned first, in the
10179 // order of their declaration in the base-specifier-list, and then the
10180 // immediate non-static data members of X are assigned, in the order in
10181 // which they were declared in the class definition.
10182
10183 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010184 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010185
10186 // The parameter for the "other" object, which we are copying from.
10187 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10188 Qualifiers OtherQuals = Other->getType().getQualifiers();
10189 QualType OtherRefType = Other->getType();
10190 if (const LValueReferenceType *OtherRef
10191 = OtherRefType->getAs<LValueReferenceType>()) {
10192 OtherRefType = OtherRef->getPointeeType();
10193 OtherQuals = OtherRefType.getQualifiers();
10194 }
10195
10196 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010197 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10198 ? CopyAssignOperator->getLocEnd()
10199 : CopyAssignOperator->getLocation();
10200
Pavel Labath58934982013-08-30 08:52:28 +000010201 // Builds a DeclRefExpr for the "other" object.
10202 RefBuilder OtherRef(Other, OtherRefType);
10203
10204 // Builds the "this" pointer.
10205 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010206
10207 // Assign base classes.
10208 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010209 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010210 // Form the assignment:
10211 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010212 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010213 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010214 Invalid = true;
10215 continue;
10216 }
10217
John McCallcf142162010-08-07 06:22:56 +000010218 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010219 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010220
Douglas Gregorb139cd52010-05-01 20:49:11 +000010221 // Construct the "from" expression, which is an implicit cast to the
10222 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010223 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10224 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010225
10226 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010227 DerefBuilder DerefThis(This);
10228 CastBuilder To(DerefThis,
10229 Context.getCVRQualifiedType(
10230 BaseType, CopyAssignOperator->getTypeQualifiers()),
10231 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010232
10233 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010234 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010235 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010236 /*CopyingBaseSubobject=*/true,
10237 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010238 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010239 Diag(CurrentLocation, diag::note_member_synthesized_at)
10240 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10241 CopyAssignOperator->setInvalidDecl();
10242 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010243 }
10244
10245 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010246 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010247 }
10248
Douglas Gregorb139cd52010-05-01 20:49:11 +000010249 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010250 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010251 // FIXME: We should form some kind of AST representation for the implied
10252 // memcpy in a union copy operation.
10253 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010254 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010255
10256 if (Field->isInvalidDecl()) {
10257 Invalid = true;
10258 continue;
10259 }
10260
Douglas Gregorb139cd52010-05-01 20:49:11 +000010261 // Check for members of reference type; we can't copy those.
10262 if (Field->getType()->isReferenceType()) {
10263 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10264 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10265 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010266 Diag(CurrentLocation, diag::note_member_synthesized_at)
10267 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010268 Invalid = true;
10269 continue;
10270 }
10271
10272 // Check for members of const-qualified, non-class type.
10273 QualType BaseType = Context.getBaseElementType(Field->getType());
10274 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10275 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10276 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10277 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010278 Diag(CurrentLocation, diag::note_member_synthesized_at)
10279 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010280 Invalid = true;
10281 continue;
10282 }
John McCall1b1a1db2011-06-17 00:18:42 +000010283
10284 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010285 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10286 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010287
10288 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010289 if (FieldType->isIncompleteArrayType()) {
10290 assert(ClassDecl->hasFlexibleArrayMember() &&
10291 "Incomplete array type is not valid");
10292 continue;
10293 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010294
10295 // Build references to the field in the object we're copying from and to.
10296 CXXScopeSpec SS; // Intentionally empty
10297 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10298 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010299 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010300 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010301
10302 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10303
10304 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010305
Douglas Gregorb139cd52010-05-01 20:49:11 +000010306 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010307 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010308 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010309 /*CopyingBaseSubobject=*/false,
10310 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010311 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010312 Diag(CurrentLocation, diag::note_member_synthesized_at)
10313 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10314 CopyAssignOperator->setInvalidDecl();
10315 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010316 }
10317
10318 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010319 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010320 }
10321
10322 if (!Invalid) {
10323 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010324 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010325
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010326 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010327 if (Return.isInvalid())
10328 Invalid = true;
10329 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010330 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010331
10332 if (Trap.hasErrorOccurred()) {
10333 Diag(CurrentLocation, diag::note_member_synthesized_at)
10334 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10335 Invalid = true;
10336 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010337 }
10338 }
10339
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010340 // The exception specification is needed because we are defining the
10341 // function.
10342 ResolveExceptionSpec(CurrentLocation,
10343 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10344
Douglas Gregorb139cd52010-05-01 20:49:11 +000010345 if (Invalid) {
10346 CopyAssignOperator->setInvalidDecl();
10347 return;
10348 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010349
10350 StmtResult Body;
10351 {
10352 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010353 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010354 /*isStmtExpr=*/false);
10355 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10356 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010357 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010358
10359 if (ASTMutationListener *L = getASTMutationListener()) {
10360 L->CompletedImplicitDefinition(CopyAssignOperator);
10361 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010362}
10363
Sebastian Redl22653ba2011-08-30 19:58:05 +000010364Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010365Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10366 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010367
Richard Smithd3b5c9082012-07-27 04:22:15 +000010368 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010369 if (ClassDecl->isInvalidDecl())
10370 return ExceptSpec;
10371
10372 // C++0x [except.spec]p14:
10373 // An implicitly declared special member function (Clause 12) shall have an
10374 // exception-specification. [...]
10375
10376 // It is unspecified whether or not an implicit move assignment operator
10377 // attempts to deduplicate calls to assignment operators of virtual bases are
10378 // made. As such, this exception specification is effectively unspecified.
10379 // Based on a similar decision made for constness in C++0x, we're erring on
10380 // the side of assuming such calls to be made regardless of whether they
10381 // actually happen.
10382 // Note that a move constructor is not implicitly declared when there are
10383 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010384 for (const auto &Base : ClassDecl->bases()) {
10385 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010386 continue;
10387
10388 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010389 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010390 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010391 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010392 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010393 }
10394
Aaron Ballman445a9392014-03-13 16:15:17 +000010395 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010396 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010397 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010398 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010399 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010400 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010401 }
10402
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010403 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010404 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010405 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010406 if (CXXMethodDecl *MoveAssign =
10407 LookupMovingAssignment(FieldClassDecl,
10408 FieldType.getCVRQualifiers(),
10409 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010410 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010411 }
10412 }
10413
10414 return ExceptSpec;
10415}
10416
10417CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010418 assert(ClassDecl->needsImplicitMoveAssignment());
10419
Richard Smith8bf22e52012-11-29 01:34:07 +000010420 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10421 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010422 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010423
Sebastian Redl22653ba2011-08-30 19:58:05 +000010424 // Note: The following rules are largely analoguous to the move
10425 // constructor rules.
10426
Sebastian Redl22653ba2011-08-30 19:58:05 +000010427 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10428 QualType RetType = Context.getLValueReferenceType(ArgType);
10429 ArgType = Context.getRValueReferenceType(ArgType);
10430
Richard Smith99005e62013-05-07 03:19:20 +000010431 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10432 CXXMoveAssignment,
10433 false);
10434
Sebastian Redl22653ba2011-08-30 19:58:05 +000010435 // An implicitly-declared move assignment operator is an inline public
10436 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010437 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10438 SourceLocation ClassLoc = ClassDecl->getLocation();
10439 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010440 CXXMethodDecl *MoveAssignment =
10441 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010442 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010443 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010444 MoveAssignment->setAccess(AS_public);
10445 MoveAssignment->setDefaulted();
10446 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010447
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010448 if (getLangOpts().CUDA) {
10449 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10450 MoveAssignment,
10451 /* ConstRHS */ false,
10452 /* Diagnose */ false);
10453 }
10454
Richard Smithd3b5c9082012-07-27 04:22:15 +000010455 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010456 FunctionProtoType::ExtProtoInfo EPI =
10457 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010458 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010459
Sebastian Redl22653ba2011-08-30 19:58:05 +000010460 // Add the parameter to the operator.
10461 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010462 ClassLoc, ClassLoc,
10463 /*Id=*/nullptr, ArgType,
10464 /*TInfo=*/nullptr, SC_None,
10465 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010466 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010467
Richard Smith6b02d462012-12-08 08:32:28 +000010468 AddOverriddenMethods(ClassDecl, MoveAssignment);
10469
10470 MoveAssignment->setTrivial(
10471 ClassDecl->needsOverloadResolutionForMoveAssignment()
10472 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10473 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010474
Richard Smithd951a1d2012-02-18 02:02:13 +000010475 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010476 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10477 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010478 }
10479
Richard Smith6b02d462012-12-08 08:32:28 +000010480 // Note that we have added this copy-assignment operator.
10481 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10482
Sebastian Redl22653ba2011-08-30 19:58:05 +000010483 if (Scope *S = getScopeForContext(ClassDecl))
10484 PushOnScopeChains(MoveAssignment, S, false);
10485 ClassDecl->addDecl(MoveAssignment);
10486
Sebastian Redl22653ba2011-08-30 19:58:05 +000010487 return MoveAssignment;
10488}
10489
Richard Smithb2504bd2013-11-04 04:26:14 +000010490/// Check if we're implicitly defining a move assignment operator for a class
10491/// with virtual bases. Such a move assignment might move-assign the virtual
10492/// base multiple times.
10493static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10494 SourceLocation CurrentLocation) {
10495 assert(!Class->isDependentContext() && "should not define dependent move");
10496
10497 // Only a virtual base could get implicitly move-assigned multiple times.
10498 // Only a non-trivial move assignment can observe this. We only want to
10499 // diagnose if we implicitly define an assignment operator that assigns
10500 // two base classes, both of which move-assign the same virtual base.
10501 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10502 Class->getNumBases() < 2)
10503 return;
10504
10505 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10506 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10507 VBaseMap VBases;
10508
Aaron Ballman574705e2014-03-13 15:41:46 +000010509 for (auto &BI : Class->bases()) {
10510 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010511 while (!Worklist.empty()) {
10512 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10513 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10514
10515 // If the base has no non-trivial move assignment operators,
10516 // we don't care about moves from it.
10517 if (!Base->hasNonTrivialMoveAssignment())
10518 continue;
10519
10520 // If there's nothing virtual here, skip it.
10521 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10522 continue;
10523
10524 // If we're not actually going to call a move assignment for this base,
10525 // or the selected move assignment is trivial, skip it.
10526 Sema::SpecialMemberOverloadResult *SMOR =
10527 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10528 /*ConstArg*/false, /*VolatileArg*/false,
10529 /*RValueThis*/true, /*ConstThis*/false,
10530 /*VolatileThis*/false);
10531 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10532 !SMOR->getMethod()->isMoveAssignmentOperator())
10533 continue;
10534
10535 if (BaseSpec->isVirtual()) {
10536 // We're going to move-assign this virtual base, and its move
10537 // assignment operator is not trivial. If this can happen for
10538 // multiple distinct direct bases of Class, diagnose it. (If it
10539 // only happens in one base, we'll diagnose it when synthesizing
10540 // that base class's move assignment operator.)
10541 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010542 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010543 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010544 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010545 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10546 << Class << Base;
10547 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10548 << (Base->getCanonicalDecl() ==
10549 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10550 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010551 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010552 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010553 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10554 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010555
10556 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010557 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010558 }
10559 } else {
10560 // Only walk over bases that have defaulted move assignment operators.
10561 // We assume that any user-provided move assignment operator handles
10562 // the multiple-moves-of-vbase case itself somehow.
10563 if (!SMOR->getMethod()->isDefaulted())
10564 continue;
10565
10566 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010567 for (auto &BI : Base->bases())
10568 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010569 }
10570 }
10571 }
10572}
10573
Sebastian Redl22653ba2011-08-30 19:58:05 +000010574void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10575 CXXMethodDecl *MoveAssignOperator) {
10576 assert((MoveAssignOperator->isDefaulted() &&
10577 MoveAssignOperator->isOverloadedOperator() &&
10578 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010579 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10580 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010581 "DefineImplicitMoveAssignment called for wrong function");
10582
10583 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10584
10585 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10586 MoveAssignOperator->setInvalidDecl();
10587 return;
10588 }
10589
Eli Friedman276dd182013-09-05 00:02:25 +000010590 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010591
Eli Friedmaneaf34142012-10-18 20:14:08 +000010592 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010593 DiagnosticErrorTrap Trap(Diags);
10594
10595 // C++0x [class.copy]p28:
10596 // The implicitly-defined or move assignment operator for a non-union class
10597 // X performs memberwise move assignment of its subobjects. The direct base
10598 // classes of X are assigned first, in the order of their declaration in the
10599 // base-specifier-list, and then the immediate non-static data members of X
10600 // are assigned, in the order in which they were declared in the class
10601 // definition.
10602
Richard Smithb2504bd2013-11-04 04:26:14 +000010603 // Issue a warning if our implicit move assignment operator will move
10604 // from a virtual base more than once.
10605 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010606
Sebastian Redl22653ba2011-08-30 19:58:05 +000010607 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010608 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010609
10610 // The parameter for the "other" object, which we are move from.
10611 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10612 QualType OtherRefType = Other->getType()->
10613 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010614 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010615 "Bad argument type of defaulted move assignment");
10616
10617 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010618 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10619 ? MoveAssignOperator->getLocEnd()
10620 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010621
Pavel Labath58934982013-08-30 08:52:28 +000010622 // Builds a reference to the "other" object.
10623 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010624 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010625 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010626
Pavel Labath58934982013-08-30 08:52:28 +000010627 // Builds the "this" pointer.
10628 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010629
Sebastian Redl22653ba2011-08-30 19:58:05 +000010630 // Assign base classes.
10631 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010632 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010633 // C++11 [class.copy]p28:
10634 // It is unspecified whether subobjects representing virtual base classes
10635 // are assigned more than once by the implicitly-defined copy assignment
10636 // operator.
10637 // FIXME: Do not assign to a vbase that will be assigned by some other base
10638 // class. For a move-assignment, this can result in the vbase being moved
10639 // multiple times.
10640
Sebastian Redl22653ba2011-08-30 19:58:05 +000010641 // Form the assignment:
10642 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010643 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010644 if (!BaseType->isRecordType()) {
10645 Invalid = true;
10646 continue;
10647 }
10648
10649 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010650 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010651
10652 // Construct the "from" expression, which is an implicit cast to the
10653 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010654 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010655
10656 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010657 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010658
10659 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010660 CastBuilder To(DerefThis,
10661 Context.getCVRQualifiedType(
10662 BaseType, MoveAssignOperator->getTypeQualifiers()),
10663 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010664
10665 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010666 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010667 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010668 /*CopyingBaseSubobject=*/true,
10669 /*Copying=*/false);
10670 if (Move.isInvalid()) {
10671 Diag(CurrentLocation, diag::note_member_synthesized_at)
10672 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10673 MoveAssignOperator->setInvalidDecl();
10674 return;
10675 }
10676
10677 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010678 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010679 }
10680
Sebastian Redl22653ba2011-08-30 19:58:05 +000010681 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010682 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010683 // FIXME: We should form some kind of AST representation for the implied
10684 // memcpy in a union copy operation.
10685 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010686 continue;
10687
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010688 if (Field->isInvalidDecl()) {
10689 Invalid = true;
10690 continue;
10691 }
10692
Sebastian Redl22653ba2011-08-30 19:58:05 +000010693 // Check for members of reference type; we can't move those.
10694 if (Field->getType()->isReferenceType()) {
10695 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10696 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10697 Diag(Field->getLocation(), diag::note_declared_at);
10698 Diag(CurrentLocation, diag::note_member_synthesized_at)
10699 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10700 Invalid = true;
10701 continue;
10702 }
10703
10704 // Check for members of const-qualified, non-class type.
10705 QualType BaseType = Context.getBaseElementType(Field->getType());
10706 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10707 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10708 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10709 Diag(Field->getLocation(), diag::note_declared_at);
10710 Diag(CurrentLocation, diag::note_member_synthesized_at)
10711 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10712 Invalid = true;
10713 continue;
10714 }
10715
10716 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010717 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10718 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010719
10720 QualType FieldType = Field->getType().getNonReferenceType();
10721 if (FieldType->isIncompleteArrayType()) {
10722 assert(ClassDecl->hasFlexibleArrayMember() &&
10723 "Incomplete array type is not valid");
10724 continue;
10725 }
10726
10727 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010728 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10729 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010730 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010731 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010732 MemberBuilder From(MoveOther, OtherRefType,
10733 /*IsArrow=*/false, MemberLookup);
10734 MemberBuilder To(This, getCurrentThisType(),
10735 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010736
Pavel Labath58934982013-08-30 08:52:28 +000010737 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010738 "Member reference with rvalue base must be rvalue except for reference "
10739 "members, which aren't allowed for move assignment.");
10740
Sebastian Redl22653ba2011-08-30 19:58:05 +000010741 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010742 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010743 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010744 /*CopyingBaseSubobject=*/false,
10745 /*Copying=*/false);
10746 if (Move.isInvalid()) {
10747 Diag(CurrentLocation, diag::note_member_synthesized_at)
10748 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10749 MoveAssignOperator->setInvalidDecl();
10750 return;
10751 }
Richard Smith11d19592012-11-12 23:33:00 +000010752
Sebastian Redl22653ba2011-08-30 19:58:05 +000010753 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010754 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010755 }
10756
10757 if (!Invalid) {
10758 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010759 ExprResult ThisObj =
10760 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10761
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010762 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010763 if (Return.isInvalid())
10764 Invalid = true;
10765 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010766 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010767
10768 if (Trap.hasErrorOccurred()) {
10769 Diag(CurrentLocation, diag::note_member_synthesized_at)
10770 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10771 Invalid = true;
10772 }
10773 }
10774 }
10775
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010776 // The exception specification is needed because we are defining the
10777 // function.
10778 ResolveExceptionSpec(CurrentLocation,
10779 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10780
Sebastian Redl22653ba2011-08-30 19:58:05 +000010781 if (Invalid) {
10782 MoveAssignOperator->setInvalidDecl();
10783 return;
10784 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010785
10786 StmtResult Body;
10787 {
10788 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010789 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010790 /*isStmtExpr=*/false);
10791 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10792 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010793 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010794
10795 if (ASTMutationListener *L = getASTMutationListener()) {
10796 L->CompletedImplicitDefinition(MoveAssignOperator);
10797 }
10798}
10799
Richard Smithd3b5c9082012-07-27 04:22:15 +000010800Sema::ImplicitExceptionSpecification
10801Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10802 CXXRecordDecl *ClassDecl = MD->getParent();
10803
10804 ImplicitExceptionSpecification ExceptSpec(*this);
10805 if (ClassDecl->isInvalidDecl())
10806 return ExceptSpec;
10807
10808 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010809 assert(T->getNumParams() >= 1 && "not a copy ctor");
10810 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010811
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010812 // C++ [except.spec]p14:
10813 // An implicitly declared special member function (Clause 12) shall have an
10814 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010815 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010816 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010817 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010818 continue;
10819
Douglas Gregora6d69502010-07-02 23:41:54 +000010820 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010821 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010822 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010823 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010824 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010825 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010826 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010827 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010828 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010829 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010830 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010831 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010832 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010833 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010834 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010835 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10836 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010837 LookupCopyingConstructor(FieldClassDecl,
10838 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010839 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010840 }
10841 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010842
Richard Smithd3b5c9082012-07-27 04:22:15 +000010843 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010844}
10845
10846CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10847 CXXRecordDecl *ClassDecl) {
10848 // C++ [class.copy]p4:
10849 // If the class definition does not explicitly declare a copy
10850 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010851 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010852
Richard Smith8bf22e52012-11-29 01:34:07 +000010853 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10854 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010855 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010856
Alexis Hunt913820d2011-05-13 06:10:58 +000010857 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10858 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010859 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010860 if (Const)
10861 ArgType = ArgType.withConst();
10862 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010863
Richard Smithb5800092012-06-10 05:43:50 +000010864 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10865 CXXCopyConstructor,
10866 Const);
10867
Douglas Gregor54be3392010-07-01 17:57:27 +000010868 DeclarationName Name
10869 = Context.DeclarationNames.getCXXConstructorName(
10870 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010871 SourceLocation ClassLoc = ClassDecl->getLocation();
10872 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010873
10874 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010875 // member of its class.
10876 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010877 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010878 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010879 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010880 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010881 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010882
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010883 if (getLangOpts().CUDA) {
10884 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10885 CopyConstructor,
10886 /* ConstRHS */ Const,
10887 /* Diagnose */ false);
10888 }
10889
Richard Smithd3b5c9082012-07-27 04:22:15 +000010890 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010891 FunctionProtoType::ExtProtoInfo EPI =
10892 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010893 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010894 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010895
Douglas Gregor54be3392010-07-01 17:57:27 +000010896 // Add the parameter to the constructor.
10897 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010898 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010899 /*IdentifierInfo=*/nullptr,
10900 ArgType, /*TInfo=*/nullptr,
10901 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010902 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010903
Richard Smith6b02d462012-12-08 08:32:28 +000010904 CopyConstructor->setTrivial(
10905 ClassDecl->needsOverloadResolutionForCopyConstructor()
10906 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10907 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010908
Richard Smith852265f2012-03-30 20:53:28 +000010909 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010910 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010911
Richard Smith6b02d462012-12-08 08:32:28 +000010912 // Note that we have declared this constructor.
10913 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10914
10915 if (Scope *S = getScopeForContext(ClassDecl))
10916 PushOnScopeChains(CopyConstructor, S, false);
10917 ClassDecl->addDecl(CopyConstructor);
10918
Douglas Gregor54be3392010-07-01 17:57:27 +000010919 return CopyConstructor;
10920}
10921
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010922void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010923 CXXConstructorDecl *CopyConstructor) {
10924 assert((CopyConstructor->isDefaulted() &&
10925 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010926 !CopyConstructor->doesThisDeclarationHaveABody() &&
10927 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010928 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010929
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010930 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010931 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010932
Richard Smithd577fbb2013-06-13 03:23:42 +000010933 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010934 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010935 // deprecated if the class has a user-declared copy assignment operator
10936 // or a user-declared destructor.
10937 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10938 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10939
Eli Friedmaneaf34142012-10-18 20:14:08 +000010940 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010941 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010942
David Blaikie3fc2f912013-01-17 05:26:25 +000010943 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010944 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010945 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010946 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010947 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010948 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010949 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10950 ? CopyConstructor->getLocEnd()
10951 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010952 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010953 CopyConstructor->setBody(
10954 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010955 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010956
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010957 // The exception specification is needed because we are defining the
10958 // function.
10959 ResolveExceptionSpec(CurrentLocation,
10960 CopyConstructor->getType()->castAs<FunctionProtoType>());
10961
Eli Friedman276dd182013-09-05 00:02:25 +000010962 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010963 MarkVTableUsed(CurrentLocation, ClassDecl);
10964
Sebastian Redlab238a72011-04-24 16:28:06 +000010965 if (ASTMutationListener *L = getASTMutationListener()) {
10966 L->CompletedImplicitDefinition(CopyConstructor);
10967 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010968}
10969
Sebastian Redl22653ba2011-08-30 19:58:05 +000010970Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010971Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10972 CXXRecordDecl *ClassDecl = MD->getParent();
10973
Sebastian Redl22653ba2011-08-30 19:58:05 +000010974 // C++ [except.spec]p14:
10975 // An implicitly declared special member function (Clause 12) shall have an
10976 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010977 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010978 if (ClassDecl->isInvalidDecl())
10979 return ExceptSpec;
10980
10981 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010982 for (const auto &B : ClassDecl->bases()) {
10983 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010984 continue;
10985
Aaron Ballman574705e2014-03-13 15:41:46 +000010986 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010987 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010988 CXXConstructorDecl *Constructor =
10989 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010990 // If this is a deleted function, add it anyway. This might be conformant
10991 // with the standard. This might not. I'm not sure. It might not matter.
10992 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010993 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010994 }
10995 }
10996
10997 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010998 for (const auto &B : ClassDecl->vbases()) {
10999 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011000 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011001 CXXConstructorDecl *Constructor =
11002 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011003 // If this is a deleted function, add it anyway. This might be conformant
11004 // with the standard. This might not. I'm not sure. It might not matter.
11005 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011006 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011007 }
11008 }
11009
11010 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011011 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011012 QualType FieldType = Context.getBaseElementType(F->getType());
11013 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11014 CXXConstructorDecl *Constructor =
11015 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011016 // If this is a deleted function, add it anyway. This might be conformant
11017 // with the standard. This might not. I'm not sure. It might not matter.
11018 // In particular, the problem is that this function never gets called. It
11019 // might just be ill-formed because this function attempts to refer to
11020 // a deleted function here.
11021 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011022 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011023 }
11024 }
11025
11026 return ExceptSpec;
11027}
11028
11029CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11030 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011031 assert(ClassDecl->needsImplicitMoveConstructor());
11032
Richard Smith8bf22e52012-11-29 01:34:07 +000011033 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11034 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011035 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011036
Sebastian Redl22653ba2011-08-30 19:58:05 +000011037 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11038 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011039
Richard Smithb5800092012-06-10 05:43:50 +000011040 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11041 CXXMoveConstructor,
11042 false);
11043
Sebastian Redl22653ba2011-08-30 19:58:05 +000011044 DeclarationName Name
11045 = Context.DeclarationNames.getCXXConstructorName(
11046 Context.getCanonicalType(ClassType));
11047 SourceLocation ClassLoc = ClassDecl->getLocation();
11048 DeclarationNameInfo NameInfo(Name, ClassLoc);
11049
Richard Smith99005e62013-05-07 03:19:20 +000011050 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011051 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011052 // member of its class.
11053 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011054 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011055 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011056 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011057 MoveConstructor->setAccess(AS_public);
11058 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011059
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011060 if (getLangOpts().CUDA) {
11061 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11062 MoveConstructor,
11063 /* ConstRHS */ false,
11064 /* Diagnose */ false);
11065 }
11066
Richard Smithd3b5c9082012-07-27 04:22:15 +000011067 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011068 FunctionProtoType::ExtProtoInfo EPI =
11069 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011070 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011071 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011072
Sebastian Redl22653ba2011-08-30 19:58:05 +000011073 // Add the parameter to the constructor.
11074 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11075 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011076 /*IdentifierInfo=*/nullptr,
11077 ArgType, /*TInfo=*/nullptr,
11078 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011079 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011080
Richard Smith6b02d462012-12-08 08:32:28 +000011081 MoveConstructor->setTrivial(
11082 ClassDecl->needsOverloadResolutionForMoveConstructor()
11083 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11084 : ClassDecl->hasTrivialMoveConstructor());
11085
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000011086 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011087 ClassDecl->setImplicitMoveConstructorIsDeleted();
11088 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011089 }
11090
11091 // Note that we have declared this constructor.
11092 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11093
11094 if (Scope *S = getScopeForContext(ClassDecl))
11095 PushOnScopeChains(MoveConstructor, S, false);
11096 ClassDecl->addDecl(MoveConstructor);
11097
11098 return MoveConstructor;
11099}
11100
11101void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11102 CXXConstructorDecl *MoveConstructor) {
11103 assert((MoveConstructor->isDefaulted() &&
11104 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011105 !MoveConstructor->doesThisDeclarationHaveABody() &&
11106 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011107 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11108
11109 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11110 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11111
Eli Friedmaneaf34142012-10-18 20:14:08 +000011112 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011113 DiagnosticErrorTrap Trap(Diags);
11114
David Blaikie3fc2f912013-01-17 05:26:25 +000011115 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011116 Trap.hasErrorOccurred()) {
11117 Diag(CurrentLocation, diag::note_member_synthesized_at)
11118 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11119 MoveConstructor->setInvalidDecl();
11120 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011121 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11122 ? MoveConstructor->getLocEnd()
11123 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011124 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011125 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011126 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011127 }
11128
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011129 // The exception specification is needed because we are defining the
11130 // function.
11131 ResolveExceptionSpec(CurrentLocation,
11132 MoveConstructor->getType()->castAs<FunctionProtoType>());
11133
Eli Friedman276dd182013-09-05 00:02:25 +000011134 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011135 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011136
11137 if (ASTMutationListener *L = getASTMutationListener()) {
11138 L->CompletedImplicitDefinition(MoveConstructor);
11139 }
11140}
11141
Douglas Gregor74f7d502012-02-15 19:33:52 +000011142bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011143 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011144}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011145
11146void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011147 SourceLocation CurrentLocation,
11148 CXXConversionDecl *Conv) {
11149 CXXRecordDecl *Lambda = Conv->getParent();
11150 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11151 // If we are defining a specialization of a conversion to function-ptr
11152 // cache the deduced template arguments for this specialization
11153 // so that we can use them to retrieve the corresponding call-operator
11154 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011155 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11156
Faisal Vali571df122013-09-29 08:45:24 +000011157 // Retrieve the corresponding call-operator specialization.
11158 if (Lambda->isGenericLambda()) {
11159 assert(Conv->isFunctionTemplateSpecialization());
11160 FunctionTemplateDecl *CallOpTemplate =
11161 CallOp->getDescribedFunctionTemplate();
11162 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011163 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011164 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011165 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011166 InsertPos);
11167 assert(CallOpSpec &&
11168 "Conversion operator must have a corresponding call operator");
11169 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11170 }
11171 // Mark the call operator referenced (and add to pending instantiations
11172 // if necessary).
11173 // For both the conversion and static-invoker template specializations
11174 // we construct their body's in this function, so no need to add them
11175 // to the PendingInstantiations.
11176 MarkFunctionReferenced(CurrentLocation, CallOp);
11177
Eli Friedmaneaf34142012-10-18 20:14:08 +000011178 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011179 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011180
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011181 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011182 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11183 // ... and get the corresponding specialization for a generic lambda.
11184 if (Lambda->isGenericLambda()) {
11185 assert(DeducedTemplateArgs &&
11186 "Must have deduced template arguments from Conversion Operator");
11187 FunctionTemplateDecl *InvokeTemplate =
11188 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011189 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011190 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011191 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011192 InsertPos);
11193 assert(InvokeSpec &&
11194 "Must have a corresponding static invoker specialization");
11195 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11196 }
11197 // Construct the body of the conversion function { return __invoke; }.
11198 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011199 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011200 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011201 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011202 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11203 Conv->getLocation(),
11204 Conv->getLocation()));
11205
11206 Conv->markUsed(Context);
11207 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011208
Faisal Vali571df122013-09-29 08:45:24 +000011209 // Fill in the __invoke function with a dummy implementation. IR generation
11210 // will fill in the actual details.
11211 Invoker->markUsed(Context);
11212 Invoker->setReferenced();
11213 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11214
Douglas Gregord3b672c2012-02-16 01:06:16 +000011215 if (ASTMutationListener *L = getASTMutationListener()) {
11216 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011217 L->CompletedImplicitDefinition(Invoker);
11218 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011219}
11220
Faisal Vali571df122013-09-29 08:45:24 +000011221
11222
Douglas Gregord3b672c2012-02-16 01:06:16 +000011223void Sema::DefineImplicitLambdaToBlockPointerConversion(
11224 SourceLocation CurrentLocation,
11225 CXXConversionDecl *Conv)
11226{
Faisal Vali850da1a2013-09-29 17:08:32 +000011227 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011228
Eli Friedman276dd182013-09-05 00:02:25 +000011229 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011230
Eli Friedmaneaf34142012-10-18 20:14:08 +000011231 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011232 DiagnosticErrorTrap Trap(Diags);
11233
Douglas Gregored90df32012-02-22 05:02:47 +000011234 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011235 Expr *This = ActOnCXXThis(CurrentLocation).get();
11236 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011237
Eli Friedman98b01ed2012-03-01 04:01:32 +000011238 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11239 Conv->getLocation(),
11240 Conv, DerefThis);
11241
11242 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11243 // behavior. Note that only the general conversion function does this
11244 // (since it's unusable otherwise); in the case where we inline the
11245 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011246 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011247 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11248 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011249 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011250
11251 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011252 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011253 Conv->setInvalidDecl();
11254 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011255 }
Douglas Gregored90df32012-02-22 05:02:47 +000011256
Douglas Gregored90df32012-02-22 05:02:47 +000011257 // Create the return statement that returns the block from the conversion
11258 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011259 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011260 if (Return.isInvalid()) {
11261 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11262 Conv->setInvalidDecl();
11263 return;
11264 }
11265
11266 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011267 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011268 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011269 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011270 Conv->getLocation()));
11271
Douglas Gregored90df32012-02-22 05:02:47 +000011272 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011273 if (ASTMutationListener *L = getASTMutationListener()) {
11274 L->CompletedImplicitDefinition(Conv);
11275 }
11276}
11277
Douglas Gregord2f70072012-03-10 06:53:13 +000011278/// \brief Determine whether the given list arguments contains exactly one
11279/// "real" (non-default) argument.
11280static bool hasOneRealArgument(MultiExprArg Args) {
11281 switch (Args.size()) {
11282 case 0:
11283 return false;
11284
11285 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011286 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011287 return false;
11288
11289 // fall through
11290 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011291 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011292 }
11293
11294 return false;
11295}
11296
John McCalldadc5752010-08-24 06:29:42 +000011297ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011298Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011299 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011300 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011301 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011302 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011303 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011304 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011305 unsigned ConstructKind,
11306 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011307 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011308
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011309 // C++0x [class.copy]p34:
11310 // When certain criteria are met, an implementation is allowed to
11311 // omit the copy/move construction of a class object, even if the
11312 // copy/move constructor and/or destructor for the object have
11313 // side effects. [...]
11314 // - when a temporary class object that has not been bound to a
11315 // reference (12.2) would be copied/moved to a class object
11316 // with the same cv-unqualified type, the copy/move operation
11317 // can be omitted by constructing the temporary object
11318 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011319 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011320 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011321 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011322 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011323 }
Mike Stump11289f42009-09-09 15:08:12 +000011324
11325 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011326 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011327 IsListInitialization,
11328 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011329 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011330}
11331
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011332/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11333/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011334ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011335Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11336 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011337 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011338 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011339 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011340 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011341 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011342 unsigned ConstructKind,
11343 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011344 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011345 return CXXConstructExpr::Create(
11346 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011347 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11348 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011349 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11350 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011351}
11352
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011353ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11354 assert(Field->hasInClassInitializer());
11355
11356 // If we already have the in-class initializer nothing needs to be done.
11357 if (Field->getInClassInitializer())
11358 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11359
11360 // Maybe we haven't instantiated the in-class initializer. Go check the
11361 // pattern FieldDecl to see if it has one.
11362 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11363
11364 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11365 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11366 DeclContext::lookup_result Lookup =
11367 ClassPattern->lookup(Field->getDeclName());
11368 assert(Lookup.size() == 1);
11369 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11370 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11371 getTemplateInstantiationArgs(Field)))
11372 return ExprError();
11373 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11374 }
11375
11376 // DR1351:
11377 // If the brace-or-equal-initializer of a non-static data member
11378 // invokes a defaulted default constructor of its class or of an
11379 // enclosing class in a potentially evaluated subexpression, the
11380 // program is ill-formed.
11381 //
11382 // This resolution is unworkable: the exception specification of the
11383 // default constructor can be needed in an unevaluated context, in
11384 // particular, in the operand of a noexcept-expression, and we can be
11385 // unable to compute an exception specification for an enclosed class.
11386 //
11387 // Any attempt to resolve the exception specification of a defaulted default
11388 // constructor before the initializer is lexically complete will ultimately
11389 // come here at which point we can diagnose it.
11390 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11391 if (OutermostClass == ParentRD) {
11392 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11393 << ParentRD << Field;
11394 } else {
11395 Diag(Field->getLocEnd(),
11396 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11397 << ParentRD << OutermostClass << Field;
11398 }
11399
11400 return ExprError();
11401}
11402
John McCall03c48482010-02-02 09:10:11 +000011403void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011404 if (VD->isInvalidDecl()) return;
11405
John McCall03c48482010-02-02 09:10:11 +000011406 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011407 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011408 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011409 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011410
Chandler Carruth86d17d32011-03-27 21:26:48 +000011411 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011412 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011413 CheckDestructorAccess(VD->getLocation(), Destructor,
11414 PDiag(diag::err_access_dtor_var)
11415 << VD->getDeclName()
11416 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011417 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011418
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011419 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011420 if (!VD->hasGlobalStorage()) return;
11421
11422 // Emit warning for non-trivial dtor in global scope (a real global,
11423 // class-static, function-static).
11424 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11425
11426 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011427 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011428 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011429}
11430
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011431/// \brief Given a constructor and the set of arguments provided for the
11432/// constructor, convert the arguments and add any required default arguments
11433/// to form a proper call to this constructor.
11434///
11435/// \returns true if an error occurred, false otherwise.
11436bool
11437Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11438 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011439 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011440 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011441 bool AllowExplicit,
11442 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011443 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11444 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011445 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011446
11447 const FunctionProtoType *Proto
11448 = Constructor->getType()->getAs<FunctionProtoType>();
11449 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011450 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011451
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011452 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011453 if (NumArgs < NumParams)
11454 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011455 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011456 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011457
11458 VariadicCallType CallType =
11459 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011460 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011461 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011462 Proto, 0,
11463 llvm::makeArrayRef(Args, NumArgs),
11464 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011465 CallType, AllowExplicit,
11466 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011467 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011468
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011469 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011470
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011471 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011472 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011473 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011474
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011475 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011476}
11477
Anders Carlssone363c8e2009-12-12 00:32:00 +000011478static inline bool
11479CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11480 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011481 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011482 if (isa<NamespaceDecl>(DC)) {
11483 return SemaRef.Diag(FnDecl->getLocation(),
11484 diag::err_operator_new_delete_declared_in_namespace)
11485 << FnDecl->getDeclName();
11486 }
11487
11488 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011489 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011490 return SemaRef.Diag(FnDecl->getLocation(),
11491 diag::err_operator_new_delete_declared_static)
11492 << FnDecl->getDeclName();
11493 }
11494
Anders Carlsson60659a82009-12-12 02:43:16 +000011495 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011496}
11497
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011498static inline bool
11499CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11500 CanQualType ExpectedResultType,
11501 CanQualType ExpectedFirstParamType,
11502 unsigned DependentParamTypeDiag,
11503 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011504 QualType ResultType =
11505 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011506
11507 // Check that the result type is not dependent.
11508 if (ResultType->isDependentType())
11509 return SemaRef.Diag(FnDecl->getLocation(),
11510 diag::err_operator_new_delete_dependent_result_type)
11511 << FnDecl->getDeclName() << ExpectedResultType;
11512
11513 // Check that the result type is what we expect.
11514 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11515 return SemaRef.Diag(FnDecl->getLocation(),
11516 diag::err_operator_new_delete_invalid_result_type)
11517 << FnDecl->getDeclName() << ExpectedResultType;
11518
11519 // A function template must have at least 2 parameters.
11520 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11521 return SemaRef.Diag(FnDecl->getLocation(),
11522 diag::err_operator_new_delete_template_too_few_parameters)
11523 << FnDecl->getDeclName();
11524
11525 // The function decl must have at least 1 parameter.
11526 if (FnDecl->getNumParams() == 0)
11527 return SemaRef.Diag(FnDecl->getLocation(),
11528 diag::err_operator_new_delete_too_few_parameters)
11529 << FnDecl->getDeclName();
11530
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011531 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011532 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11533 if (FirstParamType->isDependentType())
11534 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11535 << FnDecl->getDeclName() << ExpectedFirstParamType;
11536
11537 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011538 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011539 ExpectedFirstParamType)
11540 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11541 << FnDecl->getDeclName() << ExpectedFirstParamType;
11542
11543 return false;
11544}
11545
Anders Carlsson12308f42009-12-11 23:23:22 +000011546static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011547CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011548 // C++ [basic.stc.dynamic.allocation]p1:
11549 // A program is ill-formed if an allocation function is declared in a
11550 // namespace scope other than global scope or declared static in global
11551 // scope.
11552 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11553 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011554
11555 CanQualType SizeTy =
11556 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11557
11558 // C++ [basic.stc.dynamic.allocation]p1:
11559 // The return type shall be void*. The first parameter shall have type
11560 // std::size_t.
11561 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11562 SizeTy,
11563 diag::err_operator_new_dependent_param_type,
11564 diag::err_operator_new_param_type))
11565 return true;
11566
11567 // C++ [basic.stc.dynamic.allocation]p1:
11568 // The first parameter shall not have an associated default argument.
11569 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011570 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011571 diag::err_operator_new_default_arg)
11572 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11573
11574 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011575}
11576
11577static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011578CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011579 // C++ [basic.stc.dynamic.deallocation]p1:
11580 // A program is ill-formed if deallocation functions are declared in a
11581 // namespace scope other than global scope or declared static in global
11582 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011583 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11584 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011585
11586 // C++ [basic.stc.dynamic.deallocation]p2:
11587 // Each deallocation function shall return void and its first parameter
11588 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011589 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11590 SemaRef.Context.VoidPtrTy,
11591 diag::err_operator_delete_dependent_param_type,
11592 diag::err_operator_delete_param_type))
11593 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011594
Anders Carlsson12308f42009-12-11 23:23:22 +000011595 return false;
11596}
11597
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011598/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11599/// of this overloaded operator is well-formed. If so, returns false;
11600/// otherwise, emits appropriate diagnostics and returns true.
11601bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011602 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011603 "Expected an overloaded operator declaration");
11604
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011605 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11606
Mike Stump11289f42009-09-09 15:08:12 +000011607 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011608 // The allocation and deallocation functions, operator new,
11609 // operator new[], operator delete and operator delete[], are
11610 // described completely in 3.7.3. The attributes and restrictions
11611 // found in the rest of this subclause do not apply to them unless
11612 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011613 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011614 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011615
Anders Carlsson22f443f2009-12-12 00:26:23 +000011616 if (Op == OO_New || Op == OO_Array_New)
11617 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011618
11619 // C++ [over.oper]p6:
11620 // An operator function shall either be a non-static member
11621 // function or be a non-member function and have at least one
11622 // parameter whose type is a class, a reference to a class, an
11623 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011624 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11625 if (MethodDecl->isStatic())
11626 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011627 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011628 } else {
11629 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011630 for (auto Param : FnDecl->params()) {
11631 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011632 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11633 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011634 ClassOrEnumParam = true;
11635 break;
11636 }
11637 }
11638
Douglas Gregord69246b2008-11-17 16:14:12 +000011639 if (!ClassOrEnumParam)
11640 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011641 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011642 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011643 }
11644
11645 // C++ [over.oper]p8:
11646 // An operator function cannot have default arguments (8.3.6),
11647 // except where explicitly stated below.
11648 //
Mike Stump11289f42009-09-09 15:08:12 +000011649 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011650 // (C++ [over.call]p1).
11651 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011652 for (auto Param : FnDecl->params()) {
11653 if (Param->hasDefaultArg())
11654 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011655 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011656 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011657 }
11658 }
11659
Douglas Gregor6cf08062008-11-10 13:38:07 +000011660 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11661 { false, false, false }
11662#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11663 , { Unary, Binary, MemberOnly }
11664#include "clang/Basic/OperatorKinds.def"
11665 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011666
Douglas Gregor6cf08062008-11-10 13:38:07 +000011667 bool CanBeUnaryOperator = OperatorUses[Op][0];
11668 bool CanBeBinaryOperator = OperatorUses[Op][1];
11669 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011670
11671 // C++ [over.oper]p8:
11672 // [...] Operator functions cannot have more or fewer parameters
11673 // than the number required for the corresponding operator, as
11674 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011675 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011676 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011677 if (Op != OO_Call &&
11678 ((NumParams == 1 && !CanBeUnaryOperator) ||
11679 (NumParams == 2 && !CanBeBinaryOperator) ||
11680 (NumParams < 1) || (NumParams > 2))) {
11681 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011682 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011683 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011684 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011685 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011686 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011687 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011688 assert(CanBeBinaryOperator &&
11689 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011690 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011691 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011692
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011693 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011694 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011695 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011696
Douglas Gregord69246b2008-11-17 16:14:12 +000011697 // Overloaded operators other than operator() cannot be variadic.
11698 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011699 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011700 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011701 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011702 }
11703
11704 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011705 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11706 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011707 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011708 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011709 }
11710
11711 // C++ [over.inc]p1:
11712 // The user-defined function called operator++ implements the
11713 // prefix and postfix ++ operator. If this function is a member
11714 // function with no parameters, or a non-member function with one
11715 // parameter of class or enumeration type, it defines the prefix
11716 // increment operator ++ for objects of that type. If the function
11717 // is a member function with one parameter (which shall be of type
11718 // int) or a non-member function with two parameters (the second
11719 // of which shall be of type int), it defines the postfix
11720 // increment operator ++ for objects of that type.
11721 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11722 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011723 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011724
Richard Smith538b52a2014-01-30 22:24:05 +000011725 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11726 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011727 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011728 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011729 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011730 }
11731
Douglas Gregord69246b2008-11-17 16:14:12 +000011732 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011733}
Chris Lattner3b024a32008-12-17 07:09:26 +000011734
Alexis Huntc88db062010-01-13 09:01:02 +000011735/// CheckLiteralOperatorDeclaration - Check whether the declaration
11736/// of this literal operator function is well-formed. If so, returns
11737/// false; otherwise, emits appropriate diagnostics and returns true.
11738bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011739 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011740 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11741 << FnDecl->getDeclName();
11742 return true;
11743 }
11744
Richard Smith72eebee2012-03-04 09:41:16 +000011745 if (FnDecl->isExternC()) {
11746 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11747 return true;
11748 }
11749
Alexis Huntc88db062010-01-13 09:01:02 +000011750 bool Valid = false;
11751
Richard Smithbcc22fc2012-03-09 08:00:36 +000011752 // This might be the definition of a literal operator template.
11753 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11754 // This might be a specialization of a literal operator template.
11755 if (!TpDecl)
11756 TpDecl = FnDecl->getPrimaryTemplate();
11757
Richard Smithb8b41d32013-10-07 19:57:58 +000011758 // template <char...> type operator "" name() and
11759 // template <class T, T...> type operator "" name() are the only valid
11760 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011761 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011762 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011763 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011764 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11765 if (Params->size() == 1) {
11766 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011767 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011768
Alexis Hunt7dd26172010-04-07 23:11:06 +000011769 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011770 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11771 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11772 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011773 } else if (Params->size() == 2) {
11774 TemplateTypeParmDecl *PmType =
11775 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11776 NonTypeTemplateParmDecl *PmArgs =
11777 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11778
11779 // The second template parameter must be a parameter pack with the
11780 // first template parameter as its type.
11781 if (PmType && PmArgs &&
11782 !PmType->isTemplateParameterPack() &&
11783 PmArgs->isTemplateParameterPack()) {
11784 const TemplateTypeParmType *TArgs =
11785 PmArgs->getType()->getAs<TemplateTypeParmType>();
11786 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11787 TArgs->getIndex() == PmType->getIndex()) {
11788 Valid = true;
11789 if (ActiveTemplateInstantiations.empty())
11790 Diag(FnDecl->getLocation(),
11791 diag::ext_string_literal_operator_template);
11792 }
11793 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011794 }
11795 }
Richard Smith72eebee2012-03-04 09:41:16 +000011796 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011797 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011798 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11799
Richard Smith72eebee2012-03-04 09:41:16 +000011800 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011801
Alexis Hunt079a6f72010-04-07 22:57:35 +000011802 // unsigned long long int, long double, and any character type are allowed
11803 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011804 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11805 Context.hasSameType(T, Context.LongDoubleTy) ||
11806 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011807 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011808 Context.hasSameType(T, Context.Char16Ty) ||
11809 Context.hasSameType(T, Context.Char32Ty)) {
11810 if (++Param == FnDecl->param_end())
11811 Valid = true;
11812 goto FinishedParams;
11813 }
11814
Alexis Hunt079a6f72010-04-07 22:57:35 +000011815 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011816 const PointerType *PT = T->getAs<PointerType>();
11817 if (!PT)
11818 goto FinishedParams;
11819 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011820 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011821 goto FinishedParams;
11822 T = T.getUnqualifiedType();
11823
11824 // Move on to the second parameter;
11825 ++Param;
11826
11827 // If there is no second parameter, the first must be a const char *
11828 if (Param == FnDecl->param_end()) {
11829 if (Context.hasSameType(T, Context.CharTy))
11830 Valid = true;
11831 goto FinishedParams;
11832 }
11833
11834 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11835 // are allowed as the first parameter to a two-parameter function
11836 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011837 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011838 Context.hasSameType(T, Context.Char16Ty) ||
11839 Context.hasSameType(T, Context.Char32Ty)))
11840 goto FinishedParams;
11841
11842 // The second and final parameter must be an std::size_t
11843 T = (*Param)->getType().getUnqualifiedType();
11844 if (Context.hasSameType(T, Context.getSizeType()) &&
11845 ++Param == FnDecl->param_end())
11846 Valid = true;
11847 }
11848
11849 // FIXME: This diagnostic is absolutely terrible.
11850FinishedParams:
11851 if (!Valid) {
11852 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11853 << FnDecl->getDeclName();
11854 return true;
11855 }
11856
Richard Smith768cecc2012-03-09 08:16:22 +000011857 // A parameter-declaration-clause containing a default argument is not
11858 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011859 for (auto Param : FnDecl->params()) {
11860 if (Param->hasDefaultArg()) {
11861 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011862 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011863 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011864 break;
11865 }
11866 }
11867
Richard Smith0df56f42012-03-08 02:39:21 +000011868 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011869 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11870 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011871 // C++11 [usrlit.suffix]p1:
11872 // Literal suffix identifiers that do not start with an underscore
11873 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011874 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11875 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011876 }
Richard Smith0df56f42012-03-08 02:39:21 +000011877
Alexis Huntc88db062010-01-13 09:01:02 +000011878 return false;
11879}
11880
Douglas Gregor07665a62009-01-05 19:45:36 +000011881/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11882/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011883/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11884/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011885/// the '{' brace. Otherwise, this linkage specification does not
11886/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011887Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011888 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011889 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011890 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11891 if (!Lit->isAscii()) {
11892 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11893 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011894 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011895 }
11896
11897 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011898 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011899 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011900 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011901 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011902 Language = LinkageSpecDecl::lang_cxx;
11903 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011904 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11905 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011906 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011907 }
Mike Stump11289f42009-09-09 15:08:12 +000011908
Chris Lattner438e5012008-12-17 07:13:27 +000011909 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011910
Richard Smith4ee696d2014-02-17 23:25:27 +000011911 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11912 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011913 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011914 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011915 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011916 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011917}
11918
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011919/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011920/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11921/// valid, it's the position of the closing '}' brace in a linkage
11922/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011923Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011924 Decl *LinkageSpec,
11925 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011926 if (RBraceLoc.isValid()) {
11927 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11928 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011929 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011930 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011931 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011932}
11933
Michael Han84324352013-02-22 17:15:32 +000011934Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11935 AttributeList *AttrList,
11936 SourceLocation SemiLoc) {
11937 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11938 // Attribute declarations appertain to empty declaration so we handle
11939 // them here.
11940 if (AttrList)
11941 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011942
Michael Han84324352013-02-22 17:15:32 +000011943 CurContext->addDecl(ED);
11944 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011945}
11946
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011947/// \brief Perform semantic analysis for the variable declaration that
11948/// occurs within a C++ catch clause, returning the newly-created
11949/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011950VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011951 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011952 SourceLocation StartLoc,
11953 SourceLocation Loc,
11954 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011955 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011956 QualType ExDeclType = TInfo->getType();
11957
Sebastian Redl54c04d42008-12-22 19:15:10 +000011958 // Arrays and functions decay.
11959 if (ExDeclType->isArrayType())
11960 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11961 else if (ExDeclType->isFunctionType())
11962 ExDeclType = Context.getPointerType(ExDeclType);
11963
11964 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11965 // The exception-declaration shall not denote a pointer or reference to an
11966 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011967 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011968 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011969 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011970 Invalid = true;
11971 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011972
Sebastian Redl54c04d42008-12-22 19:15:10 +000011973 QualType BaseType = ExDeclType;
11974 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011975 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011976 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011977 BaseType = Ptr->getPointeeType();
11978 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011979 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011980 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011981 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011982 BaseType = Ref->getPointeeType();
11983 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011984 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011985 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011986 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011987 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011988 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011989
Mike Stump11289f42009-09-09 15:08:12 +000011990 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011991 RequireNonAbstractType(Loc, ExDeclType,
11992 diag::err_abstract_type_in_decl,
11993 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011994 Invalid = true;
11995
John McCall2ca705e2010-07-24 00:37:23 +000011996 // Only the non-fragile NeXT runtime currently supports C++ catches
11997 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011998 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011999 QualType T = ExDeclType;
12000 if (const ReferenceType *RT = T->getAs<ReferenceType>())
12001 T = RT->getPointeeType();
12002
12003 if (T->isObjCObjectType()) {
12004 Diag(Loc, diag::err_objc_object_catch);
12005 Invalid = true;
12006 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000012007 // FIXME: should this be a test for macosx-fragile specifically?
12008 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000012009 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000012010 }
12011 }
12012
Abramo Bagnaradff19302011-03-08 08:55:46 +000012013 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000012014 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000012015 ExDecl->setExceptionVariable(true);
12016
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012017 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012018 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012019 Invalid = true;
12020
Douglas Gregor750734c2011-07-06 18:14:43 +000012021 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000012022 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000012023 // Insulate this from anything else we might currently be parsing.
12024 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12025
Douglas Gregor6de584c2010-03-05 23:38:39 +000012026 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000012027 // The object declared in an exception-declaration or, if the
12028 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000012029 // copy-initialized (8.5) from the exception object. [...]
12030 // The object is destroyed when the handler exits, after the destruction
12031 // of any automatic objects initialized within the handler.
12032 //
Nick Lewycky0f292892013-09-22 10:06:57 +000012033 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000012034 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000012035 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000012036
12037 InitializedEntity entity =
12038 InitializedEntity::InitializeVariable(ExDecl);
12039 InitializationKind initKind =
12040 InitializationKind::CreateCopy(Loc, SourceLocation());
12041
12042 Expr *opaqueValue =
12043 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000012044 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12045 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000012046 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000012047 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000012048 else {
12049 // If the constructor used was non-trivial, set this as the
12050 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012051 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000012052 if (!construct->getConstructor()->isTrivial()) {
12053 Expr *init = MaybeCreateExprWithCleanups(construct);
12054 ExDecl->setInit(init);
12055 }
12056
12057 // And make sure it's destructable.
12058 FinalizeVarWithDestructor(ExDecl, recordType);
12059 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000012060 }
12061 }
12062
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012063 if (Invalid)
12064 ExDecl->setInvalidDecl();
12065
12066 return ExDecl;
12067}
12068
12069/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12070/// handler.
John McCall48871652010-08-21 09:40:31 +000012071Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000012072 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000012073 bool Invalid = D.isInvalidType();
12074
12075 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000012076 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12077 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000012078 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12079 D.getIdentifierLoc());
12080 Invalid = true;
12081 }
12082
Sebastian Redl54c04d42008-12-22 19:15:10 +000012083 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012084 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000012085 LookupOrdinaryName,
12086 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012087 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012088 // it contains any previous declaration, except for function parameters in
12089 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012090 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012091 if (isDeclInScope(PrevDecl, CurContext, S)) {
12092 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12093 << D.getIdentifier();
12094 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12095 Invalid = true;
12096 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012097 // Maybe we will complain about the shadowed template parameter.
12098 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012099 }
12100
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012101 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012102 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12103 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012104 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012105 }
12106
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012107 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012108 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012109 D.getIdentifierLoc(),
12110 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012111 if (Invalid)
12112 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012113
Sebastian Redl54c04d42008-12-22 19:15:10 +000012114 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012115 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012116 PushOnScopeChains(ExDecl, S);
12117 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012118 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012119
Douglas Gregor758a8692009-06-17 21:51:59 +000012120 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012121 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012122}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012123
Abramo Bagnaraea947882011-03-08 16:41:52 +000012124Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012125 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012126 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012127 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012128 StringLiteral *AssertMessage =
12129 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012130
Richard Smithded9c2e2012-07-11 22:37:56 +000012131 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012132 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012133
12134 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12135 AssertMessage, RParenLoc, false);
12136}
12137
12138Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12139 Expr *AssertExpr,
12140 StringLiteral *AssertMessage,
12141 SourceLocation RParenLoc,
12142 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012143 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012144 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12145 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012146 // In a static_assert-declaration, the constant-expression shall be a
12147 // constant expression that can be contextually converted to bool.
12148 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12149 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012150 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012151
Richard Smith902ca212011-12-14 23:32:26 +000012152 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012153 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012154 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012155 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012156 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012157
Richard Smithded9c2e2012-07-11 22:37:56 +000012158 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012159 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012160 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012161 if (AssertMessage)
12162 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012163 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012164 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012165 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012166 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012167 }
Mike Stump11289f42009-09-09 15:08:12 +000012168
Abramo Bagnaraea947882011-03-08 16:41:52 +000012169 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012170 AssertExpr, AssertMessage, RParenLoc,
12171 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012172
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012173 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012174 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012175}
Sebastian Redlf769df52009-03-24 22:27:57 +000012176
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012177/// \brief Perform semantic analysis of the given friend type declaration.
12178///
12179/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012180FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012181 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012182 TypeSourceInfo *TSInfo) {
12183 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12184
12185 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012186 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012187
Richard Smithc8239732011-10-18 21:39:00 +000012188 // C++03 [class.friend]p2:
12189 // An elaborated-type-specifier shall be used in a friend declaration
12190 // for a class.*
12191 //
12192 // * The class-key of the elaborated-type-specifier is required.
12193 if (!ActiveTemplateInstantiations.empty()) {
12194 // Do not complain about the form of friend template types during
12195 // template instantiation; we will already have complained when the
12196 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012197 } else {
12198 if (!T->isElaboratedTypeSpecifier()) {
12199 // If we evaluated the type to a record type, suggest putting
12200 // a tag in front.
12201 if (const RecordType *RT = T->getAs<RecordType>()) {
12202 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012203
12204 SmallString<16> InsertionText(" ");
12205 InsertionText += RD->getKindName();
12206
Nick Lewycky36722d22013-02-06 05:59:33 +000012207 Diag(TypeRange.getBegin(),
12208 getLangOpts().CPlusPlus11 ?
12209 diag::warn_cxx98_compat_unelaborated_friend_type :
12210 diag::ext_unelaborated_friend_type)
12211 << (unsigned) RD->getTagKind()
12212 << T
12213 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12214 InsertionText);
12215 } else {
12216 Diag(FriendLoc,
12217 getLangOpts().CPlusPlus11 ?
12218 diag::warn_cxx98_compat_nonclass_type_friend :
12219 diag::ext_nonclass_type_friend)
12220 << T
12221 << TypeRange;
12222 }
12223 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012224 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012225 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012226 diag::warn_cxx98_compat_enum_friend :
12227 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012228 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012229 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012230 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012231
Nick Lewycky36722d22013-02-06 05:59:33 +000012232 // C++11 [class.friend]p3:
12233 // A friend declaration that does not declare a function shall have one
12234 // of the following forms:
12235 // friend elaborated-type-specifier ;
12236 // friend simple-type-specifier ;
12237 // friend typename-specifier ;
12238 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12239 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12240 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012241
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012242 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012243 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012244 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012245 return FriendDecl::Create(Context, CurContext,
12246 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12247 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012248}
12249
John McCallace48cd2010-10-19 01:40:49 +000012250/// Handle a friend tag declaration where the scope specifier was
12251/// templated.
12252Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12253 unsigned TagSpec, SourceLocation TagLoc,
12254 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012255 IdentifierInfo *Name,
12256 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012257 AttributeList *Attr,
12258 MultiTemplateParamsArg TempParamLists) {
12259 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12260
12261 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012262 bool Invalid = false;
12263
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012264 if (TemplateParameterList *TemplateParams =
12265 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012266 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012267 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012268 if (TemplateParams->size() > 0) {
12269 // This is a declaration of a class template.
12270 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012271 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012272
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012273 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12274 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012275 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012276 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012277 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012278 } else {
12279 // The "template<>" header is extraneous.
12280 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12281 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12282 isExplicitSpecialization = true;
12283 }
12284 }
12285
Craig Topperc3ec1492014-05-26 06:22:03 +000012286 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012287
John McCallace48cd2010-10-19 01:40:49 +000012288 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012289 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012290 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012291 isAllExplicitSpecializations = false;
12292 break;
12293 }
12294 }
12295
12296 // FIXME: don't ignore attributes.
12297
12298 // If it's explicit specializations all the way down, just forget
12299 // about the template header and build an appropriate non-templated
12300 // friend. TODO: for source fidelity, remember the headers.
12301 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012302 if (SS.isEmpty()) {
12303 bool Owned = false;
12304 bool IsDependent = false;
12305 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012306 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012307 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012308 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012309 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012310 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012311 /*UnderlyingType=*/TypeResult(),
12312 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012313 }
Richard Smith649c7b062014-01-08 00:56:48 +000012314
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012315 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012316 ElaboratedTypeKeyword Keyword
12317 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012318 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012319 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012320 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012321 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012322
12323 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12324 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012325 DependentNameTypeLoc TL =
12326 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012327 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012328 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012329 TL.setNameLoc(NameLoc);
12330 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012331 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012332 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012333 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012334 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012335 }
12336
12337 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012338 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012339 Friend->setAccess(AS_public);
12340 CurContext->addDecl(Friend);
12341 return Friend;
12342 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012343
12344 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12345
12346
John McCallace48cd2010-10-19 01:40:49 +000012347
12348 // Handle the case of a templated-scope friend class. e.g.
12349 // template <class T> class A<T>::B;
12350 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012351 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12352 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012353 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12354 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12355 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012356 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012357 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012358 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012359 TL.setNameLoc(NameLoc);
12360
12361 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012362 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012363 Friend->setAccess(AS_public);
12364 Friend->setUnsupportedFriend(true);
12365 CurContext->addDecl(Friend);
12366 return Friend;
12367}
12368
12369
John McCall11083da2009-09-16 22:47:08 +000012370/// Handle a friend type declaration. This works in tandem with
12371/// ActOnTag.
12372///
12373/// Notes on friend class templates:
12374///
12375/// We generally treat friend class declarations as if they were
12376/// declaring a class. So, for example, the elaborated type specifier
12377/// in a friend declaration is required to obey the restrictions of a
12378/// class-head (i.e. no typedefs in the scope chain), template
12379/// parameters are required to match up with simple template-ids, &c.
12380/// However, unlike when declaring a template specialization, it's
12381/// okay to refer to a template specialization without an empty
12382/// template parameter declaration, e.g.
12383/// friend class A<T>::B<unsigned>;
12384/// We permit this as a special case; if there are any template
12385/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012386/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012387Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012388 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012389 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012390
12391 assert(DS.isFriendSpecified());
12392 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12393
John McCall11083da2009-09-16 22:47:08 +000012394 // Try to convert the decl specifier to a type. This works for
12395 // friend templates because ActOnTag never produces a ClassTemplateDecl
12396 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012397 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012398 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12399 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012400 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012401 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012402
Douglas Gregor6c110f32010-12-16 01:14:37 +000012403 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012404 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012405
John McCall11083da2009-09-16 22:47:08 +000012406 // This is definitely an error in C++98. It's probably meant to
12407 // be forbidden in C++0x, too, but the specification is just
12408 // poorly written.
12409 //
12410 // The problem is with declarations like the following:
12411 // template <T> friend A<T>::foo;
12412 // where deciding whether a class C is a friend or not now hinges
12413 // on whether there exists an instantiation of A that causes
12414 // 'foo' to equal C. There are restrictions on class-heads
12415 // (which we declare (by fiat) elaborated friend declarations to
12416 // be) that makes this tractable.
12417 //
12418 // FIXME: handle "template <> friend class A<T>;", which
12419 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012420 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012421 Diag(Loc, diag::err_tagless_friend_type_template)
12422 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012423 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012424 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012425
John McCallaa74a0c2009-08-28 07:59:38 +000012426 // C++98 [class.friend]p1: A friend of a class is a function
12427 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012428 // This is fixed in DR77, which just barely didn't make the C++03
12429 // deadline. It's also a very silly restriction that seriously
12430 // affects inner classes and which nobody else seems to implement;
12431 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012432 //
12433 // But note that we could warn about it: it's always useless to
12434 // friend one of your own members (it's not, however, worthless to
12435 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012436
John McCall11083da2009-09-16 22:47:08 +000012437 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012438 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012439 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012440 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012441 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012442 TSI,
John McCall11083da2009-09-16 22:47:08 +000012443 DS.getFriendSpecLoc());
12444 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012445 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012446
12447 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012448 return nullptr;
12449
John McCall11083da2009-09-16 22:47:08 +000012450 D->setAccess(AS_public);
12451 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012452
John McCall48871652010-08-21 09:40:31 +000012453 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012454}
12455
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012456NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12457 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012458 const DeclSpec &DS = D.getDeclSpec();
12459
12460 assert(DS.isFriendSpecified());
12461 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12462
12463 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012464 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012465
12466 // C++ [class.friend]p1
12467 // A friend of a class is a function or class....
12468 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012469 // It *doesn't* see through dependent types, which is correct
12470 // according to [temp.arg.type]p3:
12471 // If a declaration acquires a function type through a
12472 // type dependent on a template-parameter and this causes
12473 // a declaration that does not use the syntactic form of a
12474 // function declarator to have a function type, the program
12475 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012476 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012477 Diag(Loc, diag::err_unexpected_friend);
12478
12479 // It might be worthwhile to try to recover by creating an
12480 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012481 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012482 }
12483
12484 // C++ [namespace.memdef]p3
12485 // - If a friend declaration in a non-local class first declares a
12486 // class or function, the friend class or function is a member
12487 // of the innermost enclosing namespace.
12488 // - The name of the friend is not found by simple name lookup
12489 // until a matching declaration is provided in that namespace
12490 // scope (either before or after the class declaration granting
12491 // friendship).
12492 // - If a friend function is called, its name may be found by the
12493 // name lookup that considers functions from namespaces and
12494 // classes associated with the types of the function arguments.
12495 // - When looking for a prior declaration of a class or a function
12496 // declared as a friend, scopes outside the innermost enclosing
12497 // namespace scope are not considered.
12498
John McCallde3fd222010-10-12 23:13:28 +000012499 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012500 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12501 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012502 assert(Name);
12503
Douglas Gregor6c110f32010-12-16 01:14:37 +000012504 // Check for unexpanded parameter packs.
12505 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12506 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12507 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012508 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012509
John McCall07e91c02009-08-06 02:15:43 +000012510 // The context we found the declaration in, or in which we should
12511 // create the declaration.
12512 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012513 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012514 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012515 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012516
Richard Smith114394f2013-08-09 04:35:01 +000012517 // There are five cases here.
12518 // - There's no scope specifier and we're in a local class. Only look
12519 // for functions declared in the immediately-enclosing block scope.
12520 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012521 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012522 if ((SS.isInvalid() || !SS.isSet()) &&
12523 (FunctionContainingLocalClass =
12524 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12525 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012526 // If a friend declaration appears in a local class and the name
12527 // specified is an unqualified name, a prior declaration is
12528 // looked up without considering scopes that are outside the
12529 // innermost enclosing non-class scope. For a friend function
12530 // declaration, if there is no prior declaration, the program is
12531 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012532
12533 // Find the innermost enclosing non-class scope. This is the block
12534 // scope containing the local class definition (or for a nested class,
12535 // the outer local class).
12536 DCScope = S->getFnParent();
12537
12538 // Look up the function name in the scope.
12539 Previous.clear(LookupLocalFriendName);
12540 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12541
12542 if (!Previous.empty()) {
12543 // All possible previous declarations must have the same context:
12544 // either they were declared at block scope or they are members of
12545 // one of the enclosing local classes.
12546 DC = Previous.getRepresentativeDecl()->getDeclContext();
12547 } else {
12548 // This is ill-formed, but provide the context that we would have
12549 // declared the function in, if we were permitted to, for error recovery.
12550 DC = FunctionContainingLocalClass;
12551 }
Richard Smith541b38b2013-09-20 01:15:31 +000012552 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012553
12554 // C++ [class.friend]p6:
12555 // A function can be defined in a friend declaration of a class if and
12556 // only if the class is a non-local class (9.8), the function name is
12557 // unqualified, and the function has namespace scope.
12558 if (D.isFunctionDefinition()) {
12559 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12560 }
12561
12562 // - There's no scope specifier, in which case we just go to the
12563 // appropriate scope and look for a function or function template
12564 // there as appropriate.
12565 } else if (SS.isInvalid() || !SS.isSet()) {
12566 // C++11 [namespace.memdef]p3:
12567 // If the name in a friend declaration is neither qualified nor
12568 // a template-id and the declaration is a function or an
12569 // elaborated-type-specifier, the lookup to determine whether
12570 // the entity has been previously declared shall not consider
12571 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012572 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012573
John McCallf7cfb222010-10-13 05:45:15 +000012574 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012575 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012576
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012577 // Skip class contexts. If someone can cite chapter and verse
12578 // for this behavior, that would be nice --- it's what GCC and
12579 // EDG do, and it seems like a reasonable intent, but the spec
12580 // really only says that checks for unqualified existing
12581 // declarations should stop at the nearest enclosing namespace,
12582 // not that they should only consider the nearest enclosing
12583 // namespace.
12584 while (DC->isRecord())
12585 DC = DC->getParent();
12586
12587 DeclContext *LookupDC = DC;
12588 while (LookupDC->isTransparentContext())
12589 LookupDC = LookupDC->getParent();
12590
12591 while (true) {
12592 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012593
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012594 if (!Previous.empty()) {
12595 DC = LookupDC;
12596 break;
John McCallf4776592010-10-14 22:22:28 +000012597 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012598
12599 if (isTemplateId) {
12600 if (isa<TranslationUnitDecl>(LookupDC)) break;
12601 } else {
12602 if (LookupDC->isFileContext()) break;
12603 }
12604 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012605 }
12606
John McCallccbc0322010-10-13 06:22:15 +000012607 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012608
John McCallde3fd222010-10-12 23:13:28 +000012609 // - There's a non-dependent scope specifier, in which case we
12610 // compute it and do a previous lookup there for a function
12611 // or function template.
12612 } else if (!SS.getScopeRep()->isDependent()) {
12613 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012614 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012615
Craig Topperc3ec1492014-05-26 06:22:03 +000012616 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012617
12618 LookupQualifiedName(Previous, DC);
12619
12620 // Ignore things found implicitly in the wrong scope.
12621 // TODO: better diagnostics for this case. Suggesting the right
12622 // qualified scope would be nice...
12623 LookupResult::Filter F = Previous.makeFilter();
12624 while (F.hasNext()) {
12625 NamedDecl *D = F.next();
12626 if (!DC->InEnclosingNamespaceSetOf(
12627 D->getDeclContext()->getRedeclContext()))
12628 F.erase();
12629 }
12630 F.done();
12631
12632 if (Previous.empty()) {
12633 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012634 Diag(Loc, diag::err_qualified_friend_not_found)
12635 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012636 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012637 }
12638
12639 // C++ [class.friend]p1: A friend of a class is a function or
12640 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012641 if (DC->Equals(CurContext))
12642 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012643 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012644 diag::warn_cxx98_compat_friend_is_member :
12645 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012646
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012647 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012648 // C++ [class.friend]p6:
12649 // A function can be defined in a friend declaration of a class if and
12650 // only if the class is a non-local class (9.8), the function name is
12651 // unqualified, and the function has namespace scope.
12652 SemaDiagnosticBuilder DB
12653 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12654
12655 DB << SS.getScopeRep();
12656 if (DC->isFileContext())
12657 DB << FixItHint::CreateRemoval(SS.getRange());
12658 SS.clear();
12659 }
John McCallde3fd222010-10-12 23:13:28 +000012660
12661 // - There's a scope specifier that does not match any template
12662 // parameter lists, in which case we use some arbitrary context,
12663 // create a method or method template, and wait for instantiation.
12664 // - There's a scope specifier that does match some template
12665 // parameter lists, which we don't handle right now.
12666 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012667 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012668 // C++ [class.friend]p6:
12669 // A function can be defined in a friend declaration of a class if and
12670 // only if the class is a non-local class (9.8), the function name is
12671 // unqualified, and the function has namespace scope.
12672 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12673 << SS.getScopeRep();
12674 }
12675
John McCallde3fd222010-10-12 23:13:28 +000012676 DC = CurContext;
12677 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012678 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012679
John McCallf7cfb222010-10-13 05:45:15 +000012680 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012681 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012682 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12683 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12684 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012685 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012686 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12687 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012688 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012689 }
John McCall07e91c02009-08-06 02:15:43 +000012690 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012691
Douglas Gregordd847ba2011-11-03 16:37:14 +000012692 // FIXME: This is an egregious hack to cope with cases where the scope stack
12693 // does not contain the declaration context, i.e., in an out-of-line
12694 // definition of a class.
12695 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12696 if (!DCScope) {
12697 FakeDCScope.setEntity(DC);
12698 DCScope = &FakeDCScope;
12699 }
Richard Smith114394f2013-08-09 04:35:01 +000012700
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012701 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012702 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012703 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012704 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012705
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012706 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012707
Richard Smith114394f2013-08-09 04:35:01 +000012708 // If we performed typo correction, we might have added a scope specifier
12709 // and changed the decl context.
12710 DC = ND->getDeclContext();
12711
John McCall759e32b2009-08-31 22:39:49 +000012712 // Add the function declaration to the appropriate lookup tables,
12713 // adjusting the redeclarations list as necessary. We don't
12714 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012715 //
John McCall759e32b2009-08-31 22:39:49 +000012716 // Also update the scope-based lookup if the target context's
12717 // lookup context is in lexical scope.
12718 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012719 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012720 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012721 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012722 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012723 }
John McCallaa74a0c2009-08-28 07:59:38 +000012724
12725 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012726 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012727 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012728 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012729 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012730
John McCalla0a96892012-08-10 03:15:35 +000012731 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012732 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012733 } else {
12734 if (DC->isRecord()) CheckFriendAccess(ND);
12735
John McCall2c2eb122010-10-16 06:59:13 +000012736 FunctionDecl *FD;
12737 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12738 FD = FTD->getTemplatedDecl();
12739 else
12740 FD = cast<FunctionDecl>(ND);
12741
David Majnemer502b0ed2013-06-25 23:09:30 +000012742 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12743 // default argument expression, that declaration shall be a definition
12744 // and shall be the only declaration of the function or function
12745 // template in the translation unit.
12746 if (functionDeclHasDefaultArgument(FD)) {
12747 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12748 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12749 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12750 } else if (!D.isFunctionDefinition())
12751 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12752 }
12753
John McCall2c2eb122010-10-16 06:59:13 +000012754 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012755 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12756 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12757 << SS.getScopeRep() << SS.getRange()
12758 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012759 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012760 }
John McCall2c2eb122010-10-16 06:59:13 +000012761 }
John McCallde3fd222010-10-12 23:13:28 +000012762
John McCall48871652010-08-21 09:40:31 +000012763 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012764}
12765
John McCall48871652010-08-21 09:40:31 +000012766void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12767 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012768
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012769 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012770 if (!Fn) {
12771 Diag(DelLoc, diag::err_deleted_non_function);
12772 return;
12773 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012774
Douglas Gregorec9fd132012-01-14 16:38:05 +000012775 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012776 // Don't consider the implicit declaration we generate for explicit
12777 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012778 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12779 Prev->getPreviousDecl()) &&
12780 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012781 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012782 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12783 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12784 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012785 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012786 // If the declaration wasn't the first, we delete the function anyway for
12787 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012788 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012789 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012790
Nico Rieck9de0a572014-05-29 16:51:19 +000012791 // dllimport/dllexport cannot be deleted.
12792 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12793 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12794 Fn->setInvalidDecl();
12795 }
12796
Richard Smithb4d2a152013-04-02 19:38:47 +000012797 if (Fn->isDeleted())
12798 return;
12799
12800 // See if we're deleting a function which is already known to override a
12801 // non-deleted virtual function.
12802 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12803 bool IssuedDiagnostic = false;
12804 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12805 E = MD->end_overridden_methods();
12806 I != E; ++I) {
12807 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12808 if (!IssuedDiagnostic) {
12809 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12810 IssuedDiagnostic = true;
12811 }
12812 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12813 }
12814 }
12815 }
12816
Richard Smithb63b6ee2014-01-22 01:43:19 +000012817 // C++11 [basic.start.main]p3:
12818 // A program that defines main as deleted [...] is ill-formed.
12819 if (Fn->isMain())
12820 Diag(DelLoc, diag::err_deleted_main);
12821
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012822 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012823}
Sebastian Redl4c018662009-04-27 21:33:24 +000012824
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012825void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012826 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012827
12828 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012829 if (MD->getParent()->isDependentType()) {
12830 MD->setDefaulted();
12831 MD->setExplicitlyDefaulted();
12832 return;
12833 }
12834
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012835 CXXSpecialMember Member = getSpecialMember(MD);
12836 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012837 if (!MD->isInvalidDecl())
12838 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012839 return;
12840 }
12841
12842 MD->setDefaulted();
12843 MD->setExplicitlyDefaulted();
12844
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012845 // If this definition appears within the record, do the checking when
12846 // the record is complete.
12847 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012848 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012849 // Find the uninstantiated declaration that actually had the '= default'
12850 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012851 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012852
Richard Smith3901dfe2013-03-27 00:22:47 +000012853 // If the method was defaulted on its first declaration, we will have
12854 // already performed the checking in CheckCompletedCXXClass. Such a
12855 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012856 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012857 return;
12858
Richard Smithd3b5c9082012-07-27 04:22:15 +000012859 CheckExplicitlyDefaultedSpecialMember(MD);
12860
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012861 if (MD->isInvalidDecl())
12862 return;
12863
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012864 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012865 case CXXDefaultConstructor:
12866 DefineImplicitDefaultConstructor(DefaultLoc,
12867 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012868 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012869 case CXXCopyConstructor:
12870 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012871 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012872 case CXXCopyAssignment:
12873 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012874 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012875 case CXXDestructor:
12876 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012877 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012878 case CXXMoveConstructor:
12879 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012880 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012881 case CXXMoveAssignment:
12882 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012883 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012884 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012885 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012886 }
12887 } else {
12888 Diag(DefaultLoc, diag::err_default_special_members);
12889 }
12890}
12891
Sebastian Redl4c018662009-04-27 21:33:24 +000012892static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012893 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012894 Stmt *SubStmt = *CI;
12895 if (!SubStmt)
12896 continue;
12897 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012898 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012899 diag::err_return_in_constructor_handler);
12900 if (!isa<Expr>(SubStmt))
12901 SearchForReturnInStmt(Self, SubStmt);
12902 }
12903}
12904
12905void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12906 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12907 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12908 SearchForReturnInStmt(*this, Handler);
12909 }
12910}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012911
David Blaikie68f71a32013-01-18 23:03:15 +000012912bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012913 const CXXMethodDecl *Old) {
12914 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12915 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12916
12917 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12918
12919 // If the calling conventions match, everything is fine
12920 if (NewCC == OldCC)
12921 return false;
12922
Hans Wennborg2545efe2013-12-11 17:42:11 +000012923 // If the calling conventions mismatch because the new function is static,
12924 // suppress the calling convention mismatch error; the error about static
12925 // function override (err_static_overrides_virtual from
12926 // Sema::CheckFunctionDeclaration) is more clear.
12927 if (New->getStorageClass() == SC_Static)
12928 return false;
12929
Reid Kleckner78af0702013-08-27 23:08:25 +000012930 Diag(New->getLocation(),
12931 diag::err_conflicting_overriding_cc_attributes)
12932 << New->getDeclName() << New->getType() << Old->getType();
12933 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12934 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012935}
12936
Mike Stump11289f42009-09-09 15:08:12 +000012937bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012938 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012939 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12940 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012941
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012942 if (Context.hasSameType(NewTy, OldTy) ||
12943 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012944 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012945
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012946 // Check if the return types are covariant
12947 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012948
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012949 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012950 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12951 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012952 NewClassTy = NewPT->getPointeeType();
12953 OldClassTy = OldPT->getPointeeType();
12954 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012955 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12956 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12957 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12958 NewClassTy = NewRT->getPointeeType();
12959 OldClassTy = OldRT->getPointeeType();
12960 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012961 }
12962 }
Mike Stump11289f42009-09-09 15:08:12 +000012963
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012964 // The return types aren't either both pointers or references to a class type.
12965 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012966 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012967 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012968 << New->getDeclName() << NewTy << OldTy
12969 << New->getReturnTypeSourceRange();
12970 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12971 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012972
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012973 return true;
12974 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012975
Anders Carlssone60365b2009-12-31 18:34:24 +000012976 // C++ [class.virtual]p6:
12977 // If the return type of D::f differs from the return type of B::f, the
12978 // class type in the return type of D::f shall be complete at the point of
12979 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012980 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12981 if (!RT->isBeingDefined() &&
12982 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012983 diag::err_covariant_return_incomplete,
12984 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012985 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012986 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012987
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012988 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012989 // Check if the new class derives from the old class.
12990 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012991 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12992 << New->getDeclName() << NewTy << OldTy
12993 << New->getReturnTypeSourceRange();
12994 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12995 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012996 return true;
12997 }
Mike Stump11289f42009-09-09 15:08:12 +000012998
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012999 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013000 if (CheckDerivedToBaseConversion(
13001 NewClassTy, OldClassTy,
13002 diag::err_covariant_return_inaccessible_base,
13003 diag::err_covariant_return_ambiguous_derived_to_base_conv,
13004 New->getLocation(), New->getReturnTypeSourceRange(),
13005 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000013006 // FIXME: this note won't trigger for delayed access control
13007 // diagnostics, and it's impossible to get an undelayed error
13008 // here from access control during the original parse because
13009 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013010 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13011 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013012 return true;
13013 }
13014 }
Mike Stump11289f42009-09-09 15:08:12 +000013015
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013016 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013017 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013018 Diag(New->getLocation(),
13019 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013020 << New->getDeclName() << NewTy << OldTy
13021 << New->getReturnTypeSourceRange();
13022 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13023 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013024 return true;
13025 };
Mike Stump11289f42009-09-09 15:08:12 +000013026
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013027
13028 // The new class type must have the same or less qualifiers as the old type.
13029 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13030 Diag(New->getLocation(),
13031 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013032 << New->getDeclName() << NewTy << OldTy
13033 << New->getReturnTypeSourceRange();
13034 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13035 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013036 return true;
13037 };
Mike Stump11289f42009-09-09 15:08:12 +000013038
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013039 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013040}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013041
Douglas Gregor21920e372009-12-01 17:24:26 +000013042/// \brief Mark the given method pure.
13043///
13044/// \param Method the method to be marked pure.
13045///
13046/// \param InitRange the source range that covers the "0" initializer.
13047bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013048 SourceLocation EndLoc = InitRange.getEnd();
13049 if (EndLoc.isValid())
13050 Method->setRangeEnd(EndLoc);
13051
Douglas Gregor21920e372009-12-01 17:24:26 +000013052 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13053 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000013054 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013055 }
Douglas Gregor21920e372009-12-01 17:24:26 +000013056
13057 if (!Method->isInvalidDecl())
13058 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13059 << Method->getDeclName() << InitRange;
13060 return true;
13061}
13062
Douglas Gregor926410d2012-02-21 02:22:07 +000013063/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013064static bool isStaticDataMember(const Decl *D) {
13065 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13066 return Var->isStaticDataMember();
13067
13068 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000013069}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013070
John McCall1f4ee7b2009-12-19 09:28:58 +000013071/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13072/// an initializer for the out-of-line declaration 'Dcl'. The scope
13073/// is a fresh scope pushed for just this purpose.
13074///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013075/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13076/// static data member of class X, names should be looked up in the scope of
13077/// class X.
John McCall48871652010-08-21 09:40:31 +000013078void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013079 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013080 if (!D || D->isInvalidDecl())
13081 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013082
Richard Smitha2302242013-12-05 07:51:02 +000013083 // We will always have a nested name specifier here, but this declaration
13084 // might not be out of line if the specifier names the current namespace:
13085 // extern int n;
13086 // int ::n = 0;
13087 if (D->isOutOfLine())
13088 EnterDeclaratorContext(S, D->getDeclContext());
13089
Douglas Gregor926410d2012-02-21 02:22:07 +000013090 // If we are parsing the initializer for a static data member, push a
13091 // new expression evaluation context that is associated with this static
13092 // data member.
13093 if (isStaticDataMember(D))
13094 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013095}
13096
13097/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013098/// initializer for the out-of-line declaration 'D'.
13099void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013100 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013101 if (!D || D->isInvalidDecl())
13102 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013103
Douglas Gregor926410d2012-02-21 02:22:07 +000013104 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013105 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013106
Richard Smitha2302242013-12-05 07:51:02 +000013107 if (D->isOutOfLine())
13108 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013109}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013110
13111/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13112/// C++ if/switch/while/for statement.
13113/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013114DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013115 // C++ 6.4p2:
13116 // The declarator shall not specify a function or an array.
13117 // The type-specifier-seq shall not contain typedef and shall not declare a
13118 // new class or enumeration.
13119 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13120 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013121
13122 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013123 if (!Dcl)
13124 return true;
13125
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013126 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13127 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013128 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013129 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013130 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013131
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013132 return Dcl;
13133}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013134
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013135void Sema::LoadExternalVTableUses() {
13136 if (!ExternalSource)
13137 return;
13138
13139 SmallVector<ExternalVTableUse, 4> VTables;
13140 ExternalSource->ReadUsedVTables(VTables);
13141 SmallVector<VTableUse, 4> NewUses;
13142 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13143 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13144 = VTablesUsed.find(VTables[I].Record);
13145 // Even if a definition wasn't required before, it may be required now.
13146 if (Pos != VTablesUsed.end()) {
13147 if (!Pos->second && VTables[I].DefinitionRequired)
13148 Pos->second = true;
13149 continue;
13150 }
13151
13152 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13153 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13154 }
13155
13156 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13157}
13158
Douglas Gregor88d292c2010-05-13 16:44:06 +000013159void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13160 bool DefinitionRequired) {
13161 // Ignore any vtable uses in unevaluated operands or for classes that do
13162 // not have a vtable.
13163 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013164 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013165 return;
13166
Douglas Gregor88d292c2010-05-13 16:44:06 +000013167 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013168 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013169 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13170 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13171 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13172 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013173 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013174 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013175 // list, since we may have already processed the first entry.
13176 if (DefinitionRequired && !Pos.first->second) {
13177 Pos.first->second = true;
13178 } else {
13179 // Otherwise, we can early exit.
13180 return;
13181 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013182 } else {
13183 // The Microsoft ABI requires that we perform the destructor body
13184 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13185 // the deleting destructor is emitted with the vtable, not with the
13186 // destructor definition as in the Itanium ABI.
13187 // If it has a definition, we do the check at that point instead.
13188 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13189 Class->hasUserDeclaredDestructor() &&
13190 !Class->getDestructor()->isDefined() &&
13191 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013192 CXXDestructorDecl *DD = Class->getDestructor();
13193 ContextRAII SavedContext(*this, DD);
13194 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013195 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013196 }
13197
13198 // Local classes need to have their virtual members marked
13199 // immediately. For all other classes, we mark their virtual members
13200 // at the end of the translation unit.
13201 if (Class->isLocalClass())
13202 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013203 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013204 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013205}
13206
Douglas Gregor88d292c2010-05-13 16:44:06 +000013207bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013208 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013209 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013210 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013211
Douglas Gregor88d292c2010-05-13 16:44:06 +000013212 // Note: The VTableUses vector could grow as a result of marking
13213 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013214 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013215 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013216 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013217 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013218 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013219 if (!Class)
13220 continue;
13221
13222 SourceLocation Loc = VTableUses[I].second;
13223
Richard Smithd3b5c9082012-07-27 04:22:15 +000013224 bool DefineVTable = true;
13225
Douglas Gregor88d292c2010-05-13 16:44:06 +000013226 // If this class has a key function, but that key function is
13227 // defined in another translation unit, we don't need to emit the
13228 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013229 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013230 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013231 // The key function is in another translation unit.
13232 DefineVTable = false;
13233 TemplateSpecializationKind TSK =
13234 KeyFunction->getTemplateSpecializationKind();
13235 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13236 TSK != TSK_ImplicitInstantiation &&
13237 "Instantiations don't have key functions");
13238 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013239 } else if (!KeyFunction) {
13240 // If we have a class with no key function that is the subject
13241 // of an explicit instantiation declaration, suppress the
13242 // vtable; it will live with the explicit instantiation
13243 // definition.
13244 bool IsExplicitInstantiationDeclaration
13245 = Class->getTemplateSpecializationKind()
13246 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013247 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013248 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013249 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013250 if (TSK == TSK_ExplicitInstantiationDeclaration)
13251 IsExplicitInstantiationDeclaration = true;
13252 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13253 IsExplicitInstantiationDeclaration = false;
13254 break;
13255 }
13256 }
13257
13258 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013259 DefineVTable = false;
13260 }
13261
13262 // The exception specifications for all virtual members may be needed even
13263 // if we are not providing an authoritative form of the vtable in this TU.
13264 // We may choose to emit it available_externally anyway.
13265 if (!DefineVTable) {
13266 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13267 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013268 }
13269
13270 // Mark all of the virtual members of this class as referenced, so
13271 // that we can build a vtable. Then, tell the AST consumer that a
13272 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013273 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013274 MarkVirtualMembersReferenced(Loc, Class);
13275 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013276 if (VTablesUsed[Canonical])
13277 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013278
13279 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013280 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013281 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013282 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013283 if (!KeyFunction ||
13284 (KeyFunction->hasBody(KeyFunctionDef) &&
13285 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013286 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13287 TSK_ExplicitInstantiationDefinition
13288 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13289 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013290 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013291 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013292 VTableUses.clear();
13293
Douglas Gregor97509692011-04-22 22:25:37 +000013294 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013295}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013296
Richard Smithd3b5c9082012-07-27 04:22:15 +000013297void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13298 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013299 for (const auto *I : RD->methods())
13300 if (I->isVirtual() && !I->isPure())
13301 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013302}
13303
Rafael Espindola5b334082010-03-26 00:36:59 +000013304void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13305 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013306 // Mark all functions which will appear in RD's vtable as used.
13307 CXXFinalOverriderMap FinalOverriders;
13308 RD->getFinalOverriders(FinalOverriders);
13309 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13310 E = FinalOverriders.end();
13311 I != E; ++I) {
13312 for (OverridingMethods::const_iterator OI = I->second.begin(),
13313 OE = I->second.end();
13314 OI != OE; ++OI) {
13315 assert(OI->second.size() > 0 && "no final overrider");
13316 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013317
Richard Smith4ff9ff92012-07-07 06:59:51 +000013318 // C++ [basic.def.odr]p2:
13319 // [...] A virtual member function is used if it is not pure. [...]
13320 if (!Overrider->isPure())
13321 MarkFunctionReferenced(Loc, Overrider);
13322 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013323 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013324
13325 // Only classes that have virtual bases need a VTT.
13326 if (RD->getNumVBases() == 0)
13327 return;
13328
Aaron Ballman574705e2014-03-13 15:41:46 +000013329 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013330 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013331 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013332 if (Base->getNumVBases() == 0)
13333 continue;
13334 MarkVirtualMembersReferenced(Loc, Base);
13335 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013336}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013337
13338/// SetIvarInitializers - This routine builds initialization ASTs for the
13339/// Objective-C implementation whose ivars need be initialized.
13340void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013341 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013342 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013343 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013344 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013345 CollectIvarsToConstructOrDestruct(OID, ivars);
13346 if (ivars.empty())
13347 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013348 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013349 for (unsigned i = 0; i < ivars.size(); i++) {
13350 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013351 if (Field->isInvalidDecl())
13352 continue;
13353
Alexis Hunt1d792652011-01-08 20:30:50 +000013354 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013355 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13356 InitializationKind InitKind =
13357 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013358
13359 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13360 ExprResult MemberInit =
13361 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013362 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013363 // Note, MemberInit could actually come back empty if no initialization
13364 // is required (e.g., because it would call a trivial default constructor)
13365 if (!MemberInit.get() || MemberInit.isInvalid())
13366 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013367
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013368 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013369 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13370 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013371 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013372 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013373 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013374
13375 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013376 if (const RecordType *RecordTy =
13377 Context.getBaseElementType(Field->getType())
13378 ->getAs<RecordType>()) {
13379 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013380 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013381 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013382 CheckDestructorAccess(Field->getLocation(), Destructor,
13383 PDiag(diag::err_access_dtor_ivar)
13384 << Context.getBaseElementType(Field->getType()));
13385 }
13386 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013387 }
13388 ObjCImplementation->setIvarInitializers(Context,
13389 AllToInit.data(), AllToInit.size());
13390 }
13391}
Alexis Hunt6118d662011-05-04 05:57:24 +000013392
Alexis Hunt27a761d2011-05-04 23:29:54 +000013393static
13394void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13395 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13396 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13397 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13398 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013399 if (Ctor->isInvalidDecl())
13400 return;
13401
Richard Smith802c4b72012-08-23 06:16:52 +000013402 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13403
13404 // Target may not be determinable yet, for instance if this is a dependent
13405 // call in an uninstantiated template.
13406 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013407 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013408 (void)Target->hasBody(FNTarget);
13409 Target = const_cast<CXXConstructorDecl*>(
13410 cast_or_null<CXXConstructorDecl>(FNTarget));
13411 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013412
13413 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13414 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013415 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013416
David Blaikie82e95a32014-11-19 07:49:47 +000013417 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013418 return;
13419
13420 // We know that beyond here, we aren't chaining into a cycle.
13421 if (!Target || !Target->isDelegatingConstructor() ||
13422 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013423 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013424 Current.clear();
13425 // We've hit a cycle.
13426 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13427 Current.count(TCanonical)) {
13428 // If we haven't diagnosed this cycle yet, do so now.
13429 if (!Invalid.count(TCanonical)) {
13430 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013431 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013432 << Ctor;
13433
Richard Smith802c4b72012-08-23 06:16:52 +000013434 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013435 if (TCanonical != Canonical)
13436 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13437
13438 CXXConstructorDecl *C = Target;
13439 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013440 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013441 (void)C->getTargetConstructor()->hasBody(FNTarget);
13442 assert(FNTarget && "Ctor cycle through bodiless function");
13443
Richard Smith802c4b72012-08-23 06:16:52 +000013444 C = const_cast<CXXConstructorDecl*>(
13445 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013446 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13447 }
13448 }
13449
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013450 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013451 Current.clear();
13452 } else {
13453 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13454 }
13455}
13456
13457
Alexis Hunt6118d662011-05-04 05:57:24 +000013458void Sema::CheckDelegatingCtorCycles() {
13459 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13460
Douglas Gregorbae31202011-07-27 21:57:17 +000013461 for (DelegatingCtorDeclsType::iterator
13462 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013463 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013464 I != E; ++I)
13465 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013466
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013467 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13468 CE = Invalid.end();
13469 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013470 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013471}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013472
Douglas Gregor3024f072012-04-16 07:05:22 +000013473namespace {
13474 /// \brief AST visitor that finds references to the 'this' expression.
13475 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13476 Sema &S;
13477
13478 public:
13479 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13480
13481 bool VisitCXXThisExpr(CXXThisExpr *E) {
13482 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13483 << E->isImplicit();
13484 return false;
13485 }
13486 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013487}
Douglas Gregor3024f072012-04-16 07:05:22 +000013488
13489bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13490 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13491 if (!TSInfo)
13492 return false;
13493
13494 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013495 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013496 if (!ProtoTL)
13497 return false;
13498
13499 // C++11 [expr.prim.general]p3:
13500 // [The expression this] shall not appear before the optional
13501 // cv-qualifier-seq and it shall not appear within the declaration of a
13502 // static member function (although its type and value category are defined
13503 // within a static member function as they are within a non-static member
13504 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013505 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013506 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013507 FindCXXThisExpr Finder(*this);
13508
13509 // If the return type came after the cv-qualifier-seq, check it now.
13510 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013511 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013512 return true;
13513
13514 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013515 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13516 return true;
13517
13518 return checkThisInStaticMemberFunctionAttributes(Method);
13519}
13520
13521bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13522 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13523 if (!TSInfo)
13524 return false;
13525
13526 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013527 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013528 if (!ProtoTL)
13529 return false;
13530
David Blaikie6adc78e2013-02-18 22:06:02 +000013531 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013532 FindCXXThisExpr Finder(*this);
13533
Douglas Gregor3024f072012-04-16 07:05:22 +000013534 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013535 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013536 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013537 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013538 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013539 case EST_DynamicNone:
13540 case EST_MSAny:
13541 case EST_None:
13542 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013543
Douglas Gregor3024f072012-04-16 07:05:22 +000013544 case EST_ComputedNoexcept:
13545 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13546 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013547
Douglas Gregor3024f072012-04-16 07:05:22 +000013548 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013549 for (const auto &E : Proto->exceptions()) {
13550 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013551 return true;
13552 }
13553 break;
13554 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013555
13556 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013557}
13558
13559bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13560 FindCXXThisExpr Finder(*this);
13561
13562 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013563 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013564 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013565 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013566 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013567 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013568 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013569 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013570 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013571 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013572 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013573 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013574 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013575 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013576 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013577 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013578 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013579 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013580 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013581 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013582 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013583 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013584 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013585 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013586 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013587 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013588 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013589 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013590 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013591 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013592 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013593
13594 if (Arg && !Finder.TraverseStmt(Arg))
13595 return true;
13596
13597 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13598 if (!Finder.TraverseStmt(Args[I]))
13599 return true;
13600 }
13601 }
13602
13603 return false;
13604}
13605
Richard Smith2e321552014-11-12 02:00:47 +000013606void Sema::checkExceptionSpecification(
13607 bool IsTopLevel, ExceptionSpecificationType EST,
13608 ArrayRef<ParsedType> DynamicExceptions,
13609 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13610 SmallVectorImpl<QualType> &Exceptions,
13611 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013612 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013613 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013614 if (EST == EST_Dynamic) {
13615 Exceptions.reserve(DynamicExceptions.size());
13616 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13617 // FIXME: Preserve type source info.
13618 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13619
Richard Smith2e321552014-11-12 02:00:47 +000013620 if (IsTopLevel) {
13621 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13622 collectUnexpandedParameterPacks(ET, Unexpanded);
13623 if (!Unexpanded.empty()) {
13624 DiagnoseUnexpandedParameterPacks(
13625 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13626 Unexpanded);
13627 continue;
13628 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013629 }
13630
13631 // Check that the type is valid for an exception spec, and
13632 // drop it if not.
13633 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13634 Exceptions.push_back(ET);
13635 }
Richard Smith8acb4282014-07-31 21:57:55 +000013636 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013637 return;
13638 }
Richard Smith8acb4282014-07-31 21:57:55 +000013639
Douglas Gregor433e0532012-04-16 18:27:27 +000013640 if (EST == EST_ComputedNoexcept) {
13641 // If an error occurred, there's no expression here.
13642 if (NoexceptExpr) {
13643 assert((NoexceptExpr->isTypeDependent() ||
13644 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13645 Context.BoolTy) &&
13646 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013647 if (IsTopLevel && NoexceptExpr &&
13648 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013649 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013650 return;
13651 }
Richard Smith8acb4282014-07-31 21:57:55 +000013652
Douglas Gregor433e0532012-04-16 18:27:27 +000013653 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013654 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013655 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013656 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013657 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013658 }
13659 return;
13660 }
13661}
13662
Richard Smith0b3a4622014-11-13 20:01:57 +000013663void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13664 ExceptionSpecificationType EST,
13665 SourceRange SpecificationRange,
13666 ArrayRef<ParsedType> DynamicExceptions,
13667 ArrayRef<SourceRange> DynamicExceptionRanges,
13668 Expr *NoexceptExpr) {
13669 if (!MethodD)
13670 return;
13671
13672 // Dig out the method we're referring to.
13673 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13674 MethodD = FunTmpl->getTemplatedDecl();
13675
13676 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13677 if (!Method)
13678 return;
13679
13680 // Check the exception specification.
13681 llvm::SmallVector<QualType, 4> Exceptions;
13682 FunctionProtoType::ExceptionSpecInfo ESI;
13683 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13684 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13685 ESI);
13686
13687 // Update the exception specification on the function type.
13688 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13689
13690 if (Method->isStatic())
13691 checkThisInStaticMemberFunctionExceptionSpec(Method);
13692
13693 if (Method->isVirtual()) {
13694 // Check overrides, which we previously had to delay.
13695 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13696 OEnd = Method->end_overridden_methods();
13697 O != OEnd; ++O)
13698 CheckOverridingFunctionExceptionSpec(Method, *O);
13699 }
13700}
13701
John McCall5e77d762013-04-16 07:28:30 +000013702/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13703///
13704MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13705 SourceLocation DeclStart,
13706 Declarator &D, Expr *BitWidth,
13707 InClassInitStyle InitStyle,
13708 AccessSpecifier AS,
13709 AttributeList *MSPropertyAttr) {
13710 IdentifierInfo *II = D.getIdentifier();
13711 if (!II) {
13712 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013713 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013714 }
13715 SourceLocation Loc = D.getIdentifierLoc();
13716
13717 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13718 QualType T = TInfo->getType();
13719 if (getLangOpts().CPlusPlus) {
13720 CheckExtraCXXDefaultArguments(D);
13721
13722 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13723 UPPC_DataMemberType)) {
13724 D.setInvalidType();
13725 T = Context.IntTy;
13726 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13727 }
13728 }
13729
13730 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13731
13732 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13733 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13734 diag::err_invalid_thread)
13735 << DeclSpec::getSpecifierName(TSCS);
13736
13737 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013738 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013739 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13740 LookupName(Previous, S);
13741 switch (Previous.getResultKind()) {
13742 case LookupResult::Found:
13743 case LookupResult::FoundUnresolvedValue:
13744 PrevDecl = Previous.getAsSingle<NamedDecl>();
13745 break;
13746
13747 case LookupResult::FoundOverloaded:
13748 PrevDecl = Previous.getRepresentativeDecl();
13749 break;
13750
13751 case LookupResult::NotFound:
13752 case LookupResult::NotFoundInCurrentInstantiation:
13753 case LookupResult::Ambiguous:
13754 break;
13755 }
13756
13757 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13758 // Maybe we will complain about the shadowed template parameter.
13759 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13760 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013761 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013762 }
13763
13764 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013765 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013766
13767 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013768 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013769 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13770 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013771 ProcessDeclAttributes(TUScope, NewPD, D);
13772 NewPD->setAccess(AS);
13773
13774 if (NewPD->isInvalidDecl())
13775 Record->setInvalidDecl();
13776
13777 if (D.getDeclSpec().isModulePrivateSpecified())
13778 NewPD->setModulePrivate();
13779
13780 if (NewPD->isInvalidDecl() && PrevDecl) {
13781 // Don't introduce NewFD into scope; there's already something
13782 // with the same name in the same scope.
13783 } else if (II) {
13784 PushOnScopeChains(NewPD, S);
13785 } else
13786 Record->addDecl(NewPD);
13787
13788 return NewPD;
13789}