blob: aa1bfac7e06f61c03014beaeeff2be6d70134a3e [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 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
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
Chris Lattner199abbc2008-04-08 05:04:30 +0000441 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 // For non-template functions, default arguments can be added in
443 // later declarations of a function in the same
444 // scope. Declarations in different scopes have completely
445 // distinct sets of default arguments. That is, declarations in
446 // inner scopes do not acquire default arguments from
447 // declarations in outer scopes, and vice versa. In a given
448 // function declaration, all parameters subsequent to a
449 // parameter with a default argument shall have default
450 // arguments supplied in this or previous declarations. A
451 // default argument shall not be redefined by a later
452 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000453 //
454 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000455 // Except for member functions of class templates, the default arguments
456 // in a member function definition that appears outside of the class
457 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000458 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000459 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
460 ParmVarDecl *OldParam = Old->getParamDecl(p);
461 ParmVarDecl *NewParam = New->getParamDecl(p);
462
James Molloye9430032012-03-13 08:55:35 +0000463 bool OldParamHasDfl = OldParam->hasDefaultArg();
464 bool NewParamHasDfl = NewParam->hasDefaultArg();
465
Richard Smith541b38b2013-09-20 01:15:31 +0000466 // The declaration context corresponding to the scope is the semantic
467 // parent, unless this is a local function declaration, in which case
468 // it is that surrounding function.
Richard Smith5971e8c2014-08-27 22:31:34 +0000469 DeclContext *ScopeDC = New->isLocalExternDecl()
470 ? New->getLexicalDeclContext()
471 : New->getDeclContext();
472 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000473 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000474 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000475 // the same scope and this is not an out-of-line definition of
476 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000477 OldParamHasDfl = false;
Richard Smith5971e8c2014-08-27 22:31:34 +0000478 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
479 // If only one of these is a local function declaration, then they are
480 // declared in different scopes, even though isDeclInScope may think
481 // they're in the same scope. (If both are local, the scope check is
482 // sufficent, and if neither is local, then they are in the same scope.)
483 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000484
485 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000486
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000487 unsigned DiagDefaultParamID =
488 diag::err_param_default_argument_redefinition;
489
490 // MSVC accepts that default parameters be redefined for member functions
491 // of template class. The new default parameter's value is ignored.
492 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000493 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000494 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
495 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000496 // Merge the old default argument into the new parameter.
497 NewParam->setHasInheritedDefaultArg();
498 if (OldParam->hasUninstantiatedDefaultArg())
499 NewParam->setUninstantiatedDefaultArg(
500 OldParam->getUninstantiatedDefaultArg());
501 else
502 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000503 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000504 Invalid = false;
505 }
506 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000507
Francois Pichet8cb243a2011-04-10 04:58:30 +0000508 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
509 // hint here. Alternatively, we could walk the type-source information
510 // for NewParam to find the last source location in the type... but it
511 // isn't worth the effort right now. This is the kind of test case that
512 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000513 // int f(int);
514 // void g(int (*fp)(int) = f);
515 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000516 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000517 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000518
519 // Look for the function declaration where the default argument was
520 // actually written, which may be a declaration prior to Old.
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000521 for (auto Older = Old; OldParam->hasInheritedDefaultArg();) {
522 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000523 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000524 }
525
Douglas Gregorc732aba2009-09-11 18:44:32 +0000526 Diag(OldParam->getLocation(), diag::note_previous_definition)
527 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000528 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000529 // Merge the old default argument into the new parameter.
530 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000531 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000532 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000533 if (OldParam->hasUnparsedDefaultArg())
534 NewParam->setUnparsedDefaultArg();
535 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000536 NewParam->setUninstantiatedDefaultArg(
537 OldParam->getUninstantiatedDefaultArg());
538 else
John McCalle61b02b2010-05-04 01:53:42 +0000539 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000540 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000541 if (New->getDescribedFunctionTemplate()) {
542 // Paragraph 4, quoted above, only applies to non-template functions.
543 Diag(NewParam->getLocation(),
544 diag::err_param_default_argument_template_redecl)
545 << NewParam->getDefaultArgRange();
546 Diag(Old->getLocation(), diag::note_template_prev_declaration)
547 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000548 } else if (New->getTemplateSpecializationKind()
549 != TSK_ImplicitInstantiation &&
550 New->getTemplateSpecializationKind() != TSK_Undeclared) {
551 // C++ [temp.expr.spec]p21:
552 // Default function arguments shall not be specified in a declaration
553 // or a definition for one of the following explicit specializations:
554 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000555 // - the explicit specialization of a member function template;
556 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000557 // template where the class template specialization to which the
558 // member function specialization belongs is implicitly
559 // instantiated.
560 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
561 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
562 << New->getDeclName()
563 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000564 } else if (New->getDeclContext()->isDependentContext()) {
565 // C++ [dcl.fct.default]p6 (DR217):
566 // Default arguments for a member function of a class template shall
567 // be specified on the initial declaration of the member function
568 // within the class template.
569 //
570 // Reading the tea leaves a bit in DR217 and its reference to DR205
571 // leads me to the conclusion that one cannot add default function
572 // arguments for an out-of-line definition of a member function of a
573 // dependent type.
574 int WhichKind = 2;
575 if (CXXRecordDecl *Record
576 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
577 if (Record->getDescribedClassTemplate())
578 WhichKind = 0;
579 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
580 WhichKind = 1;
581 else
582 WhichKind = 2;
583 }
584
585 Diag(NewParam->getLocation(),
586 diag::err_param_default_argument_member_template_redecl)
587 << WhichKind
588 << NewParam->getDefaultArgRange();
589 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000590 }
591 }
592
Richard Smith58c3cc12012-11-28 03:45:24 +0000593 // DR1344: If a default argument is added outside a class definition and that
594 // default argument makes the function a special member function, the program
595 // is ill-formed. This can only happen for constructors.
596 if (isa<CXXConstructorDecl>(New) &&
597 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
598 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
599 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
600 if (NewSM != OldSM) {
601 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
602 assert(NewParam->hasDefaultArg());
603 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
604 << NewParam->getDefaultArgRange() << NewSM;
605 Diag(Old->getLocation(), diag::note_previous_declaration);
606 }
607 }
608
David Majnemeree4f4022014-03-30 06:44:54 +0000609 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000610 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000611 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000612 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000613 if (New->isConstexpr() != Old->isConstexpr()) {
614 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
615 << New << New->isConstexpr();
616 Diag(Old->getLocation(), diag::note_previous_declaration);
617 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000618 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
619 // C++11 [dcl.fcn.spec]p4:
620 // If the definition of a function appears in a translation unit before its
621 // first declaration as inline, the program is ill-formed.
622 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
623 Diag(Def->getLocation(), diag::note_previous_definition);
624 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000625 }
626
David Majnemer502b0ed2013-06-25 23:09:30 +0000627 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000628 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000629 // the only declaration of the function or function template in the
630 // translation unit.
631 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
632 functionDeclHasDefaultArgument(Old)) {
633 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
634 Diag(Old->getLocation(), diag::note_previous_declaration);
635 Invalid = true;
636 }
637
Douglas Gregorf40863c2010-02-12 07:32:17 +0000638 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000639 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000640
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000641 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000642}
643
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000644/// \brief Merge the exception specifications of two variable declarations.
645///
646/// This is called when there's a redeclaration of a VarDecl. The function
647/// checks if the redeclaration might have an exception specification and
648/// validates compatibility and merges the specs if necessary.
649void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
650 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000651 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000652 return;
653
654 assert(Context.hasSameType(New->getType(), Old->getType()) &&
655 "Should only be called if types are otherwise the same.");
656
657 QualType NewType = New->getType();
658 QualType OldType = Old->getType();
659
660 // We're only interested in pointers and references to functions, as well
661 // as pointers to member functions.
662 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
663 NewType = R->getPointeeType();
664 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
665 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
666 NewType = P->getPointeeType();
667 OldType = OldType->getAs<PointerType>()->getPointeeType();
668 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
669 NewType = M->getPointeeType();
670 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
671 }
672
673 if (!NewType->isFunctionProtoType())
674 return;
675
676 // There's lots of special cases for functions. For function pointers, system
677 // libraries are hopefully not as broken so that we don't need these
678 // workarounds.
679 if (CheckEquivalentExceptionSpec(
680 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
681 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
682 New->setInvalidDecl();
683 }
684}
685
Chris Lattner199abbc2008-04-08 05:04:30 +0000686/// CheckCXXDefaultArguments - Verify that the default arguments for a
687/// function declaration are well-formed according to C++
688/// [dcl.fct.default].
689void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
690 unsigned NumParams = FD->getNumParams();
691 unsigned p;
692
693 // Find first parameter with a default argument
694 for (p = 0; p < NumParams; ++p) {
695 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000696 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000697 break;
698 }
699
Benjamin Kramerfe257592015-03-27 13:58:41 +0000700 // C++11 [dcl.fct.default]p4:
701 // In a given function declaration, each parameter subsequent to a parameter
702 // with a default argument shall have a default argument supplied in this or
703 // a previous declaration or shall be a function parameter pack. A default
704 // argument shall not be redefined by a later declaration (not even to the
705 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +0000706 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000707 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000708 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +0000709 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000710 if (Param->isInvalidDecl())
711 /* We already complained about this parameter. */;
712 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000713 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000714 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000715 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000716 else
Mike Stump11289f42009-09-09 15:08:12 +0000717 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000718 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattner199abbc2008-04-08 05:04:30 +0000720 LastMissingDefaultArg = p;
721 }
722 }
723
724 if (LastMissingDefaultArg > 0) {
725 // Some default arguments were missing. Clear out all of the
726 // default arguments up to (and including) the last missing
727 // default argument, so that we leave the function parameters
728 // in a semantically valid state.
729 for (p = 0; p <= LastMissingDefaultArg; ++p) {
730 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000731 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000732 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000733 }
734 }
735 }
736}
Douglas Gregor556877c2008-04-13 21:30:24 +0000737
Richard Smitheb3c10c2011-10-01 02:31:28 +0000738// CheckConstexprParameterTypes - Check whether a function's parameter types
739// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000740// diagnostic and return false.
741static bool CheckConstexprParameterTypes(Sema &SemaRef,
742 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000743 unsigned ArgIndex = 0;
744 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000745 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
746 e = FT->param_type_end();
747 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000748 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
749 SourceLocation ParamLoc = PD->getLocation();
750 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000751 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000752 diag::err_constexpr_non_literal_param,
753 ArgIndex+1, PD->getSourceRange(),
754 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000755 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000757 return true;
758}
759
760/// \brief Get diagnostic %select index for tag kind for
761/// record diagnostic message.
762/// WARNING: Indexes apply to particular diagnostics only!
763///
764/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000765static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000766 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000767 case TTK_Struct: return 0;
768 case TTK_Interface: return 1;
769 case TTK_Class: return 2;
770 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000771 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000772}
773
774// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
775// the requirements of a constexpr function definition or a constexpr
776// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000777// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778//
Richard Smith3607ffe2012-02-13 03:54:03 +0000779// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
780bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000781 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
782 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000783 // C++11 [dcl.constexpr]p4:
784 // The definition of a constexpr constructor shall satisfy the following
785 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000786 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000787 const CXXRecordDecl *RD = MD->getParent();
788 if (RD->getNumVBases()) {
789 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
790 << isa<CXXConstructorDecl>(NewFD)
791 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000792 for (const auto &I : RD->vbases())
793 Diag(I.getLocStart(),
794 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000795 return false;
796 }
Richard Smith7971b692012-01-13 04:54:00 +0000797 }
798
799 if (!isa<CXXConstructorDecl>(NewFD)) {
800 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 // The definition of a constexpr function shall satisfy the following
802 // constraints:
803 // - it shall not be virtual;
804 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
805 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000807
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 // If it's not obvious why this function is virtual, find an overridden
809 // function which uses the 'virtual' keyword.
810 const CXXMethodDecl *WrittenVirtual = Method;
811 while (!WrittenVirtual->isVirtualAsWritten())
812 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
813 if (WrittenVirtual != Method)
814 Diag(WrittenVirtual->getLocation(),
815 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816 return false;
817 }
818
819 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000820 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000821 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000822 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000823 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000825 }
826
Richard Smith7971b692012-01-13 04:54:00 +0000827 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000828 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000829 return false;
830
Richard Smitheb3c10c2011-10-01 02:31:28 +0000831 return true;
832}
833
834/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000835/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000836///
Richard Smithd9f663b2013-04-22 15:31:51 +0000837/// \return true if the body is OK (maybe only as an extension), false if we
838/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000839static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000840 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
841 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000842 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
843 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000844 for (const auto *DclIt : DS->decls()) {
845 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000846 case Decl::StaticAssert:
847 case Decl::Using:
848 case Decl::UsingShadow:
849 case Decl::UsingDirective:
850 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000851 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000852 // - static_assert-declarations
853 // - using-declarations,
854 // - using-directives,
855 continue;
856
857 case Decl::Typedef:
858 case Decl::TypeAlias: {
859 // - typedef declarations and alias-declarations that do not define
860 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000861 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000862 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
863 // Don't allow variably-modified types in constexpr functions.
864 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
865 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
866 << TL.getSourceRange() << TL.getType()
867 << isa<CXXConstructorDecl>(Dcl);
868 return false;
869 }
870 continue;
871 }
872
873 case Decl::Enum:
874 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000875 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000876 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000877 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000878 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000879 ? diag::warn_cxx11_compat_constexpr_type_definition
880 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000881 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000882 continue;
883
Richard Smithd9f663b2013-04-22 15:31:51 +0000884 case Decl::EnumConstant:
885 case Decl::IndirectField:
886 case Decl::ParmVar:
887 // These can only appear with other declarations which are banned in
888 // C++11 and permitted in C++1y, so ignore them.
889 continue;
890
891 case Decl::Var: {
892 // C++1y [dcl.constexpr]p3 allows anything except:
893 // a definition of a variable of non-literal type or of static or
894 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000895 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000896 if (VD->isThisDeclarationADefinition()) {
897 if (VD->isStaticLocal()) {
898 SemaRef.Diag(VD->getLocation(),
899 diag::err_constexpr_local_var_static)
900 << isa<CXXConstructorDecl>(Dcl)
901 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
902 return false;
903 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000904 if (!VD->getType()->isDependentType() &&
905 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000906 VD->getLocation(), VD->getType(),
907 diag::err_constexpr_local_var_non_literal_type,
908 isa<CXXConstructorDecl>(Dcl)))
909 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000910 if (!VD->getType()->isDependentType() &&
911 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000912 SemaRef.Diag(VD->getLocation(),
913 diag::err_constexpr_local_var_no_init)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917 }
918 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000919 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000920 ? diag::warn_cxx11_compat_constexpr_local_var
921 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000922 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000923 continue;
924 }
925
926 case Decl::NamespaceAlias:
927 case Decl::Function:
928 // These are disallowed in C++11 and permitted in C++1y. Allow them
929 // everywhere as an extension.
930 if (!Cxx1yLoc.isValid())
931 Cxx1yLoc = DS->getLocStart();
932 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000933
934 default:
935 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
936 << isa<CXXConstructorDecl>(Dcl);
937 return false;
938 }
939 }
940
941 return true;
942}
943
944/// Check that the given field is initialized within a constexpr constructor.
945///
946/// \param Dcl The constexpr constructor being checked.
947/// \param Field The field being checked. This may be a member of an anonymous
948/// struct or union nested within the class being checked.
949/// \param Inits All declarations, including anonymous struct/union members and
950/// indirect members, for which any initialization was provided.
951/// \param Diagnosed Set to true if an error is produced.
952static void CheckConstexprCtorInitializer(Sema &SemaRef,
953 const FunctionDecl *Dcl,
954 FieldDecl *Field,
955 llvm::SmallSet<Decl*, 16> &Inits,
956 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000957 if (Field->isInvalidDecl())
958 return;
959
Douglas Gregor556e5862011-10-10 17:22:13 +0000960 if (Field->isUnnamedBitfield())
961 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000962
Richard Smithab44d5b2013-12-10 08:25:00 +0000963 // Anonymous unions with no variant members and empty anonymous structs do not
964 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
965 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000966 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000967 (Field->getType()->isUnionType()
968 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
969 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000970 return;
971
Richard Smitheb3c10c2011-10-01 02:31:28 +0000972 if (!Inits.count(Field)) {
973 if (!Diagnosed) {
974 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
975 Diagnosed = true;
976 }
977 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
978 } else if (Field->isAnonymousStructOrUnion()) {
979 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000980 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000981 // If an anonymous union contains an anonymous struct of which any member
982 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000983 if (!RD->isUnion() || Inits.count(I))
984 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000985 }
986}
987
Richard Smithd9f663b2013-04-22 15:31:51 +0000988/// Check the provided statement is allowed in a constexpr function
989/// definition.
990static bool
991CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000992 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000993 SourceLocation &Cxx1yLoc) {
994 // - its function-body shall be [...] a compound-statement that contains only
995 switch (S->getStmtClass()) {
996 case Stmt::NullStmtClass:
997 // - null statements,
998 return true;
999
1000 case Stmt::DeclStmtClass:
1001 // - static_assert-declarations
1002 // - using-declarations,
1003 // - using-directives,
1004 // - typedef declarations and alias-declarations that do not define
1005 // classes or enumerations,
1006 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1007 return false;
1008 return true;
1009
1010 case Stmt::ReturnStmtClass:
1011 // - and exactly one return statement;
1012 if (isa<CXXConstructorDecl>(Dcl)) {
1013 // C++1y allows return statements in constexpr constructors.
1014 if (!Cxx1yLoc.isValid())
1015 Cxx1yLoc = S->getLocStart();
1016 return true;
1017 }
1018
1019 ReturnStmts.push_back(S->getLocStart());
1020 return true;
1021
1022 case Stmt::CompoundStmtClass: {
1023 // C++1y allows compound-statements.
1024 if (!Cxx1yLoc.isValid())
1025 Cxx1yLoc = S->getLocStart();
1026
1027 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001028 for (auto *BodyIt : CompStmt->body()) {
1029 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001030 Cxx1yLoc))
1031 return false;
1032 }
1033 return true;
1034 }
1035
1036 case Stmt::AttributedStmtClass:
1037 if (!Cxx1yLoc.isValid())
1038 Cxx1yLoc = S->getLocStart();
1039 return true;
1040
1041 case Stmt::IfStmtClass: {
1042 // C++1y allows if-statements.
1043 if (!Cxx1yLoc.isValid())
1044 Cxx1yLoc = S->getLocStart();
1045
1046 IfStmt *If = cast<IfStmt>(S);
1047 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1048 Cxx1yLoc))
1049 return false;
1050 if (If->getElse() &&
1051 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1052 Cxx1yLoc))
1053 return false;
1054 return true;
1055 }
1056
1057 case Stmt::WhileStmtClass:
1058 case Stmt::DoStmtClass:
1059 case Stmt::ForStmtClass:
1060 case Stmt::CXXForRangeStmtClass:
1061 case Stmt::ContinueStmtClass:
1062 // C++1y allows all of these. We don't allow them as extensions in C++11,
1063 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001064 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001065 break;
1066 if (!Cxx1yLoc.isValid())
1067 Cxx1yLoc = S->getLocStart();
1068 for (Stmt::child_range Children = S->children(); Children; ++Children)
1069 if (*Children &&
1070 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1071 Cxx1yLoc))
1072 return false;
1073 return true;
1074
1075 case Stmt::SwitchStmtClass:
1076 case Stmt::CaseStmtClass:
1077 case Stmt::DefaultStmtClass:
1078 case Stmt::BreakStmtClass:
1079 // C++1y allows switch-statements, and since they don't need variable
1080 // mutation, we can reasonably allow them in C++11 as an extension.
1081 if (!Cxx1yLoc.isValid())
1082 Cxx1yLoc = S->getLocStart();
1083 for (Stmt::child_range Children = S->children(); Children; ++Children)
1084 if (*Children &&
1085 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1086 Cxx1yLoc))
1087 return false;
1088 return true;
1089
1090 default:
1091 if (!isa<Expr>(S))
1092 break;
1093
1094 // C++1y allows expression-statements.
1095 if (!Cxx1yLoc.isValid())
1096 Cxx1yLoc = S->getLocStart();
1097 return true;
1098 }
1099
1100 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1101 << isa<CXXConstructorDecl>(Dcl);
1102 return false;
1103}
1104
Richard Smitheb3c10c2011-10-01 02:31:28 +00001105/// Check the body for the given constexpr function declaration only contains
1106/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1107///
1108/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001109bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001110 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001111 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001112 // The definition of a constexpr function shall satisfy the following
1113 // constraints: [...]
1114 // - its function-body shall be = delete, = default, or a
1115 // compound-statement
1116 //
Richard Smith74388b42012-02-04 00:33:54 +00001117 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001118 // In the definition of a constexpr constructor, [...]
1119 // - its function-body shall not be a function-try-block;
1120 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1121 << isa<CXXConstructorDecl>(Dcl);
1122 return false;
1123 }
1124
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001125 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001126
1127 // - its function-body shall be [...] a compound-statement that contains only
1128 // [... list of cases ...]
1129 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1130 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001131 for (auto *BodyIt : CompBody->body()) {
1132 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001133 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001134 }
1135
Richard Smithd9f663b2013-04-22 15:31:51 +00001136 if (Cxx1yLoc.isValid())
1137 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001138 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001139 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1140 : diag::ext_constexpr_body_invalid_stmt)
1141 << isa<CXXConstructorDecl>(Dcl);
1142
Richard Smitheb3c10c2011-10-01 02:31:28 +00001143 if (const CXXConstructorDecl *Constructor
1144 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1145 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001146 // DR1359:
1147 // - every non-variant non-static data member and base class sub-object
1148 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001149 // DR1460:
1150 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001151 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001152 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001153 if (Constructor->getNumCtorInitializers() == 0 &&
1154 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1156 return false;
1157 }
Richard Smithf368fb42011-10-10 16:38:04 +00001158 } else if (!Constructor->isDependentContext() &&
1159 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001160 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1161
1162 // Skip detailed checking if we have enough initializers, and we would
1163 // allow at most one initializer per member.
1164 bool AnyAnonStructUnionMembers = false;
1165 unsigned Fields = 0;
1166 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1167 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001168 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001169 AnyAnonStructUnionMembers = true;
1170 break;
1171 }
1172 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001173 // DR1460:
1174 // - if the class is a union-like class, but is not a union, for each of
1175 // its anonymous union members having variant members, exactly one of
1176 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 if (AnyAnonStructUnionMembers ||
1178 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1179 // Check initialization of non-static data members. Base classes are
1180 // always initialized so do not need to be checked. Dependent bases
1181 // might not have initializers in the member initializer list.
1182 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001183 for (const auto *I: Constructor->inits()) {
1184 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001185 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001186 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001187 Inits.insert(ID->chain_begin(), ID->chain_end());
1188 }
1189
1190 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001191 for (auto *I : RD->fields())
1192 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001193 if (Diagnosed)
1194 return false;
1195 }
1196 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001197 } else {
1198 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001199 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001200 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001201 // otherwise if there's no return statement, the function cannot
1202 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001203 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001204 (Dcl->getReturnType()->isVoidType() ||
1205 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001206 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001207 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1208 : diag::err_constexpr_body_no_return);
1209 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001210 }
1211 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001212 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001213 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001214 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1215 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001216 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1217 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001218 }
1219 }
1220
Richard Smith74388b42012-02-04 00:33:54 +00001221 // C++11 [dcl.constexpr]p5:
1222 // if no function argument values exist such that the function invocation
1223 // substitution would produce a constant expression, the program is
1224 // ill-formed; no diagnostic required.
1225 // C++11 [dcl.constexpr]p3:
1226 // - every constructor call and implicit conversion used in initializing the
1227 // return value shall be one of those allowed in a constant expression.
1228 // C++11 [dcl.constexpr]p4:
1229 // - every constructor involved in initializing non-static data members and
1230 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001231 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001232 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001233 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001234 << isa<CXXConstructorDecl>(Dcl);
1235 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1236 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001237 // Don't return false here: we allow this for compatibility in
1238 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001239 }
1240
Richard Smitheb3c10c2011-10-01 02:31:28 +00001241 return true;
1242}
1243
Douglas Gregor61956c42008-10-31 09:07:45 +00001244/// isCurrentClassName - Determine whether the identifier II is the
1245/// name of the class type currently being defined. In the case of
1246/// nested classes, this will only return true if II is the name of
1247/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001248bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1249 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001250 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001251
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001252 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001253 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001254 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001255 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1256 } else
1257 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1258
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001259 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001260 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001261 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001262}
1263
Richard Smithfb8b7b92013-10-15 00:00:26 +00001264/// \brief Determine whether the identifier II is a typo for the name of
1265/// the class type currently being defined. If so, update it to the identifier
1266/// that should have been used.
1267bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1268 assert(getLangOpts().CPlusPlus && "No class names in C!");
1269
1270 if (!getLangOpts().SpellChecking)
1271 return false;
1272
1273 CXXRecordDecl *CurDecl;
1274 if (SS && SS->isSet() && !SS->isInvalid()) {
1275 DeclContext *DC = computeDeclContext(*SS, true);
1276 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1277 } else
1278 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1279
1280 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1281 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1282 < II->getLength()) {
1283 II = CurDecl->getIdentifier();
1284 return true;
1285 }
1286
1287 return false;
1288}
1289
Douglas Gregordc974572012-11-10 07:24:09 +00001290/// \brief Determine whether the given class is a base class of the given
1291/// class, including looking at dependent bases.
1292static bool findCircularInheritance(const CXXRecordDecl *Class,
1293 const CXXRecordDecl *Current) {
1294 SmallVector<const CXXRecordDecl*, 8> Queue;
1295
1296 Class = Class->getCanonicalDecl();
1297 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001298 for (const auto &I : Current->bases()) {
1299 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001300 if (!Base)
1301 continue;
1302
1303 Base = Base->getDefinition();
1304 if (!Base)
1305 continue;
1306
1307 if (Base->getCanonicalDecl() == Class)
1308 return true;
1309
1310 Queue.push_back(Base);
1311 }
1312
1313 if (Queue.empty())
1314 return false;
1315
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001316 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001317 }
1318
1319 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001320}
1321
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001322/// \brief Perform propagation of DLL attributes from a derived class to a
1323/// templated base class for MS compatibility.
1324static void propagateDLLAttrToBaseClassTemplate(
1325 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1326 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1327 if (getDLLAttr(
1328 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1329 // If the base class template has a DLL attribute, don't try to change it.
1330 return;
1331 }
1332
1333 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1334 // If the base class is not already specialized, we can do the propagation.
1335 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1336 NewAttr->setInherited(true);
1337 BaseTemplateSpec->addAttr(NewAttr);
1338 return;
1339 }
1340
1341 bool DifferentAttribute = false;
1342 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1343 if (!SpecializationAttr->isInherited()) {
1344 // The template has previously been specialized or instantiated with an
1345 // explicit attribute. We should not try to change it.
1346 return;
1347 }
1348 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1349 // The specialization already has the right attribute.
1350 return;
1351 }
1352 DifferentAttribute = true;
1353 }
1354
1355 // The template was previously instantiated or explicitly specialized without
1356 // a dll attribute, or the template was previously instantiated with a
1357 // different inherited attribute. It's too late for us to change the
1358 // attribute, so warn that this is unsupported.
1359 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1360 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1361 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1362 if (BaseTemplateSpec->isExplicitSpecialization()) {
1363 S.Diag(BaseTemplateSpec->getLocation(),
1364 diag::note_template_class_explicit_specialization_was_here)
1365 << BaseTemplateSpec;
1366 } else {
1367 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1368 diag::note_template_class_instantiation_was_here)
1369 << BaseTemplateSpec;
1370 }
1371}
1372
Mike Stump11289f42009-09-09 15:08:12 +00001373/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001374///
1375/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1376/// and returns NULL otherwise.
1377CXXBaseSpecifier *
1378Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1379 SourceRange SpecifierRange,
1380 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001381 TypeSourceInfo *TInfo,
1382 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001383 QualType BaseType = TInfo->getType();
1384
Douglas Gregor463421d2009-03-03 04:44:36 +00001385 // C++ [class.union]p1:
1386 // A union shall not have base classes.
1387 if (Class->isUnion()) {
1388 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1389 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001390 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001391 }
1392
Douglas Gregor752a5952011-01-03 22:36:02 +00001393 if (EllipsisLoc.isValid() &&
1394 !TInfo->getType()->containsUnexpandedParameterPack()) {
1395 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1396 << TInfo->getTypeLoc().getSourceRange();
1397 EllipsisLoc = SourceLocation();
1398 }
Douglas Gregor62004702012-11-10 01:18:17 +00001399
1400 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1401
1402 if (BaseType->isDependentType()) {
1403 // Make sure that we don't have circular inheritance among our dependent
1404 // bases. For non-dependent bases, the check for completeness below handles
1405 // this.
1406 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1407 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1408 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001409 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001410 Diag(BaseLoc, diag::err_circular_inheritance)
1411 << BaseType << Context.getTypeDeclType(Class);
1412
1413 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1414 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1415 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001416
1417 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001418 }
1419 }
1420
Mike Stump11289f42009-09-09 15:08:12 +00001421 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001422 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001423 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001424 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001425
1426 // Base specifiers must be record types.
1427 if (!BaseType->isRecordType()) {
1428 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001429 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001430 }
1431
1432 // C++ [class.union]p1:
1433 // A union shall not be used as a base class.
1434 if (BaseType->isUnionType()) {
1435 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001436 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001437 }
1438
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001439 // For the MS ABI, propagate DLL attributes to base class templates.
1440 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1441 if (Attr *ClassAttr = getDLLAttr(Class)) {
1442 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1443 BaseType->getAsCXXRecordDecl())) {
1444 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1445 BaseTemplate, BaseLoc);
1446 }
1447 }
1448 }
1449
Douglas Gregor463421d2009-03-03 04:44:36 +00001450 // C++ [class.derived]p2:
1451 // The class-name in a base-specifier shall not be an incompletely
1452 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001453 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001454 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001455 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001456 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001457 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001458
Eli Friedmanc96d4962009-08-15 21:55:26 +00001459 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001460 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001461 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001462 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001463 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001464 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001465 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001466
David Majnemer9b1754d2013-11-02 12:00:36 +00001467 // A class which contains a flexible array member is not suitable for use as a
1468 // base class:
1469 // - If the layout determines that a base comes before another base,
1470 // the flexible array member would index into the subsequent base.
1471 // - If the layout determines that base comes before the derived class,
1472 // the flexible array member would index into the derived class.
1473 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1474 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1475 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001476 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001477 }
1478
Anders Carlsson65c76d32011-03-25 14:55:14 +00001479 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001480 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001481 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001482 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001483 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001484 << CXXBaseDecl->getDeclName()
1485 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001486 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1487 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001488 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001489 }
1490
John McCall3696dcb2010-08-17 07:23:57 +00001491 if (BaseDecl->isInvalidDecl())
1492 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001493
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001494 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001495 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001496 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001497 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001498}
1499
Douglas Gregor556877c2008-04-13 21:30:24 +00001500/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1501/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001502/// example:
1503/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001504/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001505BaseResult
John McCall48871652010-08-21 09:40:31 +00001506Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001507 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001508 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001509 ParsedType basetype, SourceLocation BaseLoc,
1510 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001511 if (!classdecl)
1512 return true;
1513
Douglas Gregorc40290e2009-03-09 23:48:35 +00001514 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001515 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001516 if (!Class)
1517 return true;
1518
David Majnemer5ef4fe72014-06-13 06:43:46 +00001519 // We haven't yet attached the base specifiers.
1520 Class->setIsParsingBaseSpecifiers();
1521
Richard Smith4c96e992013-02-19 23:47:15 +00001522 // We do not support any C++11 attributes on base-specifiers yet.
1523 // Diagnose any attributes we see.
1524 if (!Attributes.empty()) {
1525 for (AttributeList *Attr = Attributes.getList(); Attr;
1526 Attr = Attr->getNext()) {
1527 if (Attr->isInvalid() ||
1528 Attr->getKind() == AttributeList::IgnoredAttribute)
1529 continue;
1530 Diag(Attr->getLoc(),
1531 Attr->getKind() == AttributeList::UnknownAttribute
1532 ? diag::warn_unknown_attribute_ignored
1533 : diag::err_base_specifier_attribute)
1534 << Attr->getName();
1535 }
1536 }
1537
Craig Topperc3ec1492014-05-26 06:22:03 +00001538 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001539 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001540
Douglas Gregor752a5952011-01-03 22:36:02 +00001541 if (EllipsisLoc.isInvalid() &&
1542 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001543 UPPC_BaseType))
1544 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001545
Douglas Gregor463421d2009-03-03 04:44:36 +00001546 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001547 Virtual, Access, TInfo,
1548 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001549 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001550 else
1551 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001552
Douglas Gregor463421d2009-03-03 04:44:36 +00001553 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001554}
Douglas Gregor556877c2008-04-13 21:30:24 +00001555
Nathan Sidwell44b21742015-01-19 01:44:02 +00001556/// Use small set to collect indirect bases. As this is only used
1557/// locally, there's no need to abstract the small size parameter.
1558typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1559
1560/// \brief Recursively add the bases of Type. Don't add Type itself.
1561static void
1562NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1563 const QualType &Type)
1564{
1565 // Even though the incoming type is a base, it might not be
1566 // a class -- it could be a template parm, for instance.
1567 if (auto Rec = Type->getAs<RecordType>()) {
1568 auto Decl = Rec->getAsCXXRecordDecl();
1569
1570 // Iterate over its bases.
1571 for (const auto &BaseSpec : Decl->bases()) {
1572 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1573 .getUnqualifiedType();
1574 if (Set.insert(Base).second)
1575 // If we've not already seen it, recurse.
1576 NoteIndirectBases(Context, Set, Base);
1577 }
1578 }
1579}
1580
Douglas Gregor463421d2009-03-03 04:44:36 +00001581/// \brief Performs the actual work of attaching the given base class
1582/// specifiers to a C++ class.
1583bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1584 unsigned NumBases) {
1585 if (NumBases == 0)
1586 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001587
1588 // Used to keep track of which base types we have already seen, so
1589 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001590 // that the key is always the unqualified canonical type of the base
1591 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001592 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1593
Nathan Sidwell44b21742015-01-19 01:44:02 +00001594 // Used to track indirect bases so we can see if a direct base is
1595 // ambiguous.
1596 IndirectBaseSet IndirectBaseTypes;
1597
Douglas Gregor29a92472008-10-22 17:49:05 +00001598 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001599 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001600 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001601 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001602 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001603 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001604 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001605
1606 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1607 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001608 // C++ [class.mi]p3:
1609 // A class shall not be specified as a direct base class of a
1610 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001611 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001612 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001613 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001614 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001615
1616 // Delete the duplicate base class specifier; we're going to
1617 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001618 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001619
1620 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001621 } else {
1622 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001623 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001624 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001625
1626 // Note this base's direct & indirect bases, if there could be ambiguity.
1627 if (NumBases > 1)
1628 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1629
John McCalldb632ac2012-09-25 07:32:39 +00001630 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1631 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1632 if (Class->isInterface() &&
1633 (!RD->isInterface() ||
1634 KnownBase->getAccessSpecifier() != AS_public)) {
1635 // The Microsoft extension __interface does not permit bases that
1636 // are not themselves public interfaces.
1637 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1638 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1639 << RD->getSourceRange();
1640 Invalid = true;
1641 }
1642 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001643 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001644 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001645 }
1646 }
1647
1648 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001649 Class->setBases(Bases, NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001650
1651 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1652 // Check whether this direct base is inaccessible due to ambiguity.
1653 QualType BaseType = Bases[idx]->getType();
1654 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1655 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001656
Nathan Sidwell44b21742015-01-19 01:44:02 +00001657 if (IndirectBaseTypes.count(CanonicalBase)) {
1658 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1659 /*DetectVirtual=*/true);
1660 bool found
1661 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1662 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001663 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001664
1665 if (Paths.isAmbiguous(CanonicalBase))
1666 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1667 << BaseType << getAmbiguousPathsDisplayString(Paths)
1668 << Bases[idx]->getSourceRange();
1669 else
1670 assert(Bases[idx]->isVirtual());
1671 }
1672
1673 // Delete the base class specifier, since its data has been copied
1674 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001675 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001676 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001677
1678 return Invalid;
1679}
1680
1681/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1682/// class, after checking whether there are any duplicate base
1683/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001684void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001685 unsigned NumBases) {
1686 if (!ClassDecl || !Bases || !NumBases)
1687 return;
1688
1689 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001690 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001691}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001692
Douglas Gregor36d1b142009-10-06 17:59:45 +00001693/// \brief Determine whether the type \p Derived is a C++ class that is
1694/// derived from the type \p Base.
1695bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001696 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697 return false;
John McCalle78aac42010-03-10 03:28:59 +00001698
Douglas Gregor45bb4832013-03-26 23:36:30 +00001699 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001700 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001701 return false;
1702
Douglas Gregor45bb4832013-03-26 23:36:30 +00001703 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001704 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001705 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001706
1707 // If either the base or the derived type is invalid, don't try to
1708 // check whether one is derived from the other.
1709 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1710 return false;
1711
John McCall67da35c2010-02-04 22:26:26 +00001712 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1713 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001714}
1715
1716/// \brief Determine whether the type \p Derived is a C++ class that is
1717/// derived from the type \p Base.
1718bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001719 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001720 return false;
1721
Douglas Gregor45bb4832013-03-26 23:36:30 +00001722 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001723 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001724 return false;
1725
Douglas Gregor45bb4832013-03-26 23:36:30 +00001726 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001727 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001728 return false;
1729
Douglas Gregor36d1b142009-10-06 17:59:45 +00001730 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1731}
1732
Anders Carlssona70cff62010-04-24 19:06:50 +00001733void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001734 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001735 assert(BasePathArray.empty() && "Base path array must be empty!");
1736 assert(Paths.isRecordingPaths() && "Must record paths!");
1737
1738 const CXXBasePath &Path = Paths.front();
1739
1740 // We first go backward and check if we have a virtual base.
1741 // FIXME: It would be better if CXXBasePath had the base specifier for
1742 // the nearest virtual base.
1743 unsigned Start = 0;
1744 for (unsigned I = Path.size(); I != 0; --I) {
1745 if (Path[I - 1].Base->isVirtual()) {
1746 Start = I - 1;
1747 break;
1748 }
1749 }
1750
1751 // Now add all bases.
1752 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001753 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001754}
1755
Douglas Gregor36d1b142009-10-06 17:59:45 +00001756/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1757/// conversion (where Derived and Base are class types) is
1758/// well-formed, meaning that the conversion is unambiguous (and
1759/// that all of the base classes are accessible). Returns true
1760/// and emits a diagnostic if the code is ill-formed, returns false
1761/// otherwise. Loc is the location where this routine should point to
1762/// if there is an error, and Range is the source range to highlight
1763/// if there is an error.
1764bool
1765Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001766 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001767 unsigned AmbigiousBaseConvID,
1768 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001769 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001770 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001771 // First, determine whether the path from Derived to Base is
1772 // ambiguous. This is slightly more expensive than checking whether
1773 // the Derived to Base conversion exists, because here we need to
1774 // explore multiple paths to determine if there is an ambiguity.
1775 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1776 /*DetectVirtual=*/false);
1777 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1778 assert(DerivationOkay &&
1779 "Can only be used with a derived-to-base conversion");
1780 (void)DerivationOkay;
1781
1782 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001783 if (InaccessibleBaseID) {
1784 // Check that the base class can be accessed.
1785 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1786 InaccessibleBaseID)) {
1787 case AR_inaccessible:
1788 return true;
1789 case AR_accessible:
1790 case AR_dependent:
1791 case AR_delayed:
1792 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001793 }
John McCall5b0829a2010-02-10 09:31:12 +00001794 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001795
1796 // Build a base path if necessary.
1797 if (BasePath)
1798 BuildBasePathArray(Paths, *BasePath);
1799 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001800 }
1801
David Majnemer626032f2013-06-22 06:43:58 +00001802 if (AmbigiousBaseConvID) {
1803 // We know that the derived-to-base conversion is ambiguous, and
1804 // we're going to produce a diagnostic. Perform the derived-to-base
1805 // search just one more time to compute all of the possible paths so
1806 // that we can print them out. This is more expensive than any of
1807 // the previous derived-to-base checks we've done, but at this point
1808 // performance isn't as much of an issue.
1809 Paths.clear();
1810 Paths.setRecordingPaths(true);
1811 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1812 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1813 (void)StillOkay;
1814
1815 // Build up a textual representation of the ambiguous paths, e.g.,
1816 // D -> B -> A, that will be used to illustrate the ambiguous
1817 // conversions in the diagnostic. We only print one of the paths
1818 // to each base class subobject.
1819 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1820
1821 Diag(Loc, AmbigiousBaseConvID)
1822 << Derived << Base << PathDisplayStr << Range << Name;
1823 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001824 return true;
1825}
1826
1827bool
1828Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001829 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001830 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001831 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001832 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001833 IgnoreAccess ? 0
1834 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001835 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001836 Loc, Range, DeclarationName(),
1837 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001838}
1839
1840
1841/// @brief Builds a string representing ambiguous paths from a
1842/// specific derived class to different subobjects of the same base
1843/// class.
1844///
1845/// This function builds a string that can be used in error messages
1846/// to show the different paths that one can take through the
1847/// inheritance hierarchy to go from the derived class to different
1848/// subobjects of a base class. The result looks something like this:
1849/// @code
1850/// struct D -> struct B -> struct A
1851/// struct D -> struct C -> struct A
1852/// @endcode
1853std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1854 std::string PathDisplayStr;
1855 std::set<unsigned> DisplayedPaths;
1856 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1857 Path != Paths.end(); ++Path) {
1858 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1859 // We haven't displayed a path to this particular base
1860 // class subobject yet.
1861 PathDisplayStr += "\n ";
1862 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1863 for (CXXBasePath::const_iterator Element = Path->begin();
1864 Element != Path->end(); ++Element)
1865 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1866 }
1867 }
1868
1869 return PathDisplayStr;
1870}
1871
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001872//===----------------------------------------------------------------------===//
1873// C++ class member Handling
1874//===----------------------------------------------------------------------===//
1875
Abramo Bagnarad7340582010-06-05 05:09:32 +00001876/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001877bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1878 SourceLocation ASLoc,
1879 SourceLocation ColonLoc,
1880 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001881 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001882 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001883 ASLoc, ColonLoc);
1884 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001885 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001886}
1887
Richard Smith18f07db2012-08-06 03:25:17 +00001888/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001889void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001890 if (D->isInvalidDecl())
1891 return;
1892
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001893 // We only care about "override" and "final" declarations.
1894 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1895 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001896
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001897 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001898
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001899 // We can't check dependent instance methods.
1900 if (MD && MD->isInstance() &&
1901 (MD->getParent()->hasAnyDependentBases() ||
1902 MD->getType()->isDependentType()))
1903 return;
1904
1905 if (MD && !MD->isVirtual()) {
1906 // If we have a non-virtual method, check if if hides a virtual method.
1907 // (In that case, it's most likely the method has the wrong type.)
1908 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1909 FindHiddenVirtualMethods(MD, OverloadedMethods);
1910
1911 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001912 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1913 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001914 diag::override_keyword_hides_virtual_member_function)
1915 << "override" << (OverloadedMethods.size() > 1);
1916 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001917 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001918 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001919 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1920 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001921 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001922 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1923 MD->setInvalidDecl();
1924 return;
1925 }
1926 // Fall through into the general case diagnostic.
1927 // FIXME: We might want to attempt typo correction here.
1928 }
1929
1930 if (!MD || !MD->isVirtual()) {
1931 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1932 Diag(OA->getLocation(),
1933 diag::override_keyword_only_allowed_on_virtual_member_functions)
1934 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1935 D->dropAttr<OverrideAttr>();
1936 }
1937 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1938 Diag(FA->getLocation(),
1939 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001940 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1941 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001942 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001943 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001944 return;
1945 }
Richard Smith18f07db2012-08-06 03:25:17 +00001946
Richard Smith18f07db2012-08-06 03:25:17 +00001947 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001948 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001949 // does not override a member function of a base class, the program is
1950 // ill-formed.
1951 bool HasOverriddenMethods =
1952 MD->begin_overridden_methods() != MD->end_overridden_methods();
1953 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1954 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1955 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001956}
1957
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001958void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1959 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1960 return;
1961 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1962 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1963 isa<CXXDestructorDecl>(MD))
1964 return;
1965
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001966 SourceLocation Loc = MD->getLocation();
1967 SourceLocation SpellingLoc = Loc;
1968 if (getSourceManager().isMacroArgExpansion(Loc))
1969 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1970 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1971 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001972 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001973
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001974 if (MD->size_overridden_methods() > 0) {
1975 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1976 << MD->getDeclName();
1977 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1978 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1979 }
1980}
1981
Richard Smith18f07db2012-08-06 03:25:17 +00001982/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001983/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001984/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001985bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1986 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001987 FinalAttr *FA = Old->getAttr<FinalAttr>();
1988 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001989 return false;
1990
1991 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001992 << New->getDeclName()
1993 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001994 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1995 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001996}
1997
Daniel Jasper0baec5492012-06-06 08:32:04 +00001998static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001999 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2000 // FIXME: Destruction of ObjC lifetime types has side-effects.
2001 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2002 return !RD->isCompleteDefinition() ||
2003 !RD->hasTrivialDefaultConstructor() ||
2004 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002005 return false;
2006}
2007
John McCall5e77d762013-04-16 07:28:30 +00002008static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002009 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002010 if (it->isDeclspecPropertyAttribute())
2011 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002012 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002013}
2014
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002015/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2016/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002017/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002018/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2019/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002020NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002021Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002022 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002023 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002024 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002025 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002026 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2027 DeclarationName Name = NameInfo.getName();
2028 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002029
2030 // For anonymous bitfields, the location should point to the type.
2031 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002032 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002033
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002034 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002035
John McCallb1cd7da2010-06-04 08:34:12 +00002036 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002037 assert(!DS.isFriendSpecified());
2038
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002039 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002040
John McCalldb632ac2012-09-25 07:32:39 +00002041 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2042 // The Microsoft extension __interface only permits public member functions
2043 // and prohibits constructors, destructors, operators, non-public member
2044 // functions, static methods and data members.
2045 unsigned InvalidDecl;
2046 bool ShowDeclName = true;
2047 if (!isFunc)
2048 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2049 else if (AS != AS_public)
2050 InvalidDecl = 2;
2051 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2052 InvalidDecl = 3;
2053 else switch (Name.getNameKind()) {
2054 case DeclarationName::CXXConstructorName:
2055 InvalidDecl = 4;
2056 ShowDeclName = false;
2057 break;
2058
2059 case DeclarationName::CXXDestructorName:
2060 InvalidDecl = 5;
2061 ShowDeclName = false;
2062 break;
2063
2064 case DeclarationName::CXXOperatorName:
2065 case DeclarationName::CXXConversionFunctionName:
2066 InvalidDecl = 6;
2067 break;
2068
2069 default:
2070 InvalidDecl = 0;
2071 break;
2072 }
2073
2074 if (InvalidDecl) {
2075 if (ShowDeclName)
2076 Diag(Loc, diag::err_invalid_member_in_interface)
2077 << (InvalidDecl-1) << Name;
2078 else
2079 Diag(Loc, diag::err_invalid_member_in_interface)
2080 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002081 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002082 }
2083 }
2084
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002085 // C++ 9.2p6: A member shall not be declared to have automatic storage
2086 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002087 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2088 // data members and cannot be applied to names declared const or static,
2089 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002090 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002091 case DeclSpec::SCS_unspecified:
2092 case DeclSpec::SCS_typedef:
2093 case DeclSpec::SCS_static:
2094 break;
2095 case DeclSpec::SCS_mutable:
2096 if (isFunc) {
2097 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002098
Richard Smithb4a9e862013-04-12 22:46:28 +00002099 // FIXME: It would be nicer if the keyword was ignored only for this
2100 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002101 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002102 }
2103 break;
2104 default:
2105 Diag(DS.getStorageClassSpecLoc(),
2106 diag::err_storageclass_invalid_for_member);
2107 D.getMutableDeclSpec().ClearStorageClassSpecs();
2108 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002109 }
2110
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002111 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2112 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002113 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002114
David Blaikie35506f82013-01-30 01:22:18 +00002115 if (DS.isConstexprSpecified() && isInstField) {
2116 SemaDiagnosticBuilder B =
2117 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2118 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2119 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002120 B << 0 << 0;
2121 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2122 B << FixItHint::CreateRemoval(ConstexprLoc);
2123 else {
2124 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2125 D.getMutableDeclSpec().ClearConstexprSpec();
2126 const char *PrevSpec;
2127 unsigned DiagID;
2128 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2129 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2130 (void)Failed;
2131 assert(!Failed && "Making a constexpr member const shouldn't fail");
2132 }
David Blaikie35506f82013-01-30 01:22:18 +00002133 } else {
2134 B << 1;
2135 const char *PrevSpec;
2136 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002137 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002138 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2139 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002140 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002141 "This is the only DeclSpec that should fail to be applied");
2142 B << 1;
2143 } else {
2144 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2145 isInstField = false;
2146 }
2147 }
2148 }
2149
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002150 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002151 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002152 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002153
2154 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002155 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002156 Diag(Loc, diag::err_bad_variable_name)
2157 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002158 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002159 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002160
Benjamin Kramer365082d2012-05-19 16:34:46 +00002161 IdentifierInfo *II = Name.getAsIdentifierInfo();
2162
Douglas Gregor7c26c042011-09-21 14:40:46 +00002163 // Member field could not be with "template" keyword.
2164 // So TemplateParameterLists should be empty in this case.
2165 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002166 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002167 if (TemplateParams->size()) {
2168 // There is no such thing as a member field template.
2169 Diag(D.getIdentifierLoc(), diag::err_template_member)
2170 << II
2171 << SourceRange(TemplateParams->getTemplateLoc(),
2172 TemplateParams->getRAngleLoc());
2173 } else {
2174 // There is an extraneous 'template<>' for this member.
2175 Diag(TemplateParams->getTemplateLoc(),
2176 diag::err_template_member_noparams)
2177 << II
2178 << SourceRange(TemplateParams->getTemplateLoc(),
2179 TemplateParams->getRAngleLoc());
2180 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002181 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002182 }
2183
Douglas Gregora007d362010-10-13 22:19:53 +00002184 if (SS.isSet() && !SS.isInvalid()) {
2185 // The user provided a superfluous scope specifier inside a class
2186 // definition:
2187 //
2188 // class X {
2189 // int X::member;
2190 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002191 if (DeclContext *DC = computeDeclContext(SS, false))
2192 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002193 else
2194 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2195 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002196
Douglas Gregora007d362010-10-13 22:19:53 +00002197 SS.clear();
2198 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002199
John McCall5e77d762013-04-16 07:28:30 +00002200 AttributeList *MSPropertyAttr =
2201 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002202 if (MSPropertyAttr) {
2203 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2204 BitWidth, InitStyle, AS, MSPropertyAttr);
2205 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002206 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002207 isInstField = false;
2208 } else {
2209 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2210 BitWidth, InitStyle, AS);
2211 assert(Member && "HandleField never returns null");
2212 }
2213 } else {
Nico Webera089c7c2015-01-16 21:09:43 +00002214 assert(InitStyle == ICIS_NoInit ||
2215 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002216
2217 Member = HandleDeclarator(S, D, TemplateParameterLists);
2218 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002219 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002220
2221 // Non-instance-fields can't have a bitfield.
2222 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002223 if (Member->isInvalidDecl()) {
2224 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002225 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002226 // C++ 9.6p3: A bit-field shall not be a static member.
2227 // "static member 'A' cannot be a bit-field"
2228 Diag(Loc, diag::err_static_not_bitfield)
2229 << Name << BitWidth->getSourceRange();
2230 } else if (isa<TypedefDecl>(Member)) {
2231 // "typedef member 'x' cannot be a bit-field"
2232 Diag(Loc, diag::err_typedef_not_bitfield)
2233 << Name << BitWidth->getSourceRange();
2234 } else {
2235 // A function typedef ("typedef int f(); f a;").
2236 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2237 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002238 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002239 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002240 }
Mike Stump11289f42009-09-09 15:08:12 +00002241
Craig Topperc3ec1492014-05-26 06:22:03 +00002242 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002243 Member->setInvalidDecl();
2244 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002245
2246 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002247
Larisse Voufo39a1e502013-08-06 01:03:05 +00002248 // If we have declared a member function template or static data member
2249 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002250 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2251 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002252 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2253 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002254 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002255
Richard Smith18f07db2012-08-06 03:25:17 +00002256 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002257 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002258 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002259 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2260 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002261
Douglas Gregorf2f08062011-03-08 17:10:18 +00002262 if (VS.getLastLocation().isValid()) {
2263 // Update the end location of a method that has a virt-specifiers.
2264 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2265 MD->setRangeEnd(VS.getLastLocation());
2266 }
Richard Smith18f07db2012-08-06 03:25:17 +00002267
Anders Carlssonc87f8612011-01-20 06:29:02 +00002268 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002269
Douglas Gregor92751d42008-11-17 22:58:34 +00002270 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002271
Daniel Jasper0baec5492012-06-06 08:32:04 +00002272 if (isInstField) {
2273 FieldDecl *FD = cast<FieldDecl>(Member);
2274 FieldCollector->Add(FD);
2275
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002276 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002277 // Remember all explicit private FieldDecls that have a name, no side
2278 // effects and are not part of a dependent type declaration.
2279 if (!FD->isImplicit() && FD->getDeclName() &&
2280 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002281 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002282 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002283 !InitializationHasSideEffects(*FD))
2284 UnusedPrivateFields.insert(FD);
2285 }
2286 }
2287
John McCall48871652010-08-21 09:40:31 +00002288 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002289}
2290
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002291namespace {
2292 class UninitializedFieldVisitor
2293 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2294 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002295 // List of Decls to generate a warning on. Also remove Decls that become
2296 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002297 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002298 // List of base classes of the record. Classes are removed after their
2299 // initializers.
2300 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002301 // Vector of decls to be removed from the Decl set prior to visiting the
2302 // nodes. These Decls may have been initialized in the prior initializer.
2303 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002304 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002305 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002306 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002307 // InitList is true, special case initialization of FieldDecls matching
2308 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002309 bool InitList;
2310 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002311 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2312
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002313 public:
2314 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002315 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002316 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2317 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2318 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2319 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002320
Richard Trieufa1d0a72014-10-17 20:56:10 +00002321 // Returns true if the use of ME is not an uninitialized use.
2322 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2323 bool CheckReferenceOnly) {
2324 llvm::SmallVector<FieldDecl*, 4> Fields;
2325 bool ReferenceField = false;
2326 while (ME) {
2327 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2328 if (!FD)
2329 return false;
2330 Fields.push_back(FD);
2331 if (FD->getType()->isReferenceType())
2332 ReferenceField = true;
2333 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2334 }
2335
2336 // Binding a reference to an unintialized field is not an
2337 // uninitialized use.
2338 if (CheckReferenceOnly && !ReferenceField)
2339 return true;
2340
2341 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2342 // Discard the first field since it is the field decl that is being
2343 // initialized.
2344 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2345 UsedFieldIndex.push_back((*I)->getFieldIndex());
2346 }
2347
2348 for (auto UsedIter = UsedFieldIndex.begin(),
2349 UsedEnd = UsedFieldIndex.end(),
2350 OrigIter = InitFieldIndex.begin(),
2351 OrigEnd = InitFieldIndex.end();
2352 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2353 if (*UsedIter < *OrigIter)
2354 return true;
2355 if (*UsedIter > *OrigIter)
2356 break;
2357 }
2358
2359 return false;
2360 }
2361
Richard Trieu2d779b92014-10-01 03:44:58 +00002362 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2363 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002364 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2365 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002366
Richard Trieu1bc22c12013-09-13 03:20:53 +00002367 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2368 // or union.
2369 MemberExpr *FieldME = ME;
2370
Richard Trieu2d779b92014-10-01 03:44:58 +00002371 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2372
Richard Trieu1bc22c12013-09-13 03:20:53 +00002373 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002374 while (MemberExpr *SubME =
2375 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002376
Richard Trieufa1d0a72014-10-17 20:56:10 +00002377 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002378 return;
2379
Richard Trieufa1d0a72014-10-17 20:56:10 +00002380 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002381 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002382 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002383
Richard Trieu2d779b92014-10-01 03:44:58 +00002384 if (!FieldME->getType().isPODType(S.Context))
2385 AllPODFields = false;
2386
Richard Trieu3630c392014-11-21 03:10:30 +00002387 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002388 }
2389
Richard Trieu3630c392014-11-21 03:10:30 +00002390 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002391 return;
2392
Richard Trieu2d779b92014-10-01 03:44:58 +00002393 if (AddressOf && AllPODFields)
2394 return;
2395
Richard Trieu406e65c2013-09-20 03:03:06 +00002396 ValueDecl* FoundVD = FieldME->getMemberDecl();
2397
Richard Trieu3630c392014-11-21 03:10:30 +00002398 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2399 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2400 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2401 }
2402
2403 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2404 QualType T = BaseCast->getType();
2405 if (T->isPointerType() &&
2406 BaseClasses.count(T->getPointeeType())) {
2407 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2408 << T->getPointeeType() << FoundVD;
2409 }
2410 }
2411 }
2412
Richard Trieuef64e942013-10-25 00:56:00 +00002413 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002414 return;
2415
Richard Trieuef64e942013-10-25 00:56:00 +00002416 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002417
Richard Trieufa1d0a72014-10-17 20:56:10 +00002418 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2419 // Special checking for initializer lists.
2420 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2421 return;
2422 }
2423 } else {
2424 // Prevent double warnings on use of unbounded references.
2425 if (CheckReferenceOnly && !IsReference)
2426 return;
2427 }
Richard Trieuef64e942013-10-25 00:56:00 +00002428
2429 unsigned diag = IsReference
2430 ? diag::warn_reference_field_is_uninit
2431 : diag::warn_field_is_uninit;
2432 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2433 if (Constructor)
2434 S.Diag(Constructor->getLocation(),
2435 diag::note_uninit_in_this_constructor)
2436 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2437
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002438 }
2439
Richard Trieu2d779b92014-10-01 03:44:58 +00002440 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002441 E = E->IgnoreParens();
2442
2443 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002444 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2445 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002446 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002447 }
2448
2449 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002450 Visit(CO->getCond());
2451 HandleValue(CO->getTrueExpr(), AddressOf);
2452 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002453 return;
2454 }
2455
2456 if (BinaryConditionalOperator *BCO =
2457 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002458 Visit(BCO->getCond());
2459 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002460 return;
2461 }
2462
Richard Trieuabf6ec42014-08-27 22:15:10 +00002463 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002464 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002465 return;
2466 }
2467
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002468 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2469 switch (BO->getOpcode()) {
2470 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002471 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002472 case(BO_PtrMemD):
2473 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002474 HandleValue(BO->getLHS(), AddressOf);
2475 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002476 return;
2477 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002478 Visit(BO->getLHS());
2479 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002480 return;
2481 }
2482 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002483
2484 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002485 }
2486
Richard Trieufa1d0a72014-10-17 20:56:10 +00002487 void CheckInitListExpr(InitListExpr *ILE) {
2488 InitFieldIndex.push_back(0);
2489 for (auto Child : ILE->children()) {
2490 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2491 CheckInitListExpr(SubList);
2492 } else {
2493 Visit(Child);
2494 }
2495 ++InitFieldIndex.back();
2496 }
2497 InitFieldIndex.pop_back();
2498 }
2499
Richard Trieu8d08a272014-08-28 03:23:47 +00002500 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002501 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002502 // Remove Decls that may have been initialized in the previous
2503 // initializer.
2504 for (ValueDecl* VD : DeclsToRemove)
2505 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002506 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002507
Richard Trieu8d08a272014-08-28 03:23:47 +00002508 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002509 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2510
2511 if (ILE && Field) {
2512 InitList = true;
2513 InitListFieldDecl = Field;
2514 InitFieldIndex.clear();
2515 CheckInitListExpr(ILE);
2516 } else {
2517 InitList = false;
2518 Visit(E);
2519 }
2520
Richard Trieu8d08a272014-08-28 03:23:47 +00002521 if (Field)
2522 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002523 if (BaseClass)
2524 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002525 }
2526
Richard Trieu1bc22c12013-09-13 03:20:53 +00002527 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002528 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002529 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002530 }
2531
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002532 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002533 if (E->getCastKind() == CK_LValueToRValue) {
2534 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2535 return;
2536 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002537
2538 Inherited::VisitImplicitCastExpr(E);
2539 }
2540
Richard Trieu1bc22c12013-09-13 03:20:53 +00002541 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002542 if (E->getConstructor()->isCopyConstructor()) {
2543 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002544 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2545 if (ILE->getNumInits() == 1)
2546 ArgExpr = ILE->getInit(0);
2547 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2548 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002549 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002550 HandleValue(ArgExpr, false /*AddressOf*/);
2551 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002552 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002553 Inherited::VisitCXXConstructExpr(E);
2554 }
2555
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002556 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2557 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002558 if (isa<MemberExpr>(Callee)) {
2559 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002560 for (auto Arg : E->arguments())
2561 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002562 return;
2563 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002564
2565 Inherited::VisitCXXMemberCallExpr(E);
2566 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002567
Richard Trieu11fd0792014-08-26 04:30:55 +00002568 void VisitCallExpr(CallExpr *E) {
2569 // Treat std::move as a use.
2570 if (E->getNumArgs() == 1) {
2571 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002572 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2573 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002574 HandleValue(E->getArg(0), false /*AddressOf*/);
2575 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002576 }
2577 }
2578 }
2579
2580 Inherited::VisitCallExpr(E);
2581 }
2582
Richard Trieud4a01362014-10-31 21:10:22 +00002583 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2584 Expr *Callee = E->getCallee();
2585
2586 if (isa<UnresolvedLookupExpr>(Callee))
2587 return Inherited::VisitCXXOperatorCallExpr(E);
2588
2589 Visit(Callee);
2590 for (auto Arg : E->arguments())
2591 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2592 }
2593
Richard Trieu406e65c2013-09-20 03:03:06 +00002594 void VisitBinaryOperator(BinaryOperator *E) {
2595 // If a field assignment is detected, remove the field from the
2596 // uninitiailized field set.
2597 if (E->getOpcode() == BO_Assign)
2598 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2599 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002600 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002601 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002602
Richard Trieu52b8b602014-09-25 01:15:40 +00002603 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002604 HandleValue(E->getLHS(), false /*AddressOf*/);
2605 Visit(E->getRHS());
2606 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002607 }
2608
Richard Trieu406e65c2013-09-20 03:03:06 +00002609 Inherited::VisitBinaryOperator(E);
2610 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002611
2612 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002613 if (E->isIncrementDecrementOp()) {
2614 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2615 return;
2616 }
2617 if (E->getOpcode() == UO_AddrOf) {
2618 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2619 HandleValue(ME->getBase(), true /*AddressOf*/);
2620 return;
2621 }
2622 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002623
2624 Inherited::VisitUnaryOperator(E);
2625 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002626 };
Richard Trieuef64e942013-10-25 00:56:00 +00002627
2628 // Diagnose value-uses of fields to initialize themselves, e.g.
2629 // foo(foo)
2630 // where foo is not also a parameter to the constructor.
2631 // Also diagnose across field uninitialized use such as
2632 // x(y), y(x)
2633 // TODO: implement -Wuninitialized and fold this into that framework.
2634 static void DiagnoseUninitializedFields(
2635 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2636
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002637 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2638 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002639 return;
2640 }
2641
2642 if (Constructor->isInvalidDecl())
2643 return;
2644
2645 const CXXRecordDecl *RD = Constructor->getParent();
2646
Richard Trieu353a4b42014-10-22 05:21:59 +00002647 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002648 return;
2649
Richard Trieuef64e942013-10-25 00:56:00 +00002650 // Holds fields that are uninitialized.
2651 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2652
2653 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002654 for (auto *I : RD->decls()) {
2655 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002656 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002657 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002658 UninitializedFields.insert(IFD->getAnonField());
2659 }
2660 }
2661
Richard Trieu3630c392014-11-21 03:10:30 +00002662 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2663 for (auto I : RD->bases())
2664 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2665
2666 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002667 return;
2668
2669 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002670 UninitializedFields,
2671 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002672
Aaron Ballman0ad78302014-03-13 17:34:31 +00002673 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002674 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002675 break;
2676
Aaron Ballman0ad78302014-03-13 17:34:31 +00002677 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002678 if (!InitExpr)
2679 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002680
Richard Trieu8d08a272014-08-28 03:23:47 +00002681 if (CXXDefaultInitExpr *Default =
2682 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2683 InitExpr = Default->getExpr();
2684 if (!InitExpr)
2685 continue;
2686 // In class initializers will point to the constructor.
2687 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002688 FieldInit->getAnyMember(),
2689 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002690 } else {
2691 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002692 FieldInit->getAnyMember(),
2693 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002694 }
Richard Trieuef64e942013-10-25 00:56:00 +00002695 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002696 }
2697} // namespace
2698
Richard Smith74108172014-01-17 03:11:34 +00002699/// \brief Enter a new C++ default initializer scope. After calling this, the
2700/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2701/// parsing or instantiating the initializer failed.
2702void Sema::ActOnStartCXXInClassMemberInitializer() {
2703 // Create a synthetic function scope to represent the call to the constructor
2704 // that notionally surrounds a use of this initializer.
2705 PushFunctionScope();
2706}
2707
2708/// \brief This is invoked after parsing an in-class initializer for a
2709/// non-static C++ class member, and after instantiating an in-class initializer
2710/// in a class template. Such actions are deferred until the class is complete.
2711void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2712 SourceLocation InitLoc,
2713 Expr *InitExpr) {
2714 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002715 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002716
David Majnemer87ff66c2014-12-13 11:34:16 +00002717 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2718 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002719 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002720
2721 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002722 D->setInvalidDecl();
2723 if (FD)
2724 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002725 return;
2726 }
2727
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002728 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2729 FD->setInvalidDecl();
2730 FD->removeInClassInitializer();
2731 return;
2732 }
2733
Richard Smith938f40b2011-06-11 17:19:42 +00002734 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002735 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002736 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002737 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002738 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002739 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002740 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2741 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002742 if (Init.isInvalid()) {
2743 FD->setInvalidDecl();
2744 return;
2745 }
Richard Smith938f40b2011-06-11 17:19:42 +00002746 }
2747
Richard Smith945f8d32013-01-14 22:39:08 +00002748 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002749 // The initialization of each base and member constitutes a
2750 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002751 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002752 if (Init.isInvalid()) {
2753 FD->setInvalidDecl();
2754 return;
2755 }
2756
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002757 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002758
2759 FD->setInClassInitializer(InitExpr);
2760}
2761
Douglas Gregor15e77a22009-12-31 09:10:24 +00002762/// \brief Find the direct and/or virtual base specifiers that
2763/// correspond to the given base type, for use in base initialization
2764/// within a constructor.
2765static bool FindBaseInitializer(Sema &SemaRef,
2766 CXXRecordDecl *ClassDecl,
2767 QualType BaseType,
2768 const CXXBaseSpecifier *&DirectBaseSpec,
2769 const CXXBaseSpecifier *&VirtualBaseSpec) {
2770 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002771 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002772 for (const auto &Base : ClassDecl->bases()) {
2773 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002774 // We found a direct base of this type. That's what we're
2775 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002776 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002777 break;
2778 }
2779 }
2780
2781 // Check for a virtual base class.
2782 // FIXME: We might be able to short-circuit this if we know in advance that
2783 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002784 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002785 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2786 // We haven't found a base yet; search the class hierarchy for a
2787 // virtual base class.
2788 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2789 /*DetectVirtual=*/false);
2790 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2791 BaseType, Paths)) {
2792 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2793 Path != Paths.end(); ++Path) {
2794 if (Path->back().Base->isVirtual()) {
2795 VirtualBaseSpec = Path->back().Base;
2796 break;
2797 }
2798 }
2799 }
2800 }
2801
2802 return DirectBaseSpec || VirtualBaseSpec;
2803}
2804
Sebastian Redla74948d2011-09-24 17:48:25 +00002805/// \brief Handle a C++ member initializer using braced-init-list syntax.
2806MemInitResult
2807Sema::ActOnMemInitializer(Decl *ConstructorD,
2808 Scope *S,
2809 CXXScopeSpec &SS,
2810 IdentifierInfo *MemberOrBase,
2811 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002812 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002813 SourceLocation IdLoc,
2814 Expr *InitList,
2815 SourceLocation EllipsisLoc) {
2816 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002817 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002818 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002819}
2820
2821/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002822MemInitResult
John McCall48871652010-08-21 09:40:31 +00002823Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002824 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002825 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002826 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002827 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002828 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002829 SourceLocation IdLoc,
2830 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002831 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002832 SourceLocation RParenLoc,
2833 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002834 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002835 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002836 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002837 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002838}
2839
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002840namespace {
2841
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002842// Callback to only accept typo corrections that can be a valid C++ member
2843// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002844class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002845public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002846 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2847 : ClassDecl(ClassDecl) {}
2848
Craig Toppera798a9d2014-03-02 09:32:10 +00002849 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002850 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2851 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2852 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002853 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002854 }
2855 return false;
2856 }
2857
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002858private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002859 CXXRecordDecl *ClassDecl;
2860};
2861
2862}
2863
Sebastian Redla74948d2011-09-24 17:48:25 +00002864/// \brief Handle a C++ member initializer.
2865MemInitResult
2866Sema::BuildMemInitializer(Decl *ConstructorD,
2867 Scope *S,
2868 CXXScopeSpec &SS,
2869 IdentifierInfo *MemberOrBase,
2870 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002871 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002872 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002873 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002874 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002875 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2876 if (!Res.isUsable())
2877 return true;
2878 Init = Res.get();
2879
Douglas Gregor71a57182009-06-22 23:20:33 +00002880 if (!ConstructorD)
2881 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002882
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002883 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002884
2885 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002886 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002887 if (!Constructor) {
2888 // The user wrote a constructor initializer on a function that is
2889 // not a C++ constructor. Ignore the error for now, because we may
2890 // have more member initializers coming; we'll diagnose it just
2891 // once in ActOnMemInitializers.
2892 return true;
2893 }
2894
2895 CXXRecordDecl *ClassDecl = Constructor->getParent();
2896
2897 // C++ [class.base.init]p2:
2898 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002899 // constructor's class and, if not found in that scope, are looked
2900 // up in the scope containing the constructor's definition.
2901 // [Note: if the constructor's class contains a member with the
2902 // same name as a direct or virtual base class of the class, a
2903 // mem-initializer-id naming the member or base class and composed
2904 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002905 // mem-initializer-id for the hidden base class may be specified
2906 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002907 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002908 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002909 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002910 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002911 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002912 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2913 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002914 if (EllipsisLoc.isValid())
2915 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002916 << MemberOrBase
2917 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002918
Sebastian Redla9351792012-02-11 23:51:47 +00002919 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002920 }
Francois Pichetd583da02010-12-04 09:14:42 +00002921 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002922 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002923 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002924 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002925 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002926
2927 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002928 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002929 } else if (DS.getTypeSpecType() == TST_decltype) {
2930 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002931 } else {
2932 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2933 LookupParsedName(R, S, &SS);
2934
2935 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2936 if (!TyD) {
2937 if (R.isAmbiguous()) return true;
2938
John McCallda6841b2010-04-09 19:01:14 +00002939 // We don't want access-control diagnostics here.
2940 R.suppressDiagnostics();
2941
Douglas Gregora3b624a2010-01-19 06:46:48 +00002942 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2943 bool NotUnknownSpecialization = false;
2944 DeclContext *DC = computeDeclContext(SS, false);
2945 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2946 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2947
2948 if (!NotUnknownSpecialization) {
2949 // When the scope specifier can refer to a member of an unknown
2950 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002951 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2952 SS.getWithLocInContext(Context),
2953 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002954 if (BaseType.isNull())
2955 return true;
2956
Douglas Gregora3b624a2010-01-19 06:46:48 +00002957 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002958 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002959 }
2960 }
2961
Douglas Gregor15e77a22009-12-31 09:10:24 +00002962 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002963 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002964 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002965 (Corr = CorrectTypo(
2966 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2967 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2968 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002969 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002970 // We have found a non-static data member with a similar
2971 // name to what was typed; complain and initialize that
2972 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002973 diagnoseTypo(Corr,
2974 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2975 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002976 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002977 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002978 const CXXBaseSpecifier *DirectBaseSpec;
2979 const CXXBaseSpecifier *VirtualBaseSpec;
2980 if (FindBaseInitializer(*this, ClassDecl,
2981 Context.getTypeDeclType(Type),
2982 DirectBaseSpec, VirtualBaseSpec)) {
2983 // We have found a direct or virtual base class with a
2984 // similar name to what was typed; complain and initialize
2985 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002986 diagnoseTypo(Corr,
2987 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2988 << MemberOrBase << false,
2989 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002990
Richard Smithf9b15102013-08-17 00:46:16 +00002991 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2992 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002993 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002994 diag::note_base_class_specified_here)
2995 << BaseSpec->getType()
2996 << BaseSpec->getSourceRange();
2997
Douglas Gregor15e77a22009-12-31 09:10:24 +00002998 TyD = Type;
2999 }
3000 }
3001 }
3002
Douglas Gregora3b624a2010-01-19 06:46:48 +00003003 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003004 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003005 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003006 return true;
3007 }
John McCallb5a0d312009-12-21 10:41:20 +00003008 }
3009
Douglas Gregora3b624a2010-01-19 06:46:48 +00003010 if (BaseType.isNull()) {
3011 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003012 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00003013 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00003014 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00003015 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3016 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00003017 }
3018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
John McCallbcd03502009-12-07 02:54:59 +00003020 if (!TInfo)
3021 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003022
Sebastian Redla9351792012-02-11 23:51:47 +00003023 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003024}
3025
Chandler Carruth599deef2011-09-03 01:14:15 +00003026/// Checks a member initializer expression for cases where reference (or
3027/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003028static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3029 Expr *Init,
3030 SourceLocation IdLoc) {
3031 QualType MemberTy = Member->getType();
3032
3033 // We only handle pointers and references currently.
3034 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3035 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3036 return;
3037
3038 const bool IsPointer = MemberTy->isPointerType();
3039 if (IsPointer) {
3040 if (const UnaryOperator *Op
3041 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3042 // The only case we're worried about with pointers requires taking the
3043 // address.
3044 if (Op->getOpcode() != UO_AddrOf)
3045 return;
3046
3047 Init = Op->getSubExpr();
3048 } else {
3049 // We only handle address-of expression initializers for pointers.
3050 return;
3051 }
3052 }
3053
Richard Smithe3b28bc2013-06-12 21:51:50 +00003054 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003055 // We only warn when referring to a non-reference parameter declaration.
3056 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3057 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003058 return;
3059
3060 S.Diag(Init->getExprLoc(),
3061 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3062 : diag::warn_bind_ref_member_to_parameter)
3063 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003064 } else {
3065 // Other initializers are fine.
3066 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003067 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003068
3069 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3070 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003071}
3072
John McCallfaf5fb42010-08-26 23:41:50 +00003073MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003074Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003075 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003076 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3077 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3078 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003079 "Member must be a FieldDecl or IndirectFieldDecl");
3080
Sebastian Redla9351792012-02-11 23:51:47 +00003081 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003082 return true;
3083
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003084 if (Member->isInvalidDecl())
3085 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003086
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003087 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003088 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003089 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003090 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003091 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003092 } else {
3093 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003094 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003095 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003096
Sebastian Redla9351792012-02-11 23:51:47 +00003097 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003098
Sebastian Redla9351792012-02-11 23:51:47 +00003099 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003100 // Can't check initialization for a member of dependent type or when
3101 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003102 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003103 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003104 bool InitList = false;
3105 if (isa<InitListExpr>(Init)) {
3106 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003107 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003108 }
3109
Chandler Carruthd44c3102010-12-06 09:23:57 +00003110 // Initialize the member.
3111 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003112 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3113 : InitializedEntity::InitializeMember(IndirectMember,
3114 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003115 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003116 InitList ? InitializationKind::CreateDirectList(IdLoc)
3117 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3118 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003119
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003120 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003121 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3122 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003123 if (MemberInit.isInvalid())
3124 return true;
3125
Richard Smith736a9472013-06-12 20:42:33 +00003126 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3127
Richard Smith945f8d32013-01-14 22:39:08 +00003128 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003129 // The initialization of each base and member constitutes a
3130 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003131 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003132 if (MemberInit.isInvalid())
3133 return true;
3134
Richard Smithd59b8322012-12-19 01:39:02 +00003135 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003136 }
3137
Chandler Carruthd44c3102010-12-06 09:23:57 +00003138 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003139 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3140 InitRange.getBegin(), Init,
3141 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003142 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003143 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3144 InitRange.getBegin(), Init,
3145 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003146 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003147}
3148
John McCallfaf5fb42010-08-26 23:41:50 +00003149MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003150Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003151 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003152 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003153 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003154 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003155 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003156 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003157
Sebastian Redl0501c632012-02-12 16:37:36 +00003158 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003159 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003160 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3161 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003162 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003163 }
3164
Sebastian Redla9351792012-02-11 23:51:47 +00003165 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003166 // Initialize the object.
3167 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3168 QualType(ClassDecl->getTypeForDecl(), 0));
3169 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003170 InitList ? InitializationKind::CreateDirectList(NameLoc)
3171 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3172 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003173 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003174 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003175 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003176 if (DelegationInit.isInvalid())
3177 return true;
3178
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003179 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3180 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003181
Richard Smith945f8d32013-01-14 22:39:08 +00003182 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003183 // The initialization of each base and member constitutes a
3184 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003185 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3186 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003187 if (DelegationInit.isInvalid())
3188 return true;
3189
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003190 // If we are in a dependent context, template instantiation will
3191 // perform this type-checking again. Just save the arguments that we
3192 // received in a ParenListExpr.
3193 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3194 // of the information that we have about the base
3195 // initializer. However, deconstructing the ASTs is a dicey process,
3196 // and this approach is far more likely to get the corner cases right.
3197 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003198 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003199
Sebastian Redla9351792012-02-11 23:51:47 +00003200 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003201 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003202 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003203}
3204
3205MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003206Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003207 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003208 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003209 SourceLocation BaseLoc
3210 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003211
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003212 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3213 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3214 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3215
3216 // C++ [class.base.init]p2:
3217 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003218 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003219 // of that class, the mem-initializer is ill-formed. A
3220 // mem-initializer-list can initialize a base class using any
3221 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003222 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003223
Sebastian Redla9351792012-02-11 23:51:47 +00003224 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003225 if (EllipsisLoc.isValid()) {
3226 // This is a pack expansion.
3227 if (!BaseType->containsUnexpandedParameterPack()) {
3228 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003229 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003230
Douglas Gregor44e7df62011-01-04 00:32:56 +00003231 EllipsisLoc = SourceLocation();
3232 }
3233 } else {
3234 // Check for any unexpanded parameter packs.
3235 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3236 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003237
Sebastian Redla9351792012-02-11 23:51:47 +00003238 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003239 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003240 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003241
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003242 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003243 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3244 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003245 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003246 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3247 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003248 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003249
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003250 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3251 VirtualBaseSpec);
3252
3253 // C++ [base.class.init]p2:
3254 // Unless the mem-initializer-id names a nonstatic data member of the
3255 // constructor's class or a direct or virtual base of that class, the
3256 // mem-initializer is ill-formed.
3257 if (!DirectBaseSpec && !VirtualBaseSpec) {
3258 // If the class has any dependent bases, then it's possible that
3259 // one of those types will resolve to the same type as
3260 // BaseType. Therefore, just treat this as a dependent base
3261 // class initialization. FIXME: Should we try to check the
3262 // initialization anyway? It seems odd.
3263 if (ClassDecl->hasAnyDependentBases())
3264 Dependent = true;
3265 else
3266 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3267 << BaseType << Context.getTypeDeclType(ClassDecl)
3268 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3269 }
3270 }
3271
3272 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003273 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003274
Sebastian Redla74948d2011-09-24 17:48:25 +00003275 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3276 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003277 InitRange.getBegin(), Init,
3278 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003279 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003280
3281 // C++ [base.class.init]p2:
3282 // If a mem-initializer-id is ambiguous because it designates both
3283 // a direct non-virtual base class and an inherited virtual base
3284 // class, the mem-initializer is ill-formed.
3285 if (DirectBaseSpec && VirtualBaseSpec)
3286 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003287 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003288
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003289 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003290 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003291 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003292
3293 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003294 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003295 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003296 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003297 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003298 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003299 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003300
3301 InitializedEntity BaseEntity =
3302 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3303 InitializationKind Kind =
3304 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3305 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3306 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003307 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003309 if (BaseInit.isInvalid())
3310 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003311
Richard Smith945f8d32013-01-14 22:39:08 +00003312 // C++11 [class.base.init]p7:
3313 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003314 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003315 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003316 if (BaseInit.isInvalid())
3317 return true;
3318
3319 // If we are in a dependent context, template instantiation will
3320 // perform this type-checking again. Just save the arguments that we
3321 // received in a ParenListExpr.
3322 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3323 // of the information that we have about the base
3324 // initializer. However, deconstructing the ASTs is a dicey process,
3325 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003326 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003327 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003328
Alexis Hunt1d792652011-01-08 20:30:50 +00003329 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003330 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003331 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003332 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003333 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003334}
3335
Sebastian Redl22653ba2011-08-30 19:58:05 +00003336// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003337static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3338 if (T.isNull()) T = E->getType();
3339 QualType TargetType = SemaRef.BuildReferenceType(
3340 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003341 SourceLocation ExprLoc = E->getLocStart();
3342 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3343 TargetType, ExprLoc);
3344
3345 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3346 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003347 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003348}
3349
Anders Carlsson1b00e242010-04-23 03:10:23 +00003350/// ImplicitInitializerKind - How an implicit base or member initializer should
3351/// initialize its base or member.
3352enum ImplicitInitializerKind {
3353 IIK_Default,
3354 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003355 IIK_Move,
3356 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003357};
3358
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003359static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003360BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003361 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003362 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003363 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003364 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003365 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003366 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3367 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003368
John McCalldadc5752010-08-24 06:29:42 +00003369 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003370
3371 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003372 case IIK_Inherit: {
3373 const CXXRecordDecl *Inherited =
3374 Constructor->getInheritedConstructor()->getParent();
3375 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3376 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3377 // C++11 [class.inhctor]p8:
3378 // Each expression in the expression-list is of the form
3379 // static_cast<T&&>(p), where p is the name of the corresponding
3380 // constructor parameter and T is the declared type of p.
3381 SmallVector<Expr*, 16> Args;
3382 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3383 ParmVarDecl *PD = Constructor->getParamDecl(I);
3384 ExprResult ArgExpr =
3385 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3386 VK_LValue, SourceLocation());
3387 if (ArgExpr.isInvalid())
3388 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003389 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003390 }
3391
3392 InitializationKind InitKind = InitializationKind::CreateDirect(
3393 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003394 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003395 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3396 break;
3397 }
3398 }
3399 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003400 case IIK_Default: {
3401 InitializationKind InitKind
3402 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003403 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3404 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003405 break;
3406 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003407
Sebastian Redl22653ba2011-08-30 19:58:05 +00003408 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003409 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003410 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003411 ParmVarDecl *Param = Constructor->getParamDecl(0);
3412 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003413
Anders Carlsson1b00e242010-04-23 03:10:23 +00003414 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003415 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003416 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003417 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003418 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003419
Eli Friedmanfa0df832012-02-02 03:46:19 +00003420 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3421
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003422 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003423 QualType ArgTy =
3424 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3425 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003426
Sebastian Redl22653ba2011-08-30 19:58:05 +00003427 if (Moving) {
3428 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3429 }
3430
John McCallcf142162010-08-07 06:22:56 +00003431 CXXCastPath BasePath;
3432 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003433 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3434 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003435 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003436 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003437
Anders Carlsson1b00e242010-04-23 03:10:23 +00003438 InitializationKind InitKind
3439 = InitializationKind::CreateDirect(Constructor->getLocation(),
3440 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003441 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3442 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003443 break;
3444 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003445 }
John McCallb268a282010-08-23 23:25:46 +00003446
Douglas Gregora40433a2010-12-07 00:41:46 +00003447 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003448 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003449 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003450
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003451 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003452 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003453 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3454 SourceLocation()),
3455 BaseSpec->isVirtual(),
3456 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003457 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003458 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003459 SourceLocation());
3460
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003461 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003462}
3463
Sebastian Redl22653ba2011-08-30 19:58:05 +00003464static bool RefersToRValueRef(Expr *MemRef) {
3465 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3466 return Referenced->getType()->isRValueReferenceType();
3467}
3468
Anders Carlsson3c1db572010-04-23 02:15:47 +00003469static bool
3470BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003471 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003472 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003473 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003474 if (Field->isInvalidDecl())
3475 return true;
3476
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003477 SourceLocation Loc = Constructor->getLocation();
3478
Sebastian Redl22653ba2011-08-30 19:58:05 +00003479 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3480 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003481 ParmVarDecl *Param = Constructor->getParamDecl(0);
3482 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003483
3484 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003485 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3486 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003487
Anders Carlsson423f5d82010-04-23 16:04:08 +00003488 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003489 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003490 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003491 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003492
Eli Friedmanfa0df832012-02-02 03:46:19 +00003493 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3494
Sebastian Redl22653ba2011-08-30 19:58:05 +00003495 if (Moving) {
3496 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3497 }
3498
Douglas Gregor94f9a482010-05-05 05:51:00 +00003499 // Build a reference to this field within the parameter.
3500 CXXScopeSpec SS;
3501 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3502 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003503 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3504 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003505 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003506 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003507 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003508 ParamType, Loc,
3509 /*IsArrow=*/false,
3510 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003511 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003513 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003514 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003515 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003516 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003517
3518 // C++11 [class.copy]p15:
3519 // - if a member m has rvalue reference type T&&, it is direct-initialized
3520 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003521 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003522 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003523 }
3524
Douglas Gregor94f9a482010-05-05 05:51:00 +00003525 // When the field we are copying is an array, create index variables for
3526 // each dimension of the array. We use these index variables to subscript
3527 // the source array, and other clients (e.g., CodeGen) will perform the
3528 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003529 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003530 QualType BaseType = Field->getType();
3531 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003532 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003533 while (const ConstantArrayType *Array
3534 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003535 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003536 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003537 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003538 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003539 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003540 llvm::raw_svector_ostream OS(Str);
3541 OS << "__i" << IndexVariables.size();
3542 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3543 }
3544 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003545 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003546 IterationVarName, SizeType,
3547 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003548 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003549 IndexVariables.push_back(IterationVar);
3550
3551 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003552 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003553 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003554 assert(!IterationVarRef.isInvalid() &&
3555 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003556 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003557 assert(!IterationVarRef.isInvalid() &&
3558 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003559
Douglas Gregor94f9a482010-05-05 05:51:00 +00003560 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003561 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3562 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003563 Loc);
3564 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003565 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003566
Douglas Gregor94f9a482010-05-05 05:51:00 +00003567 BaseType = Array->getElementType();
3568 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003569
3570 // The array subscript expression is an lvalue, which is wrong for moving.
3571 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003572 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003573
Douglas Gregor94f9a482010-05-05 05:51:00 +00003574 // Construct the entity that we will be initializing. For an array, this
3575 // will be first element in the array, which may require several levels
3576 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003577 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003578 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003579 if (Indirect)
3580 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3581 else
3582 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003583 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3584 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3585 0,
3586 Entities.back()));
3587
3588 // Direct-initialize to use the copy constructor.
3589 InitializationKind InitKind =
3590 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3591
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003592 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00003593 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3594 CtorArgE);
3595
John McCalldadc5752010-08-24 06:29:42 +00003596 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003597 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003598 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003599 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003600 if (MemberInit.isInvalid())
3601 return true;
3602
Douglas Gregor493627b2011-08-10 15:22:55 +00003603 if (Indirect) {
3604 assert(IndexVariables.size() == 0 &&
3605 "Indirect field improperly initialized");
3606 CXXMemberInit
3607 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3608 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003609 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003610 Loc);
3611 } else
3612 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003613 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003614 Loc,
3615 IndexVariables.data(),
3616 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003617 return false;
3618 }
3619
Richard Smithc2bc61b2013-03-18 21:12:30 +00003620 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3621 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003622
Anders Carlsson3c1db572010-04-23 02:15:47 +00003623 QualType FieldBaseElementType =
3624 SemaRef.Context.getBaseElementType(Field->getType());
3625
Anders Carlsson3c1db572010-04-23 02:15:47 +00003626 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003627 InitializedEntity InitEntity
3628 = Indirect? InitializedEntity::InitializeMember(Indirect)
3629 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003630 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003631 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003632
3633 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3634 ExprResult MemberInit =
3635 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003636
Douglas Gregora40433a2010-12-07 00:41:46 +00003637 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003638 if (MemberInit.isInvalid())
3639 return true;
3640
Douglas Gregor493627b2011-08-10 15:22:55 +00003641 if (Indirect)
3642 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3643 Indirect, Loc,
3644 Loc,
3645 MemberInit.get(),
3646 Loc);
3647 else
3648 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3649 Field, Loc, Loc,
3650 MemberInit.get(),
3651 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003652 return false;
3653 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003654
Alexis Hunt8b455182011-05-17 00:19:05 +00003655 if (!Field->getParent()->isUnion()) {
3656 if (FieldBaseElementType->isReferenceType()) {
3657 SemaRef.Diag(Constructor->getLocation(),
3658 diag::err_uninitialized_member_in_ctor)
3659 << (int)Constructor->isImplicit()
3660 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3661 << 0 << Field->getDeclName();
3662 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3663 return true;
3664 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003665
Alexis Hunt8b455182011-05-17 00:19:05 +00003666 if (FieldBaseElementType.isConstQualified()) {
3667 SemaRef.Diag(Constructor->getLocation(),
3668 diag::err_uninitialized_member_in_ctor)
3669 << (int)Constructor->isImplicit()
3670 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3671 << 1 << Field->getDeclName();
3672 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3673 return true;
3674 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003675 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003676
David Blaikiebbafb8a2012-03-11 07:00:24 +00003677 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003678 FieldBaseElementType->isObjCRetainableType() &&
3679 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3680 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003681 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003682 // Default-initialize Objective-C pointers to NULL.
3683 CXXMemberInit
3684 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3685 Loc, Loc,
3686 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3687 Loc);
3688 return false;
3689 }
3690
Anders Carlsson3c1db572010-04-23 02:15:47 +00003691 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003692 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003693 return false;
3694}
John McCallbc83b3f2010-05-20 23:23:51 +00003695
3696namespace {
3697struct BaseAndFieldInfo {
3698 Sema &S;
3699 CXXConstructorDecl *Ctor;
3700 bool AnyErrorsInInits;
3701 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003702 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003703 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003704 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003705
3706 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3707 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003708 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3709 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003710 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003711 else if (Generated && Ctor->isMoveConstructor())
3712 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003713 else if (Ctor->getInheritedConstructor())
3714 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003715 else
3716 IIK = IIK_Default;
3717 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003718
3719 bool isImplicitCopyOrMove() const {
3720 switch (IIK) {
3721 case IIK_Copy:
3722 case IIK_Move:
3723 return true;
3724
3725 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003726 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003727 return false;
3728 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003729
3730 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003731 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003732
3733 bool addFieldInitializer(CXXCtorInitializer *Init) {
3734 AllToInit.push_back(Init);
3735
3736 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003737 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003738 S.UnusedPrivateFields.remove(Init->getAnyMember());
3739
3740 return false;
3741 }
John McCallbc83b3f2010-05-20 23:23:51 +00003742
Richard Smithab44d5b2013-12-10 08:25:00 +00003743 bool isInactiveUnionMember(FieldDecl *Field) {
3744 RecordDecl *Record = Field->getParent();
3745 if (!Record->isUnion())
3746 return false;
3747
Richard Smith8d183852013-12-10 20:56:03 +00003748 if (FieldDecl *Active =
3749 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003750 return Active != Field->getCanonicalDecl();
3751
3752 // In an implicit copy or move constructor, ignore any in-class initializer.
3753 if (isImplicitCopyOrMove())
3754 return true;
3755
3756 // If there's no explicit initialization, the field is active only if it
3757 // has an in-class initializer...
3758 if (Field->hasInClassInitializer())
3759 return false;
3760 // ... or it's an anonymous struct or union whose class has an in-class
3761 // initializer.
3762 if (!Field->isAnonymousStructOrUnion())
3763 return true;
3764 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3765 return !FieldRD->hasInClassInitializer();
3766 }
3767
3768 /// \brief Determine whether the given field is, or is within, a union member
3769 /// that is inactive (because there was an initializer given for a different
3770 /// member of the union, or because the union was not initialized at all).
3771 bool isWithinInactiveUnionMember(FieldDecl *Field,
3772 IndirectFieldDecl *Indirect) {
3773 if (!Indirect)
3774 return isInactiveUnionMember(Field);
3775
Aaron Ballman29c94602014-03-07 18:36:15 +00003776 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003777 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003778 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003779 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003780 }
3781 return false;
3782 }
3783};
Richard Smithc94ec842011-09-19 13:34:43 +00003784}
3785
Douglas Gregor10f939c2011-11-02 23:04:16 +00003786/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3787/// array type.
3788static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3789 if (T->isIncompleteArrayType())
3790 return true;
3791
3792 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3793 if (!ArrayT->getSize())
3794 return true;
3795
3796 T = ArrayT->getElementType();
3797 }
3798
3799 return false;
3800}
3801
Richard Smith938f40b2011-06-11 17:19:42 +00003802static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003803 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003804 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003805 if (Field->isInvalidDecl())
3806 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003807
Chandler Carruth139e9622010-06-30 02:59:29 +00003808 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003809 if (CXXCtorInitializer *Init =
3810 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003811 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003812
Richard Smithab44d5b2013-12-10 08:25:00 +00003813 // C++11 [class.base.init]p8:
3814 // if the entity is a non-static data member that has a
3815 // brace-or-equal-initializer and either
3816 // -- the constructor's class is a union and no other variant member of that
3817 // union is designated by a mem-initializer-id or
3818 // -- the constructor's class is not a union, and, if the entity is a member
3819 // of an anonymous union, no other member of that union is designated by
3820 // a mem-initializer-id,
3821 // the entity is initialized as specified in [dcl.init].
3822 //
3823 // We also apply the same rules to handle anonymous structs within anonymous
3824 // unions.
3825 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3826 return false;
3827
Douglas Gregor7db3e952011-11-28 20:03:15 +00003828 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003829 ExprResult DIE =
3830 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3831 if (DIE.isInvalid())
3832 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003833 CXXCtorInitializer *Init;
3834 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003835 Init = new (SemaRef.Context)
3836 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3837 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003838 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003839 Init = new (SemaRef.Context)
3840 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3841 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003842 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003843 }
3844
Douglas Gregor10f939c2011-11-02 23:04:16 +00003845 // Don't initialize incomplete or zero-length arrays.
3846 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3847 return false;
3848
John McCallbc83b3f2010-05-20 23:23:51 +00003849 // Don't try to build an implicit initializer if there were semantic
3850 // errors in any of the initializers (and therefore we might be
3851 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003852 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003853 return false;
3854
Craig Topperc3ec1492014-05-26 06:22:03 +00003855 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003856 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3857 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003858 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003859
Richard Smith0a8cfc72012-08-07 21:30:42 +00003860 if (!Init)
3861 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003862
Richard Smith0a8cfc72012-08-07 21:30:42 +00003863 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003864}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003865
3866bool
3867Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3868 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003869 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003870 Constructor->setNumCtorInitializers(1);
3871 CXXCtorInitializer **initializer =
3872 new (Context) CXXCtorInitializer*[1];
3873 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3874 Constructor->setCtorInitializers(initializer);
3875
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003876 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003877 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003878 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3879 }
3880
Alexis Hunte2622992011-05-05 00:05:47 +00003881 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003882
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003883 DiagnoseUninitializedFields(*this, Constructor);
3884
Alexis Hunt61bc1732011-05-01 07:04:31 +00003885 return false;
3886}
Douglas Gregor493627b2011-08-10 15:22:55 +00003887
David Blaikie3fc2f912013-01-17 05:26:25 +00003888bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3889 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003890 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003891 // Just store the initializers as written, they will be checked during
3892 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003893 if (!Initializers.empty()) {
3894 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003895 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003896 new (Context) CXXCtorInitializer*[Initializers.size()];
3897 memcpy(baseOrMemberInitializers, Initializers.data(),
3898 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003899 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003900 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003901
3902 // Let template instantiation know whether we had errors.
3903 if (AnyErrors)
3904 Constructor->setInvalidDecl();
3905
Anders Carlssondb0a9652010-04-02 06:26:44 +00003906 return false;
3907 }
3908
John McCallbc83b3f2010-05-20 23:23:51 +00003909 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003910
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003911 // We need to build the initializer AST according to order of construction
3912 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003913 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003914 if (!ClassDecl)
3915 return true;
3916
Eli Friedman9cf6b592009-11-09 19:20:36 +00003917 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003918
David Blaikie3fc2f912013-01-17 05:26:25 +00003919 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003920 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003921
Anders Carlssondb0a9652010-04-02 06:26:44 +00003922 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003923 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003924 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003925 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003926
3927 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003928 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003929 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003930 if (FD && FD->getParent()->isUnion())
3931 Info.ActiveUnionMember.insert(std::make_pair(
3932 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3933 }
3934 } else if (FieldDecl *FD = Member->getMember()) {
3935 if (FD->getParent()->isUnion())
3936 Info.ActiveUnionMember.insert(std::make_pair(
3937 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3938 }
3939 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003940 }
3941
Anders Carlsson43c64af2010-04-21 19:52:01 +00003942 // Keep track of the direct virtual bases.
3943 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003944 for (auto &I : ClassDecl->bases()) {
3945 if (I.isVirtual())
3946 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003947 }
3948
Anders Carlssondb0a9652010-04-02 06:26:44 +00003949 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003950 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003951 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003952 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003953 // [class.base.init]p7, per DR257:
3954 // A mem-initializer where the mem-initializer-id names a virtual base
3955 // class is ignored during execution of a constructor of any class that
3956 // is not the most derived class.
3957 if (ClassDecl->isAbstract()) {
3958 // FIXME: Provide a fixit to remove the base specifier. This requires
3959 // tracking the location of the associated comma for a base specifier.
3960 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003961 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003962 DiagnoseAbstractType(ClassDecl);
3963 }
3964
John McCallbc83b3f2010-05-20 23:23:51 +00003965 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003966 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3967 // [class.base.init]p8, per DR257:
3968 // If a given [...] base class is not named by a mem-initializer-id
3969 // [...] and the entity is not a virtual base class of an abstract
3970 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003971 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003972 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003973 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003974 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003975 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003976 HadError = true;
3977 continue;
3978 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003979
John McCallbc83b3f2010-05-20 23:23:51 +00003980 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003981 }
3982 }
Mike Stump11289f42009-09-09 15:08:12 +00003983
John McCallbc83b3f2010-05-20 23:23:51 +00003984 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003985 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003986 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003987 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003988 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003989
Alexis Hunt1d792652011-01-08 20:30:50 +00003990 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003991 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003992 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003993 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003994 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003995 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003996 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003997 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003998 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003999 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004000 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004001
John McCallbc83b3f2010-05-20 23:23:51 +00004002 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004003 }
4004 }
Mike Stump11289f42009-09-09 15:08:12 +00004005
John McCallbc83b3f2010-05-20 23:23:51 +00004006 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004007 for (auto *Mem : ClassDecl->decls()) {
4008 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004009 // C++ [class.bit]p2:
4010 // A declaration for a bit-field that omits the identifier declares an
4011 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4012 // initialized.
4013 if (F->isUnnamedBitfield())
4014 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004015
Sebastian Redl22653ba2011-08-30 19:58:05 +00004016 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004017 // handle anonymous struct/union fields based on their individual
4018 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004019 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004020 continue;
4021
4022 if (CollectFieldInitializer(*this, Info, F))
4023 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004024 continue;
4025 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004026
4027 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004028 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004029 continue;
4030
Aaron Ballman629afae2014-03-07 19:56:05 +00004031 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004032 if (F->getType()->isIncompleteArrayType()) {
4033 assert(ClassDecl->hasFlexibleArrayMember() &&
4034 "Incomplete array type is not valid");
4035 continue;
4036 }
4037
Douglas Gregor493627b2011-08-10 15:22:55 +00004038 // Initialize each field of an anonymous struct individually.
4039 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4040 HadError = true;
4041
4042 continue;
4043 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004044 }
Mike Stump11289f42009-09-09 15:08:12 +00004045
David Blaikie3fc2f912013-01-17 05:26:25 +00004046 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004047 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004048 Constructor->setNumCtorInitializers(NumInitializers);
4049 CXXCtorInitializer **baseOrMemberInitializers =
4050 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004051 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004052 NumInitializers * sizeof(CXXCtorInitializer*));
4053 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004054
John McCalla6309952010-03-16 21:39:52 +00004055 // Constructors implicitly reference the base and member
4056 // destructors.
4057 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4058 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004059 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004060
4061 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004062}
4063
David Blaikieb61b8152013-01-17 08:49:22 +00004064static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004065 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004066 const RecordDecl *RD = RT->getDecl();
4067 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004068 for (auto *Field : RD->fields())
4069 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004070 return;
4071 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004072 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004073 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004074}
4075
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004076static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4077 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004078}
4079
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004080static const void *GetKeyForMember(ASTContext &Context,
4081 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004082 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004083 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004084
Richard Smithcd45dbc2014-04-19 03:48:30 +00004085 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004086}
4087
David Blaikie3fc2f912013-01-17 05:26:25 +00004088static void DiagnoseBaseOrMemInitializerOrder(
4089 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4090 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004091 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004092 return;
Mike Stump11289f42009-09-09 15:08:12 +00004093
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004094 // Don't check initializers order unless the warning is enabled at the
4095 // location of at least one initializer.
4096 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004097 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004098 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004099 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4100 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004101 ShouldCheckOrder = true;
4102 break;
4103 }
4104 }
4105 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004106 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004107
John McCallbb7b6582010-04-10 07:37:23 +00004108 // Build the list of bases and members in the order that they'll
4109 // actually be initialized. The explicit initializers should be in
4110 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004111 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004112
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004113 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4114
John McCallbb7b6582010-04-10 07:37:23 +00004115 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004116 for (const auto &VBase : ClassDecl->vbases())
4117 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004118
John McCallbb7b6582010-04-10 07:37:23 +00004119 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004120 for (const auto &Base : ClassDecl->bases()) {
4121 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004122 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004123 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004124 }
Mike Stump11289f42009-09-09 15:08:12 +00004125
John McCallbb7b6582010-04-10 07:37:23 +00004126 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004127 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004128 if (Field->isUnnamedBitfield())
4129 continue;
4130
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004131 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004132 }
4133
John McCallbb7b6582010-04-10 07:37:23 +00004134 unsigned NumIdealInits = IdealInitKeys.size();
4135 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004136
Craig Topperc3ec1492014-05-26 06:22:03 +00004137 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004138 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004139 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004140 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004141
4142 // Scan forward to try to find this initializer in the idealized
4143 // initializers list.
4144 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4145 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004146 break;
John McCallbb7b6582010-04-10 07:37:23 +00004147
4148 // If we didn't find this initializer, it must be because we
4149 // scanned past it on a previous iteration. That can only
4150 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004151 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004152 Sema::SemaDiagnosticBuilder D =
4153 SemaRef.Diag(PrevInit->getSourceLocation(),
4154 diag::warn_initializer_out_of_order);
4155
Francois Pichetd583da02010-12-04 09:14:42 +00004156 if (PrevInit->isAnyMemberInitializer())
4157 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004158 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004159 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004160
Francois Pichetd583da02010-12-04 09:14:42 +00004161 if (Init->isAnyMemberInitializer())
4162 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004163 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004164 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004165
4166 // Move back to the initializer's location in the ideal list.
4167 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4168 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004169 break;
John McCallbb7b6582010-04-10 07:37:23 +00004170
4171 assert(IdealIndex != NumIdealInits &&
4172 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004173 }
John McCallbb7b6582010-04-10 07:37:23 +00004174
4175 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004176 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004177}
4178
John McCall23eebd92010-04-10 09:28:51 +00004179namespace {
4180bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004181 CXXCtorInitializer *Init,
4182 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004183 if (!PrevInit) {
4184 PrevInit = Init;
4185 return false;
4186 }
4187
Douglas Gregorea306a12013-03-25 23:28:23 +00004188 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004189 S.Diag(Init->getSourceLocation(),
4190 diag::err_multiple_mem_initialization)
4191 << Field->getDeclName()
4192 << Init->getSourceRange();
4193 else {
John McCall424cec92011-01-19 06:33:43 +00004194 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004195 assert(BaseClass && "neither field nor base");
4196 S.Diag(Init->getSourceLocation(),
4197 diag::err_multiple_base_initialization)
4198 << QualType(BaseClass, 0)
4199 << Init->getSourceRange();
4200 }
4201 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4202 << 0 << PrevInit->getSourceRange();
4203
4204 return true;
4205}
4206
Alexis Hunt1d792652011-01-08 20:30:50 +00004207typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004208typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4209
4210bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004211 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004212 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004213 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004214 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004215 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004216
4217 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004218 if (Parent->isUnion()) {
4219 UnionEntry &En = Unions[Parent];
4220 if (En.first && En.first != Child) {
4221 S.Diag(Init->getSourceLocation(),
4222 diag::err_multiple_mem_union_initialization)
4223 << Field->getDeclName()
4224 << Init->getSourceRange();
4225 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4226 << 0 << En.second->getSourceRange();
4227 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004228 }
4229 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004230 En.first = Child;
4231 En.second = Init;
4232 }
David Blaikie0f65d592011-11-17 06:01:57 +00004233 if (!Parent->isAnonymousStructOrUnion())
4234 return false;
John McCall23eebd92010-04-10 09:28:51 +00004235 }
4236
4237 Child = Parent;
4238 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004239 }
John McCall23eebd92010-04-10 09:28:51 +00004240
4241 return false;
4242}
4243}
4244
Anders Carlssone857b292010-04-02 03:37:03 +00004245/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004246void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004247 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004248 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004249 bool AnyErrors) {
4250 if (!ConstructorDecl)
4251 return;
4252
4253 AdjustDeclIfTemplate(ConstructorDecl);
4254
4255 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004256 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004257
4258 if (!Constructor) {
4259 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4260 return;
4261 }
4262
John McCall23eebd92010-04-10 09:28:51 +00004263 // Mapping for the duplicate initializers check.
4264 // For member initializers, this is keyed with a FieldDecl*.
4265 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004266 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004267
4268 // Mapping for the inconsistent anonymous-union initializers check.
4269 RedundantUnionMap MemberUnions;
4270
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004271 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004272 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004273 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004274
Abramo Bagnara341d7832010-05-26 18:09:23 +00004275 // Set the source order index.
4276 Init->setSourceOrder(i);
4277
Francois Pichetd583da02010-12-04 09:14:42 +00004278 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004279 const void *Key = GetKeyForMember(Context, Init);
4280 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004281 CheckRedundantUnionInit(*this, Init, MemberUnions))
4282 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004283 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004284 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004285 if (CheckRedundantInit(*this, Init, Members[Key]))
4286 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004287 } else {
4288 assert(Init->isDelegatingInitializer());
4289 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004290 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004291 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004292 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004293 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004294 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004295 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004296 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004297 // Return immediately as the initializer is set.
4298 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004299 }
Anders Carlssone857b292010-04-02 03:37:03 +00004300 }
4301
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004302 if (HadError)
4303 return;
4304
David Blaikie3fc2f912013-01-17 05:26:25 +00004305 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004306
David Blaikie3fc2f912013-01-17 05:26:25 +00004307 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004308
Richard Trieuef64e942013-10-25 00:56:00 +00004309 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004310}
4311
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004312void
John McCalla6309952010-03-16 21:39:52 +00004313Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4314 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004315 // Ignore dependent contexts. Also ignore unions, since their members never
4316 // have destructors implicitly called.
4317 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004318 return;
John McCall1064d7e2010-03-16 05:22:47 +00004319
4320 // FIXME: all the access-control diagnostics are positioned on the
4321 // field/base declaration. That's probably good; that said, the
4322 // user might reasonably want to know why the destructor is being
4323 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004324
Anders Carlssondee9a302009-11-17 04:44:12 +00004325 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004326 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004327 if (Field->isInvalidDecl())
4328 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004329
4330 // Don't destroy incomplete or zero-length arrays.
4331 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4332 continue;
4333
Anders Carlssondee9a302009-11-17 04:44:12 +00004334 QualType FieldType = Context.getBaseElementType(Field->getType());
4335
4336 const RecordType* RT = FieldType->getAs<RecordType>();
4337 if (!RT)
4338 continue;
4339
4340 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004341 if (FieldClassDecl->isInvalidDecl())
4342 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004343 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004344 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004345 // The destructor for an implicit anonymous union member is never invoked.
4346 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4347 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004348
Douglas Gregore71edda2010-07-01 22:47:18 +00004349 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004350 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004351 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004352 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004353 << Field->getDeclName()
4354 << FieldType);
4355
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004356 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004357 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004358 }
4359
John McCall1064d7e2010-03-16 05:22:47 +00004360 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4361
Anders Carlssondee9a302009-11-17 04:44:12 +00004362 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004363 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004364 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004365 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004366
4367 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004368 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004369 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004370
John McCall1064d7e2010-03-16 05:22:47 +00004371 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004372 // If our base class is invalid, we probably can't get its dtor anyway.
4373 if (BaseClassDecl->isInvalidDecl())
4374 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004375 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004376 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004377
Douglas Gregore71edda2010-07-01 22:47:18 +00004378 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004379 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004380
4381 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004382 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004383 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004384 << Base.getType()
4385 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004386 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004387
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004388 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004389 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004390 }
4391
4392 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004393 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004394 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004395 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004396
4397 // Ignore direct virtual bases.
4398 if (DirectVirtualBases.count(RT))
4399 continue;
4400
John McCall1064d7e2010-03-16 05:22:47 +00004401 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004402 // If our base class is invalid, we probably can't get its dtor anyway.
4403 if (BaseClassDecl->isInvalidDecl())
4404 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004405 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004406 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004407
Douglas Gregore71edda2010-07-01 22:47:18 +00004408 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004409 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004410 if (CheckDestructorAccess(
4411 ClassDecl->getLocation(), Dtor,
4412 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004413 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004414 Context.getTypeDeclType(ClassDecl)) ==
4415 AR_accessible) {
4416 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004417 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004418 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004419 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004420 }
John McCall1064d7e2010-03-16 05:22:47 +00004421
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004422 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004423 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004424 }
4425}
4426
John McCall48871652010-08-21 09:40:31 +00004427void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004428 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004429 return;
Mike Stump11289f42009-09-09 15:08:12 +00004430
Mike Stump11289f42009-09-09 15:08:12 +00004431 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004432 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004433 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004434 DiagnoseUninitializedFields(*this, Constructor);
4435 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004436}
4437
Mike Stump11289f42009-09-09 15:08:12 +00004438bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004439 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004440 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4441 unsigned DiagID;
4442 AbstractDiagSelID SelID;
4443
4444 public:
4445 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4446 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004447
Craig Toppera798a9d2014-03-02 09:32:10 +00004448 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004449 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004450 if (SelID == -1)
4451 S.Diag(Loc, DiagID) << T;
4452 else
4453 S.Diag(Loc, DiagID) << SelID << T;
4454 }
4455 } Diagnoser(DiagID, SelID);
4456
4457 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004458}
4459
Anders Carlssoneabf7702009-08-27 00:13:57 +00004460bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004461 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004462 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004463 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004464
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004465 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004466 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004467
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004468 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004469 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004470 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004471 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004472
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004473 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004474 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004475 }
Mike Stump11289f42009-09-09 15:08:12 +00004476
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004477 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004478 if (!RT)
4479 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004480
John McCall67da35c2010-02-04 22:26:26 +00004481 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004482
John McCall02db245d2010-08-18 09:41:07 +00004483 // We can't answer whether something is abstract until it has a
4484 // definition. If it's currently being defined, we'll walk back
4485 // over all the declarations when we have a full definition.
4486 const CXXRecordDecl *Def = RD->getDefinition();
4487 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004488 return false;
4489
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004490 if (!RD->isAbstract())
4491 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004492
Douglas Gregorae298422012-05-04 17:09:59 +00004493 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004494 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004495
John McCall02db245d2010-08-18 09:41:07 +00004496 return true;
4497}
4498
4499void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4500 // Check if we've already emitted the list of pure virtual functions
4501 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004502 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004503 return;
Mike Stump11289f42009-09-09 15:08:12 +00004504
Richard Smithbc46e432013-07-22 02:56:56 +00004505 // If the diagnostic is suppressed, don't emit the notes. We're only
4506 // going to emit them once, so try to attach them to a diagnostic we're
4507 // actually going to show.
4508 if (Diags.isLastDiagnosticIgnored())
4509 return;
4510
Douglas Gregor4165bd62010-03-23 23:47:56 +00004511 CXXFinalOverriderMap FinalOverriders;
4512 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004513
Anders Carlssona2f74f32010-06-03 01:00:02 +00004514 // Keep a set of seen pure methods so we won't diagnose the same method
4515 // more than once.
4516 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4517
Douglas Gregor4165bd62010-03-23 23:47:56 +00004518 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4519 MEnd = FinalOverriders.end();
4520 M != MEnd;
4521 ++M) {
4522 for (OverridingMethods::iterator SO = M->second.begin(),
4523 SOEnd = M->second.end();
4524 SO != SOEnd; ++SO) {
4525 // C++ [class.abstract]p4:
4526 // A class is abstract if it contains or inherits at least one
4527 // pure virtual function for which the final overrider is pure
4528 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004529
Douglas Gregor4165bd62010-03-23 23:47:56 +00004530 //
4531 if (SO->second.size() != 1)
4532 continue;
4533
4534 if (!SO->second.front().Method->isPure())
4535 continue;
4536
David Blaikie82e95a32014-11-19 07:49:47 +00004537 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004538 continue;
4539
Douglas Gregor4165bd62010-03-23 23:47:56 +00004540 Diag(SO->second.front().Method->getLocation(),
4541 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004542 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004543 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004544 }
4545
4546 if (!PureVirtualClassDiagSet)
4547 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4548 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004549}
4550
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004551namespace {
John McCall02db245d2010-08-18 09:41:07 +00004552struct AbstractUsageInfo {
4553 Sema &S;
4554 CXXRecordDecl *Record;
4555 CanQualType AbstractType;
4556 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004557
John McCall02db245d2010-08-18 09:41:07 +00004558 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4559 : S(S), Record(Record),
4560 AbstractType(S.Context.getCanonicalType(
4561 S.Context.getTypeDeclType(Record))),
4562 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004563
John McCall02db245d2010-08-18 09:41:07 +00004564 void DiagnoseAbstractType() {
4565 if (Invalid) return;
4566 S.DiagnoseAbstractType(Record);
4567 Invalid = true;
4568 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004569
John McCall02db245d2010-08-18 09:41:07 +00004570 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4571};
4572
4573struct CheckAbstractUsage {
4574 AbstractUsageInfo &Info;
4575 const NamedDecl *Ctx;
4576
4577 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4578 : Info(Info), Ctx(Ctx) {}
4579
4580 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4581 switch (TL.getTypeLocClass()) {
4582#define ABSTRACT_TYPELOC(CLASS, PARENT)
4583#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004584 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004585#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004586 }
John McCall02db245d2010-08-18 09:41:07 +00004587 }
Mike Stump11289f42009-09-09 15:08:12 +00004588
John McCall02db245d2010-08-18 09:41:07 +00004589 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004590 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004591 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4592 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004593 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004594
4595 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004596 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004597 }
John McCall02db245d2010-08-18 09:41:07 +00004598 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004599
John McCall02db245d2010-08-18 09:41:07 +00004600 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4601 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4602 }
Mike Stump11289f42009-09-09 15:08:12 +00004603
John McCall02db245d2010-08-18 09:41:07 +00004604 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4605 // Visit the type parameters from a permissive context.
4606 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4607 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4608 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4609 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4610 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4611 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004612 }
John McCall02db245d2010-08-18 09:41:07 +00004613 }
Mike Stump11289f42009-09-09 15:08:12 +00004614
John McCall02db245d2010-08-18 09:41:07 +00004615 // Visit pointee types from a permissive context.
4616#define CheckPolymorphic(Type) \
4617 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4618 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4619 }
4620 CheckPolymorphic(PointerTypeLoc)
4621 CheckPolymorphic(ReferenceTypeLoc)
4622 CheckPolymorphic(MemberPointerTypeLoc)
4623 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004624 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004625
John McCall02db245d2010-08-18 09:41:07 +00004626 /// Handle all the types we haven't given a more specific
4627 /// implementation for above.
4628 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4629 // Every other kind of type that we haven't called out already
4630 // that has an inner type is either (1) sugar or (2) contains that
4631 // inner type in some way as a subobject.
4632 if (TypeLoc Next = TL.getNextTypeLoc())
4633 return Visit(Next, Sel);
4634
4635 // If there's no inner type and we're in a permissive context,
4636 // don't diagnose.
4637 if (Sel == Sema::AbstractNone) return;
4638
4639 // Check whether the type matches the abstract type.
4640 QualType T = TL.getType();
4641 if (T->isArrayType()) {
4642 Sel = Sema::AbstractArrayType;
4643 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004644 }
John McCall02db245d2010-08-18 09:41:07 +00004645 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4646 if (CT != Info.AbstractType) return;
4647
4648 // It matched; do some magic.
4649 if (Sel == Sema::AbstractArrayType) {
4650 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4651 << T << TL.getSourceRange();
4652 } else {
4653 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4654 << Sel << T << TL.getSourceRange();
4655 }
4656 Info.DiagnoseAbstractType();
4657 }
4658};
4659
4660void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4661 Sema::AbstractDiagSelID Sel) {
4662 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4663}
4664
4665}
4666
4667/// Check for invalid uses of an abstract type in a method declaration.
4668static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4669 CXXMethodDecl *MD) {
4670 // No need to do the check on definitions, which require that
4671 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004672 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004673 return;
4674
4675 // For safety's sake, just ignore it if we don't have type source
4676 // information. This should never happen for non-implicit methods,
4677 // but...
4678 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4679 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4680}
4681
4682/// Check for invalid uses of an abstract type within a class definition.
4683static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4684 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004685 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004686 if (D->isImplicit()) continue;
4687
4688 // Methods and method templates.
4689 if (isa<CXXMethodDecl>(D)) {
4690 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4691 } else if (isa<FunctionTemplateDecl>(D)) {
4692 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4693 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4694
4695 // Fields and static variables.
4696 } else if (isa<FieldDecl>(D)) {
4697 FieldDecl *FD = cast<FieldDecl>(D);
4698 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4699 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4700 } else if (isa<VarDecl>(D)) {
4701 VarDecl *VD = cast<VarDecl>(D);
4702 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4703 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4704
4705 // Nested classes and class templates.
4706 } else if (isa<CXXRecordDecl>(D)) {
4707 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4708 } else if (isa<ClassTemplateDecl>(D)) {
4709 CheckAbstractClassUsage(Info,
4710 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4711 }
4712 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004713}
4714
Hans Wennborg853ae942014-05-30 16:59:42 +00004715/// \brief Check class-level dllimport/dllexport attribute.
4716static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4717 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004718
4719 // MSVC inherits DLL attributes to partial class template specializations.
4720 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4721 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4722 if (Attr *TemplateAttr =
4723 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4724 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4725 A->setInherited(true);
4726 ClassAttr = A;
4727 }
4728 }
4729 }
4730
Hans Wennborg853ae942014-05-30 16:59:42 +00004731 if (!ClassAttr)
4732 return;
4733
Hans Wennborg8313c762014-11-03 16:09:16 +00004734 if (!Class->isExternallyVisible()) {
4735 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4736 << Class << ClassAttr;
4737 return;
4738 }
4739
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004740 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4741 !ClassAttr->isInherited()) {
4742 // Diagnose dll attributes on members of class with dll attribute.
4743 for (Decl *Member : Class->decls()) {
4744 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4745 continue;
4746 InheritableAttr *MemberAttr = getDLLAttr(Member);
4747 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4748 continue;
4749
4750 S.Diag(MemberAttr->getLocation(),
4751 diag::err_attribute_dll_member_of_dll_class)
4752 << MemberAttr << ClassAttr;
4753 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4754 Member->setInvalidDecl();
4755 }
4756 }
4757
4758 if (Class->getDescribedClassTemplate())
4759 // Don't inherit dll attribute until the template is instantiated.
4760 return;
4761
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004762 // The class is either imported or exported.
4763 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4764 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004765
Hans Wennborgfd76d912015-01-15 21:18:30 +00004766 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4767
4768 // Don't dllexport explicit class template instantiation declarations.
4769 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4770 Class->dropAttr<DLLExportAttr>();
4771 return;
4772 }
4773
Hans Wennborg853ae942014-05-30 16:59:42 +00004774 // Force declaration of implicit members so they can inherit the attribute.
4775 S.ForceDeclarationOfImplicitMembers(Class);
4776
4777 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4778 // seem to be true in practice?
4779
Hans Wennborg853ae942014-05-30 16:59:42 +00004780 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004781 VarDecl *VD = dyn_cast<VarDecl>(Member);
4782 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4783
4784 // Only methods and static fields inherit the attributes.
4785 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004786 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004787
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004788 if (MD) {
4789 // Don't process deleted methods.
4790 if (MD->isDeleted())
4791 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004792
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004793 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4794 // Current MSVC versions don't export the move assignment operators, so
4795 // don't attempt to import them if we have a definition.
4796 continue;
4797 }
4798
Hans Wennborg97cbed42015-02-19 22:39:24 +00004799 if (MD->isInlined() &&
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004800 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00004801 // MinGW does not import or export inline methods.
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004802 continue;
4803 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004804 }
4805
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004806 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004807 auto *NewAttr =
4808 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4809 NewAttr->setInherited(true);
4810 Member->addAttr(NewAttr);
4811 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004812
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004813 if (MD && ClassExported) {
4814 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004815 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004816
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004817 // .. except for certain kinds of template specializations.
4818 if (TSK == TSK_ExplicitInstantiationDeclaration)
4819 continue;
4820 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4821 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004822
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004823 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004824
4825 // The function will be passed to the consumer when its definition is
4826 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004827 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4828 MD->isCopyAssignmentOperator() ||
4829 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004830 // Synthesize and instantiate non-trivial implicit methods, explicitly
4831 // defaulted methods, and the copy and move assignment operators. The
4832 // latter are exported even if they are trivial, because the address of
4833 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg58703732015-02-21 01:07:24 +00004834 DiagnosticErrorTrap Trap(S.Diags);
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004835 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg58703732015-02-21 01:07:24 +00004836 if (Trap.hasErrorOccurred()) {
4837 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4838 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4839 break;
4840 }
Hans Wennborg45810b42014-12-16 01:15:01 +00004841
4842 // There is no later point when we will see the definition of this
4843 // function, so pass it to the consumer now.
4844 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004845 }
4846 }
4847 }
4848}
4849
Douglas Gregorc99f1552009-12-03 18:33:45 +00004850/// \brief Perform semantic checks on a class definition that has been
4851/// completing, introducing implicitly-declared members, checking for
4852/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004853void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004854 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004855 return;
4856
John McCall02db245d2010-08-18 09:41:07 +00004857 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4858 AbstractUsageInfo Info(*this, Record);
4859 CheckAbstractClassUsage(Info, Record);
4860 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004861
4862 // If this is not an aggregate type and has no user-declared constructor,
4863 // complain about any non-static data members of reference or const scalar
4864 // type, since they will never get initializers.
4865 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004866 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4867 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004868 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004869 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004870 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004871 continue;
4872
Douglas Gregor454a5b62010-04-15 00:00:53 +00004873 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004874 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004875 if (!Complained) {
4876 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4877 << Record->getTagKind() << Record;
4878 Complained = true;
4879 }
4880
4881 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4882 << F->getType()->isReferenceType()
4883 << F->getDeclName();
4884 }
4885 }
4886 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004887
Douglas Gregor36c22a22010-10-15 13:21:21 +00004888 if (Record->getIdentifier()) {
4889 // C++ [class.mem]p13:
4890 // If T is the name of a class, then each of the following shall have a
4891 // name different from T:
4892 // - every member of every anonymous union that is a member of class T.
4893 //
4894 // C++ [class.mem]p14:
4895 // In addition, if class T has a user-declared constructor (12.1), every
4896 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004897 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4898 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4899 ++I) {
4900 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004901 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4902 isa<IndirectFieldDecl>(D)) {
4903 Diag(D->getLocation(), diag::err_member_name_of_class)
4904 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004905 break;
4906 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004907 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004908 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004909
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004910 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004911 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004912 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004913 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4914 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004915 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4916 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4917 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004918
David Majnemera5433082013-10-18 00:33:31 +00004919 if (Record->isAbstract()) {
4920 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4921 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4922 << FA->isSpelledAsSealed();
4923 DiagnoseAbstractType(Record);
4924 }
David Blaikie348df502012-09-21 03:21:07 +00004925 }
4926
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004927 bool HasMethodWithOverrideControl = false,
4928 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004929 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004930 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004931 // See if a method overloads virtual methods in a base
4932 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004933 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004934 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004935 if (M->hasAttr<OverrideAttr>())
4936 HasMethodWithOverrideControl = true;
4937 else if (M->size_overridden_methods() > 0)
4938 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004939 // Check whether the explicitly-defaulted special members are valid.
4940 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004941 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004942
4943 // For an explicitly defaulted or deleted special member, we defer
4944 // determining triviality until the class is complete. That time is now!
4945 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004946 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004947 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004948 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004949
4950 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004951 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004952 }
4953 }
4954 }
4955 }
4956
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004957 if (HasMethodWithOverrideControl &&
4958 HasOverridingMethodWithoutOverrideControl) {
4959 // At least one method has the 'override' control declared.
4960 // Diagnose all other overridden methods which do not have 'override' specified on them.
4961 for (auto *M : Record->methods())
4962 DiagnoseAbsenceOfOverrideControl(M);
4963 }
Sebastian Redl08905022011-02-05 19:23:19 +00004964
John McCall95833f32014-02-27 20:30:49 +00004965 // ms_struct is a request to use the same ABI rules as MSVC. Check
4966 // whether this class uses any C++ features that are implemented
4967 // completely differently in MSVC, and if so, emit a diagnostic.
4968 // That diagnostic defaults to an error, but we allow projects to
4969 // map it down to a warning (or ignore it). It's a fairly common
4970 // practice among users of the ms_struct pragma to mass-annotate
4971 // headers, sweeping up a bunch of types that the project doesn't
4972 // really rely on MSVC-compatible layout for. We must therefore
4973 // support "ms_struct except for C++ stuff" as a secondary ABI.
4974 if (Record->isMsStruct(Context) &&
4975 (Record->isPolymorphic() || Record->getNumBases())) {
4976 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004977 }
4978
Richard Smithc2bc61b2013-03-18 21:12:30 +00004979 // Declare inheriting constructors. We do this eagerly here because:
4980 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004981 // constructors from different classes.
4982 // - The lazy declaration of the other implicit constructors is so as to not
4983 // waste space and performance on classes that are not meant to be
4984 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004985 // have inheriting constructors.
4986 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004987
4988 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004989}
4990
Richard Smith41c35d62013-11-27 03:39:20 +00004991/// Look up the special member function that would be called by a special
4992/// member function for a subobject of class type.
4993///
4994/// \param Class The class type of the subobject.
4995/// \param CSM The kind of special member function.
4996/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4997/// \param ConstRHS True if this is a copy operation with a const object
4998/// on its RHS, that is, if the argument to the outer special member
4999/// function is 'const' and this is not a field marked 'mutable'.
5000static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5001 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5002 unsigned FieldQuals, bool ConstRHS) {
5003 unsigned LHSQuals = 0;
5004 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5005 LHSQuals = FieldQuals;
5006
5007 unsigned RHSQuals = FieldQuals;
5008 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5009 RHSQuals = 0;
5010 else if (ConstRHS)
5011 RHSQuals |= Qualifiers::Const;
5012
5013 return S.LookupSpecialMember(Class, CSM,
5014 RHSQuals & Qualifiers::Const,
5015 RHSQuals & Qualifiers::Volatile,
5016 false,
5017 LHSQuals & Qualifiers::Const,
5018 LHSQuals & Qualifiers::Volatile);
5019}
5020
Richard Smithb5800092012-06-10 05:43:50 +00005021/// Is the special member function which would be selected to perform the
5022/// specified operation on the specified class type a constexpr constructor?
5023static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5024 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005025 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005026 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005027 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005028 if (!SMOR || !SMOR->getMethod())
5029 // A constructor we wouldn't select can't be "involved in initializing"
5030 // anything.
5031 return true;
5032 return SMOR->getMethod()->isConstexpr();
5033}
5034
5035/// Determine whether the specified special member function would be constexpr
5036/// if it were implicitly defined.
5037static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5038 Sema::CXXSpecialMember CSM,
5039 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005040 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005041 return false;
5042
5043 // C++11 [dcl.constexpr]p4:
5044 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005045 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005046 switch (CSM) {
5047 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005048 // Since default constructor lookup is essentially trivial (and cannot
5049 // involve, for instance, template instantiation), we compute whether a
5050 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5051 //
5052 // This is important for performance; we need to know whether the default
5053 // constructor is constexpr to determine whether the type is a literal type.
5054 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5055
Richard Smithb5800092012-06-10 05:43:50 +00005056 case Sema::CXXCopyConstructor:
5057 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005058 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005059 break;
5060
5061 case Sema::CXXCopyAssignment:
5062 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005063 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005064 return false;
5065 // In C++1y, we need to perform overload resolution.
5066 Ctor = false;
5067 break;
5068
Richard Smithb5800092012-06-10 05:43:50 +00005069 case Sema::CXXDestructor:
5070 case Sema::CXXInvalid:
5071 return false;
5072 }
5073
5074 // -- if the class is a non-empty union, or for each non-empty anonymous
5075 // union member of a non-union class, exactly one non-static data member
5076 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005077 //
5078 // If we squint, this is guaranteed, since exactly one non-static data member
5079 // will be initialized (if the constructor isn't deleted), we just don't know
5080 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005081 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005082 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005083
5084 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005085 if (Ctor && ClassDecl->getNumVBases())
5086 return false;
5087
5088 // C++1y [class.copy]p26:
5089 // -- [the class] is a literal type, and
5090 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005091 return false;
5092
5093 // -- every constructor involved in initializing [...] base class
5094 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005095 // -- the assignment operator selected to copy/move each direct base
5096 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005097 for (const auto &B : ClassDecl->bases()) {
5098 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005099 if (!BaseType) continue;
5100
5101 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005102 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005103 return false;
5104 }
5105
5106 // -- every constructor involved in initializing non-static data members
5107 // [...] shall be a constexpr constructor;
5108 // -- every non-static data member and base class sub-object shall be
5109 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005110 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005111 // thereof), the assignment operator selected to copy/move that member is
5112 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005113 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005114 if (F->isInvalidDecl())
5115 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005116 QualType BaseType = S.Context.getBaseElementType(F->getType());
5117 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005118 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005119 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5120 BaseType.getCVRQualifiers(),
5121 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005122 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005123 }
5124 }
5125
5126 // All OK, it's constexpr!
5127 return true;
5128}
5129
Richard Smithd3b5c9082012-07-27 04:22:15 +00005130static Sema::ImplicitExceptionSpecification
5131computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5132 switch (S.getSpecialMember(MD)) {
5133 case Sema::CXXDefaultConstructor:
5134 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5135 case Sema::CXXCopyConstructor:
5136 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5137 case Sema::CXXCopyAssignment:
5138 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5139 case Sema::CXXMoveConstructor:
5140 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5141 case Sema::CXXMoveAssignment:
5142 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5143 case Sema::CXXDestructor:
5144 return S.ComputeDefaultedDtorExceptionSpec(MD);
5145 case Sema::CXXInvalid:
5146 break;
5147 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005148 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5149 "only special members have implicit exception specs");
5150 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005151}
5152
Reid Kleckner78af0702013-08-27 23:08:25 +00005153static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5154 CXXMethodDecl *MD) {
5155 FunctionProtoType::ExtProtoInfo EPI;
5156
5157 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005158 EPI.ExceptionSpec.Type = EST_Unevaluated;
5159 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005160
5161 // Set the calling convention to the default for C++ instance methods.
5162 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5163 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5164 /*IsCXXMethod=*/true));
5165 return EPI;
5166}
5167
Richard Smithd3b5c9082012-07-27 04:22:15 +00005168void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5169 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5170 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5171 return;
5172
Richard Smith7f782272012-07-30 23:48:14 +00005173 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005174 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005175
Richard Smith7f782272012-07-30 23:48:14 +00005176 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005177 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005178
5179 // A user-provided destructor can be defined outside the class. When that
5180 // happens, be sure to update the exception specification on both
5181 // declarations.
5182 const FunctionProtoType *CanonicalFPT =
5183 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5184 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005185 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005186}
5187
Richard Smithb9e90b12012-05-15 04:39:51 +00005188void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5189 CXXRecordDecl *RD = MD->getParent();
5190 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005191
Richard Smithb9e90b12012-05-15 04:39:51 +00005192 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5193 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005194
5195 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005196 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005197 bool First = MD == MD->getCanonicalDecl();
5198
5199 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005200
5201 // C++11 [dcl.fct.def.default]p1:
5202 // A function that is explicitly defaulted shall
5203 // -- be a special member function (checked elsewhere),
5204 // -- have the same type (except for ref-qualifiers, and except that a
5205 // copy operation can take a non-const reference) as an implicit
5206 // declaration, and
5207 // -- not have default arguments.
5208 unsigned ExpectedParams = 1;
5209 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5210 ExpectedParams = 0;
5211 if (MD->getNumParams() != ExpectedParams) {
5212 // This also checks for default arguments: a copy or move constructor with a
5213 // default argument is classified as a default constructor, and assignment
5214 // operations and destructors can't have default arguments.
5215 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5216 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005217 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005218 } else if (MD->isVariadic()) {
5219 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5220 << CSM << MD->getSourceRange();
5221 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005222 }
5223
Richard Smithb9e90b12012-05-15 04:39:51 +00005224 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005225
Richard Smithb5800092012-06-10 05:43:50 +00005226 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005227 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005228 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005229 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005230 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005231
Richard Smithb9e90b12012-05-15 04:39:51 +00005232 QualType ReturnType = Context.VoidTy;
5233 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5234 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005235 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005236 QualType ExpectedReturnType =
5237 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5238 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5239 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5240 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5241 HadError = true;
5242 }
5243
5244 // A defaulted special member cannot have cv-qualifiers.
5245 if (Type->getTypeQuals()) {
5246 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005247 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005248 HadError = true;
5249 }
5250 }
5251
5252 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005253 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005254 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005255 if (ExpectedParams && ArgType->isReferenceType()) {
5256 // Argument must be reference to possibly-const T.
5257 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005258 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005259
5260 if (ReferentType.isVolatileQualified()) {
5261 Diag(MD->getLocation(),
5262 diag::err_defaulted_special_member_volatile_param) << CSM;
5263 HadError = true;
5264 }
5265
Richard Smithb5800092012-06-10 05:43:50 +00005266 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005267 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5268 Diag(MD->getLocation(),
5269 diag::err_defaulted_special_member_copy_const_param)
5270 << (CSM == CXXCopyAssignment);
5271 // FIXME: Explain why this special member can't be const.
5272 } else {
5273 Diag(MD->getLocation(),
5274 diag::err_defaulted_special_member_move_const_param)
5275 << (CSM == CXXMoveAssignment);
5276 }
5277 HadError = true;
5278 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005279 } else if (ExpectedParams) {
5280 // A copy assignment operator can take its argument by value, but a
5281 // defaulted one cannot.
5282 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005283 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005284 HadError = true;
5285 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005286
Richard Smithcc36f692011-12-22 02:22:31 +00005287 // C++11 [dcl.fct.def.default]p2:
5288 // An explicitly-defaulted function may be declared constexpr only if it
5289 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005290 // Do not apply this rule to members of class templates, since core issue 1358
5291 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005292 // functions which cannot be constexpr (for non-constructors in C++11 and for
5293 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005294 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5295 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005296 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005297 : isa<CXXConstructorDecl>(MD)) &&
5298 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005299 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5300 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005301 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005302 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005303 }
Richard Smithbd305122012-12-11 01:14:52 +00005304
Richard Smithcc36f692011-12-22 02:22:31 +00005305 // and may have an explicit exception-specification only if it is compatible
5306 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005307 if (Type->hasExceptionSpec()) {
5308 // Delay the check if this is the first declaration of the special member,
5309 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005310 if (First) {
5311 // If the exception specification needs to be instantiated, do so now,
5312 // before we clobber it with an EST_Unevaluated specification below.
5313 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5314 InstantiateExceptionSpec(MD->getLocStart(), MD);
5315 Type = MD->getType()->getAs<FunctionProtoType>();
5316 }
Richard Smithbd305122012-12-11 01:14:52 +00005317 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005318 } else
Richard Smithbd305122012-12-11 01:14:52 +00005319 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5320 }
Richard Smithcc36f692011-12-22 02:22:31 +00005321
5322 // If a function is explicitly defaulted on its first declaration,
5323 if (First) {
5324 // -- it is implicitly considered to be constexpr if the implicit
5325 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005326 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005327
Richard Smithb9e90b12012-05-15 04:39:51 +00005328 // -- it is implicitly considered to have the same exception-specification
5329 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005330 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005331 EPI.ExceptionSpec.Type = EST_Unevaluated;
5332 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005333 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005334 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005335 ExpectedParams),
5336 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005337 }
5338
Richard Smithb9e90b12012-05-15 04:39:51 +00005339 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005340 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005341 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005342 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005343 // C++11 [dcl.fct.def.default]p4:
5344 // [For a] user-provided explicitly-defaulted function [...] if such a
5345 // function is implicitly defined as deleted, the program is ill-formed.
5346 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005347 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005348 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005349 }
5350 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005351
Richard Smithb9e90b12012-05-15 04:39:51 +00005352 if (HadError)
5353 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005354}
5355
Richard Smithbd305122012-12-11 01:14:52 +00005356/// Check whether the exception specification provided for an
5357/// explicitly-defaulted special member matches the exception specification
5358/// that would have been generated for an implicit special member, per
5359/// C++11 [dcl.fct.def.default]p2.
5360void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5361 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005362 // If the exception specification was explicitly specified but hadn't been
5363 // parsed when the method was defaulted, grab it now.
5364 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5365 SpecifiedType =
5366 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5367
Richard Smithbd305122012-12-11 01:14:52 +00005368 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005369 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5370 /*IsCXXMethod=*/true);
5371 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005372 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5373 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005374 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005375 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005376
5377 // Ensure that it matches.
5378 CheckEquivalentExceptionSpec(
5379 PDiag(diag::err_incorrect_defaulted_exception_spec)
5380 << getSpecialMember(MD), PDiag(),
5381 ImplicitType, SourceLocation(),
5382 SpecifiedType, MD->getLocation());
5383}
5384
Alp Tokerae3a9442013-10-18 05:54:19 +00005385void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005386 decltype(DelayedExceptionSpecChecks) Checks;
5387 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005388
Richard Smith88f45492014-11-22 03:09:05 +00005389 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005390 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5391
5392 // Perform any deferred checking of exception specifications for virtual
5393 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005394 for (auto &Check : Checks)
5395 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005396
5397 // Check that any explicitly-defaulted methods have exception specifications
5398 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005399 for (auto &Spec : Specs)
5400 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005401}
5402
Richard Smithd951a1d2012-02-18 02:02:13 +00005403namespace {
5404struct SpecialMemberDeletionInfo {
5405 Sema &S;
5406 CXXMethodDecl *MD;
5407 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005408 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005409
5410 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005411 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005412 SourceLocation Loc;
5413
5414 bool AllFieldsAreConst;
5415
5416 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005417 Sema::CXXSpecialMember CSM, bool Diagnose)
5418 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005419 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005420 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005421 AllFieldsAreConst(true) {
5422 switch (CSM) {
5423 case Sema::CXXDefaultConstructor:
5424 case Sema::CXXCopyConstructor:
5425 IsConstructor = true;
5426 break;
5427 case Sema::CXXMoveConstructor:
5428 IsConstructor = true;
5429 IsMove = true;
5430 break;
5431 case Sema::CXXCopyAssignment:
5432 IsAssignment = true;
5433 break;
5434 case Sema::CXXMoveAssignment:
5435 IsAssignment = true;
5436 IsMove = true;
5437 break;
5438 case Sema::CXXDestructor:
5439 break;
5440 case Sema::CXXInvalid:
5441 llvm_unreachable("invalid special member kind");
5442 }
5443
5444 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005445 if (const ReferenceType *RT =
5446 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5447 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005448 }
5449 }
5450
5451 bool inUnion() const { return MD->getParent()->isUnion(); }
5452
5453 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005454 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005455 unsigned Quals, bool IsMutable) {
5456 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5457 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005458 }
5459
Richard Smith852265f2012-03-30 20:53:28 +00005460 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005461
Richard Smith852265f2012-03-30 20:53:28 +00005462 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005463 bool shouldDeleteForField(FieldDecl *FD);
5464 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005465
Richard Smithaf136f82012-07-18 03:51:16 +00005466 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5467 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005468 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5469 Sema::SpecialMemberOverloadResult *SMOR,
5470 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005471
5472 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005473};
5474}
5475
John McCalld4274212012-04-09 20:53:23 +00005476/// Is the given special member inaccessible when used on the given
5477/// sub-object.
5478bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5479 CXXMethodDecl *target) {
5480 /// If we're operating on a base class, the object type is the
5481 /// type of this special member.
5482 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005483 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005484 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5485 objectTy = S.Context.getTypeDeclType(MD->getParent());
5486 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5487
5488 // If we're operating on a field, the object type is the type of the field.
5489 } else {
5490 objectTy = S.Context.getTypeDeclType(target->getParent());
5491 }
5492
5493 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5494}
5495
Richard Smith852265f2012-03-30 20:53:28 +00005496/// Check whether we should delete a special member due to the implicit
5497/// definition containing a call to a special member of a subobject.
5498bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5499 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5500 bool IsDtorCallInCtor) {
5501 CXXMethodDecl *Decl = SMOR->getMethod();
5502 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5503
5504 int DiagKind = -1;
5505
5506 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5507 DiagKind = !Decl ? 0 : 1;
5508 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5509 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005510 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005511 DiagKind = 3;
5512 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5513 !Decl->isTrivial()) {
5514 // A member of a union must have a trivial corresponding special member.
5515 // As a weird special case, a destructor call from a union's constructor
5516 // must be accessible and non-deleted, but need not be trivial. Such a
5517 // destructor is never actually called, but is semantically checked as
5518 // if it were.
5519 DiagKind = 4;
5520 }
5521
5522 if (DiagKind == -1)
5523 return false;
5524
5525 if (Diagnose) {
5526 if (Field) {
5527 S.Diag(Field->getLocation(),
5528 diag::note_deleted_special_member_class_subobject)
5529 << CSM << MD->getParent() << /*IsField*/true
5530 << Field << DiagKind << IsDtorCallInCtor;
5531 } else {
5532 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5533 S.Diag(Base->getLocStart(),
5534 diag::note_deleted_special_member_class_subobject)
5535 << CSM << MD->getParent() << /*IsField*/false
5536 << Base->getType() << DiagKind << IsDtorCallInCtor;
5537 }
5538
5539 if (DiagKind == 1)
5540 S.NoteDeletedFunction(Decl);
5541 // FIXME: Explain inaccessibility if DiagKind == 3.
5542 }
5543
5544 return true;
5545}
5546
Richard Smith921bd202012-02-26 09:11:52 +00005547/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005548/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005549bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005550 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005551 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005552 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005553
5554 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005555 // -- any direct or virtual base class, or non-static data member with no
5556 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005557 // either M has no default constructor or overload resolution as applied
5558 // to M's default constructor results in an ambiguity or in a function
5559 // that is deleted or inaccessible
5560 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5561 // -- a direct or virtual base class B that cannot be copied/moved because
5562 // overload resolution, as applied to B's corresponding special member,
5563 // results in an ambiguity or a function that is deleted or inaccessible
5564 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005565 // C++11 [class.dtor]p5:
5566 // -- any direct or virtual base class [...] has a type with a destructor
5567 // that is deleted or inaccessible
5568 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005569 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005570 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5571 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005572 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005573
Richard Smith852265f2012-03-30 20:53:28 +00005574 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5575 // -- any direct or virtual base class or non-static data member has a
5576 // type with a destructor that is deleted or inaccessible
5577 if (IsConstructor) {
5578 Sema::SpecialMemberOverloadResult *SMOR =
5579 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5580 false, false, false, false, false);
5581 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5582 return true;
5583 }
5584
Richard Smith921bd202012-02-26 09:11:52 +00005585 return false;
5586}
5587
5588/// Check whether we should delete a special member function due to the class
5589/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005590bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005591 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005592 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005593}
5594
5595/// Check whether we should delete a special member function due to the class
5596/// having a particular non-static data member.
5597bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5598 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5599 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5600
5601 if (CSM == Sema::CXXDefaultConstructor) {
5602 // For a default constructor, all references must be initialized in-class
5603 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005604 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5605 if (Diagnose)
5606 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5607 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005608 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005609 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005610 // C++11 [class.ctor]p5: any non-variant non-static data member of
5611 // const-qualified type (or array thereof) with no
5612 // brace-or-equal-initializer does not have a user-provided default
5613 // constructor.
5614 if (!inUnion() && FieldType.isConstQualified() &&
5615 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005616 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5617 if (Diagnose)
5618 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005619 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005620 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005621 }
5622
5623 if (inUnion() && !FieldType.isConstQualified())
5624 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005625 } else if (CSM == Sema::CXXCopyConstructor) {
5626 // For a copy constructor, data members must not be of rvalue reference
5627 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005628 if (FieldType->isRValueReferenceType()) {
5629 if (Diagnose)
5630 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5631 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005632 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005633 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005634 } else if (IsAssignment) {
5635 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005636 if (FieldType->isReferenceType()) {
5637 if (Diagnose)
5638 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5639 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005640 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005641 }
5642 if (!FieldRecord && FieldType.isConstQualified()) {
5643 // C++11 [class.copy]p23:
5644 // -- a non-static data member of const non-class type (or array thereof)
5645 if (Diagnose)
5646 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005647 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005648 return true;
5649 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005650 }
5651
5652 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005653 // Some additional restrictions exist on the variant members.
5654 if (!inUnion() && FieldRecord->isUnion() &&
5655 FieldRecord->isAnonymousStructOrUnion()) {
5656 bool AllVariantFieldsAreConst = true;
5657
Richard Smith5704fe82012-03-29 19:00:10 +00005658 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005659 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005660 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005661
5662 if (!UnionFieldType.isConstQualified())
5663 AllVariantFieldsAreConst = false;
5664
Richard Smith921bd202012-02-26 09:11:52 +00005665 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5666 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005667 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005668 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005669 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005670 }
5671
5672 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005673 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005674 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005675 if (Diagnose)
5676 S.Diag(FieldRecord->getLocation(),
5677 diag::note_deleted_default_ctor_all_const)
5678 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005679 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005680 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005681
Richard Smith5704fe82012-03-29 19:00:10 +00005682 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005683 // This is technically non-conformant, but sanity demands it.
5684 return false;
5685 }
5686
Richard Smithaf136f82012-07-18 03:51:16 +00005687 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5688 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005689 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005690 }
5691
5692 return false;
5693}
5694
5695/// C++11 [class.ctor] p5:
5696/// A defaulted default constructor for a class X is defined as deleted if
5697/// X is a union and all of its variant members are of const-qualified type.
5698bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005699 // This is a silly definition, because it gives an empty union a deleted
5700 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005701 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005702 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005703 if (Diagnose)
5704 S.Diag(MD->getParent()->getLocation(),
5705 diag::note_deleted_default_ctor_all_const)
5706 << MD->getParent() << /*not anonymous union*/0;
5707 return true;
5708 }
5709 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005710}
5711
5712/// Determine whether a defaulted special member function should be defined as
5713/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5714/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005715bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5716 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005717 if (MD->isInvalidDecl())
5718 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005719 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005720 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005721 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005722 return false;
5723
Richard Smithd951a1d2012-02-18 02:02:13 +00005724 // C++11 [expr.lambda.prim]p19:
5725 // The closure type associated with a lambda-expression has a
5726 // deleted (8.4.3) default constructor and a deleted copy
5727 // assignment operator.
5728 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005729 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5730 if (Diagnose)
5731 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005732 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005733 }
5734
Richard Smith6f1e2c62012-04-02 20:59:25 +00005735 // For an anonymous struct or union, the copy and assignment special members
5736 // will never be used, so skip the check. For an anonymous union declared at
5737 // namespace scope, the constructor and destructor are used.
5738 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5739 RD->isAnonymousStructOrUnion())
5740 return false;
5741
Richard Smith852265f2012-03-30 20:53:28 +00005742 // C++11 [class.copy]p7, p18:
5743 // If the class definition declares a move constructor or move assignment
5744 // operator, an implicitly declared copy constructor or copy assignment
5745 // operator is defined as deleted.
5746 if (MD->isImplicit() &&
5747 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005748 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005749
5750 // In Microsoft mode, a user-declared move only causes the deletion of the
5751 // corresponding copy operation, not both copy operations.
5752 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005753 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005754 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005755
5756 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005757 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005758 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005759 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005760 break;
5761 }
5762 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005763 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005764 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005765 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005766 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005767
5768 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005769 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005770 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005771 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005772 break;
5773 }
5774 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005775 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005776 }
5777
5778 if (UserDeclaredMove) {
5779 Diag(UserDeclaredMove->getLocation(),
5780 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005781 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005782 << UserDeclaredMove->isMoveAssignmentOperator();
5783 return true;
5784 }
5785 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005786
Richard Smith6f1e2c62012-04-02 20:59:25 +00005787 // Do access control from the special member function
5788 ContextRAII MethodContext(*this, MD);
5789
Richard Smith921bd202012-02-26 09:11:52 +00005790 // C++11 [class.dtor]p5:
5791 // -- for a virtual destructor, lookup of the non-array deallocation function
5792 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005793 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005794 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005795 DeclarationName Name =
5796 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5797 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005798 OperatorDelete, false)) {
5799 if (Diagnose)
5800 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005801 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005802 }
Richard Smith921bd202012-02-26 09:11:52 +00005803 }
5804
Richard Smith852265f2012-03-30 20:53:28 +00005805 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005806
Aaron Ballman574705e2014-03-13 15:41:46 +00005807 for (auto &BI : RD->bases())
5808 if (!BI.isVirtual() &&
5809 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005810 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005811
Richard Smithd1627032013-07-22 18:06:23 +00005812 // Per DR1611, do not consider virtual bases of constructors of abstract
5813 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005814 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005815 for (auto &BI : RD->vbases())
5816 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005817 return true;
5818 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005819
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005820 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005821 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005822 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005823 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005824
Richard Smithd951a1d2012-02-18 02:02:13 +00005825 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005826 return true;
5827
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005828 if (getLangOpts().CUDA) {
5829 // We should delete the special member in CUDA mode if target inference
5830 // failed.
5831 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5832 Diagnose);
5833 }
5834
Alexis Huntea6f0322011-05-11 22:34:38 +00005835 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005836}
5837
Richard Smith92f241f2012-12-08 02:53:02 +00005838/// Perform lookup for a special member of the specified kind, and determine
5839/// whether it is trivial. If the triviality can be determined without the
5840/// lookup, skip it. This is intended for use when determining whether a
5841/// special member of a containing object is trivial, and thus does not ever
5842/// perform overload resolution for default constructors.
5843///
5844/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5845/// member that was most likely to be intended to be trivial, if any.
5846static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5847 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005848 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005849 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005850 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005851
5852 switch (CSM) {
5853 case Sema::CXXInvalid:
5854 llvm_unreachable("not a special member");
5855
5856 case Sema::CXXDefaultConstructor:
5857 // C++11 [class.ctor]p5:
5858 // A default constructor is trivial if:
5859 // - all the [direct subobjects] have trivial default constructors
5860 //
5861 // Note, no overload resolution is performed in this case.
5862 if (RD->hasTrivialDefaultConstructor())
5863 return true;
5864
5865 if (Selected) {
5866 // If there's a default constructor which could have been trivial, dig it
5867 // out. Otherwise, if there's any user-provided default constructor, point
5868 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005869 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005870 if (RD->needsImplicitDefaultConstructor())
5871 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005872 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005873 if (!CI->isDefaultConstructor())
5874 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005875 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005876 if (!DefCtor->isUserProvided())
5877 break;
5878 }
5879
5880 *Selected = DefCtor;
5881 }
5882
5883 return false;
5884
5885 case Sema::CXXDestructor:
5886 // C++11 [class.dtor]p5:
5887 // A destructor is trivial if:
5888 // - all the direct [subobjects] have trivial destructors
5889 if (RD->hasTrivialDestructor())
5890 return true;
5891
5892 if (Selected) {
5893 if (RD->needsImplicitDestructor())
5894 S.DeclareImplicitDestructor(RD);
5895 *Selected = RD->getDestructor();
5896 }
5897
5898 return false;
5899
5900 case Sema::CXXCopyConstructor:
5901 // C++11 [class.copy]p12:
5902 // A copy constructor is trivial if:
5903 // - the constructor selected to copy each direct [subobject] is trivial
5904 if (RD->hasTrivialCopyConstructor()) {
5905 if (Quals == Qualifiers::Const)
5906 // We must either select the trivial copy constructor or reach an
5907 // ambiguity; no need to actually perform overload resolution.
5908 return true;
5909 } else if (!Selected) {
5910 return false;
5911 }
5912 // In C++98, we are not supposed to perform overload resolution here, but we
5913 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5914 // cases like B as having a non-trivial copy constructor:
5915 // struct A { template<typename T> A(T&); };
5916 // struct B { mutable A a; };
5917 goto NeedOverloadResolution;
5918
5919 case Sema::CXXCopyAssignment:
5920 // C++11 [class.copy]p25:
5921 // A copy assignment operator is trivial if:
5922 // - the assignment operator selected to copy each direct [subobject] is
5923 // trivial
5924 if (RD->hasTrivialCopyAssignment()) {
5925 if (Quals == Qualifiers::Const)
5926 return true;
5927 } else if (!Selected) {
5928 return false;
5929 }
5930 // In C++98, we are not supposed to perform overload resolution here, but we
5931 // treat that as a language defect.
5932 goto NeedOverloadResolution;
5933
5934 case Sema::CXXMoveConstructor:
5935 case Sema::CXXMoveAssignment:
5936 NeedOverloadResolution:
5937 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005938 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005939
5940 // The standard doesn't describe how to behave if the lookup is ambiguous.
5941 // We treat it as not making the member non-trivial, just like the standard
5942 // mandates for the default constructor. This should rarely matter, because
5943 // the member will also be deleted.
5944 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5945 return true;
5946
5947 if (!SMOR->getMethod()) {
5948 assert(SMOR->getKind() ==
5949 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5950 return false;
5951 }
5952
5953 // We deliberately don't check if we found a deleted special member. We're
5954 // not supposed to!
5955 if (Selected)
5956 *Selected = SMOR->getMethod();
5957 return SMOR->getMethod()->isTrivial();
5958 }
5959
5960 llvm_unreachable("unknown special method kind");
5961}
5962
Benjamin Kramer3e350262013-02-15 12:30:38 +00005963static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005964 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005965 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005966 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005967
5968 // Look for constructor templates.
5969 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5970 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5971 if (CXXConstructorDecl *CD =
5972 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5973 return CD;
5974 }
5975
Craig Topperc3ec1492014-05-26 06:22:03 +00005976 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005977}
5978
5979/// The kind of subobject we are checking for triviality. The values of this
5980/// enumeration are used in diagnostics.
5981enum TrivialSubobjectKind {
5982 /// The subobject is a base class.
5983 TSK_BaseClass,
5984 /// The subobject is a non-static data member.
5985 TSK_Field,
5986 /// The object is actually the complete object.
5987 TSK_CompleteObject
5988};
5989
5990/// Check whether the special member selected for a given type would be trivial.
5991static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005992 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005993 Sema::CXXSpecialMember CSM,
5994 TrivialSubobjectKind Kind,
5995 bool Diagnose) {
5996 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5997 if (!SubRD)
5998 return true;
5999
6000 CXXMethodDecl *Selected;
6001 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006002 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006003 return true;
6004
6005 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006006 if (ConstRHS)
6007 SubType.addConst();
6008
Richard Smith92f241f2012-12-08 02:53:02 +00006009 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6010 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6011 << Kind << SubType.getUnqualifiedType();
6012 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6013 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6014 } else if (!Selected)
6015 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6016 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6017 else if (Selected->isUserProvided()) {
6018 if (Kind == TSK_CompleteObject)
6019 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6020 << Kind << SubType.getUnqualifiedType() << CSM;
6021 else {
6022 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6023 << Kind << SubType.getUnqualifiedType() << CSM;
6024 S.Diag(Selected->getLocation(), diag::note_declared_at);
6025 }
6026 } else {
6027 if (Kind != TSK_CompleteObject)
6028 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6029 << Kind << SubType.getUnqualifiedType() << CSM;
6030
6031 // Explain why the defaulted or deleted special member isn't trivial.
6032 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6033 }
6034 }
6035
6036 return false;
6037}
6038
6039/// Check whether the members of a class type allow a special member to be
6040/// trivial.
6041static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6042 Sema::CXXSpecialMember CSM,
6043 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006044 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006045 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6046 continue;
6047
6048 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6049
6050 // Pretend anonymous struct or union members are members of this class.
6051 if (FI->isAnonymousStructOrUnion()) {
6052 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6053 CSM, ConstArg, Diagnose))
6054 return false;
6055 continue;
6056 }
6057
6058 // C++11 [class.ctor]p5:
6059 // A default constructor is trivial if [...]
6060 // -- no non-static data member of its class has a
6061 // brace-or-equal-initializer
6062 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6063 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006064 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006065 return false;
6066 }
6067
6068 // Objective C ARC 4.3.5:
6069 // [...] nontrivally ownership-qualified types are [...] not trivially
6070 // default constructible, copy constructible, move constructible, copy
6071 // assignable, move assignable, or destructible [...]
6072 if (S.getLangOpts().ObjCAutoRefCount &&
6073 FieldType.hasNonTrivialObjCLifetime()) {
6074 if (Diagnose)
6075 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6076 << RD << FieldType.getObjCLifetime();
6077 return false;
6078 }
6079
Richard Smith41c35d62013-11-27 03:39:20 +00006080 bool ConstRHS = ConstArg && !FI->isMutable();
6081 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6082 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006083 return false;
6084 }
6085
6086 return true;
6087}
6088
6089/// Diagnose why the specified class does not have a trivial special member of
6090/// the given kind.
6091void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6092 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006093
Richard Smith41c35d62013-11-27 03:39:20 +00006094 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6095 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006096 TSK_CompleteObject, /*Diagnose*/true);
6097}
6098
6099/// Determine whether a defaulted or deleted special member function is trivial,
6100/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6101/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6102bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6103 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006104 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6105
6106 CXXRecordDecl *RD = MD->getParent();
6107
6108 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006109
Richard Smith2002bfe2013-11-04 02:02:27 +00006110 // C++11 [class.copy]p12, p25: [DR1593]
6111 // A [special member] is trivial if [...] its parameter-type-list is
6112 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006113 switch (CSM) {
6114 case CXXDefaultConstructor:
6115 case CXXDestructor:
6116 // Trivial default constructors and destructors cannot have parameters.
6117 break;
6118
6119 case CXXCopyConstructor:
6120 case CXXCopyAssignment: {
6121 // Trivial copy operations always have const, non-volatile parameter types.
6122 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006123 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006124 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6125 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6126 if (Diagnose)
6127 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6128 << Param0->getSourceRange() << Param0->getType()
6129 << Context.getLValueReferenceType(
6130 Context.getRecordType(RD).withConst());
6131 return false;
6132 }
6133 break;
6134 }
6135
6136 case CXXMoveConstructor:
6137 case CXXMoveAssignment: {
6138 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006139 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006140 const RValueReferenceType *RT =
6141 Param0->getType()->getAs<RValueReferenceType>();
6142 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6143 if (Diagnose)
6144 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6145 << Param0->getSourceRange() << Param0->getType()
6146 << Context.getRValueReferenceType(Context.getRecordType(RD));
6147 return false;
6148 }
6149 break;
6150 }
6151
6152 case CXXInvalid:
6153 llvm_unreachable("not a special member");
6154 }
6155
Richard Smith92f241f2012-12-08 02:53:02 +00006156 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6157 if (Diagnose)
6158 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6159 diag::note_nontrivial_default_arg)
6160 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6161 return false;
6162 }
6163 if (MD->isVariadic()) {
6164 if (Diagnose)
6165 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6166 return false;
6167 }
6168
6169 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6170 // A copy/move [constructor or assignment operator] is trivial if
6171 // -- the [member] selected to copy/move each direct base class subobject
6172 // is trivial
6173 //
6174 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6175 // A [default constructor or destructor] is trivial if
6176 // -- all the direct base classes have trivial [default constructors or
6177 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006178 for (const auto &BI : RD->bases())
6179 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006180 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006181 return false;
6182
6183 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6184 // A copy/move [constructor or assignment operator] for a class X is
6185 // trivial if
6186 // -- for each non-static data member of X that is of class type (or array
6187 // thereof), the constructor selected to copy/move that member is
6188 // trivial
6189 //
6190 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6191 // A [default constructor or destructor] is trivial if
6192 // -- for all of the non-static data members of its class that are of class
6193 // type (or array thereof), each such class has a trivial [default
6194 // constructor or destructor]
6195 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6196 return false;
6197
6198 // C++11 [class.dtor]p5:
6199 // A destructor is trivial if [...]
6200 // -- the destructor is not virtual
6201 if (CSM == CXXDestructor && MD->isVirtual()) {
6202 if (Diagnose)
6203 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6204 return false;
6205 }
6206
6207 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6208 // A [special member] for class X is trivial if [...]
6209 // -- class X has no virtual functions and no virtual base classes
6210 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6211 if (!Diagnose)
6212 return false;
6213
6214 if (RD->getNumVBases()) {
6215 // Check for virtual bases. We already know that the corresponding
6216 // member in all bases is trivial, so vbases must all be direct.
6217 CXXBaseSpecifier &BS = *RD->vbases_begin();
6218 assert(BS.isVirtual());
6219 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6220 return false;
6221 }
6222
6223 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006224 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006225 if (MI->isVirtual()) {
6226 SourceLocation MLoc = MI->getLocStart();
6227 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6228 return false;
6229 }
6230 }
6231
6232 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6233 }
6234
6235 // Looks like it's trivial!
6236 return true;
6237}
6238
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006239/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006240namespace {
6241 struct FindHiddenVirtualMethodData {
6242 Sema *S;
6243 CXXMethodDecl *Method;
6244 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006245 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006246 };
6247}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006248
David Blaikie282c92a2012-10-19 00:53:08 +00006249/// \brief Check whether any most overriden method from MD in Methods
6250static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006251 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006252 if (MD->size_overridden_methods() == 0)
6253 return Methods.count(MD->getCanonicalDecl());
6254 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6255 E = MD->end_overridden_methods();
6256 I != E; ++I)
6257 if (CheckMostOverridenMethods(*I, Methods))
6258 return true;
6259 return false;
6260}
6261
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006262/// \brief Member lookup function that determines whether a given C++
6263/// method overloads virtual methods in a base class without overriding any,
6264/// to be used with CXXRecordDecl::lookupInBases().
6265static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6266 CXXBasePath &Path,
6267 void *UserData) {
6268 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6269
6270 FindHiddenVirtualMethodData &Data
6271 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6272
6273 DeclarationName Name = Data.Method->getDeclName();
6274 assert(Name.getNameKind() == DeclarationName::Identifier);
6275
6276 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006277 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006278 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006279 !Path.Decls.empty();
6280 Path.Decls = Path.Decls.slice(1)) {
6281 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006282 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006283 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006284 foundSameNameMethod = true;
6285 // Interested only in hidden virtual methods.
6286 if (!MD->isVirtual())
6287 continue;
6288 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006289 // don't warn about the other overloaded methods. Clang deviates from GCC
6290 // by only diagnosing overloads of inherited virtual functions that do not
6291 // override any other virtual functions in the base. GCC's
6292 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6293 // function from a base class. These cases may be better served by a
6294 // warning (not specific to virtual functions) on call sites when the call
6295 // would select a different function from the base class, were it visible.
6296 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006297 if (!Data.S->IsOverload(Data.Method, MD, false))
6298 return true;
6299 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006300 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006301 overloadedMethods.push_back(MD);
6302 }
6303 }
6304
6305 if (foundSameNameMethod)
6306 Data.OverloadedMethods.append(overloadedMethods.begin(),
6307 overloadedMethods.end());
6308 return foundSameNameMethod;
6309}
6310
David Blaikie282c92a2012-10-19 00:53:08 +00006311/// \brief Add the most overriden methods from MD to Methods
6312static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006313 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006314 if (MD->size_overridden_methods() == 0)
6315 Methods.insert(MD->getCanonicalDecl());
6316 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6317 E = MD->end_overridden_methods();
6318 I != E; ++I)
6319 AddMostOverridenMethods(*I, Methods);
6320}
6321
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006322/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006323/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006324void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6325 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006326 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006327 return;
6328
6329 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6330 /*bool RecordPaths=*/false,
6331 /*bool DetectVirtual=*/false);
6332 FindHiddenVirtualMethodData Data;
6333 Data.Method = MD;
6334 Data.S = this;
6335
6336 // Keep the base methods that were overriden or introduced in the subclass
6337 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006338 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006339 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6340 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6341 NamedDecl *ND = *I;
6342 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006343 ND = shad->getTargetDecl();
6344 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6345 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006346 }
6347
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006348 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6349 OverloadedMethods = Data.OverloadedMethods;
6350}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006351
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006352void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6353 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6354 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6355 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6356 PartialDiagnostic PD = PDiag(
6357 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6358 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6359 Diag(overloadedMD->getLocation(), PD);
6360 }
6361}
6362
6363/// \brief Diagnose methods which overload virtual methods in a base class
6364/// without overriding any.
6365void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6366 if (MD->isInvalidDecl())
6367 return;
6368
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006369 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006370 return;
6371
6372 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6373 FindHiddenVirtualMethods(MD, OverloadedMethods);
6374 if (!OverloadedMethods.empty()) {
6375 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6376 << MD << (OverloadedMethods.size() > 1);
6377
6378 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006379 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006380}
6381
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006382void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006383 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006384 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006385 SourceLocation RBrac,
6386 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006387 if (!TagDecl)
6388 return;
Mike Stump11289f42009-09-09 15:08:12 +00006389
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006390 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006391
Rafael Espindola06e1b132012-07-12 04:32:30 +00006392 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6393 if (l->getKind() != AttributeList::AT_Visibility)
6394 continue;
6395 l->setInvalid();
6396 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6397 l->getName();
6398 }
6399
David Blaikie751c5582011-09-22 02:58:26 +00006400 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006401 // strict aliasing violation!
6402 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006403 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006404
Douglas Gregor0be31a22010-07-02 17:43:08 +00006405 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006406 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006407}
6408
Douglas Gregor05379422008-11-03 17:51:48 +00006409/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6410/// special functions, such as the default constructor, copy
6411/// constructor, or destructor, to the given C++ class (C++
6412/// [special]p1). This routine can only be executed just before the
6413/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006414void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006415 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006416 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006417
Richard Smith6b02d462012-12-08 08:32:28 +00006418 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006419 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006420
Richard Smith6b02d462012-12-08 08:32:28 +00006421 // If the properties or semantics of the copy constructor couldn't be
6422 // determined while the class was being declared, force a declaration
6423 // of it now.
6424 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6425 DeclareImplicitCopyConstructor(ClassDecl);
6426 }
6427
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006428 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006429 ++ASTContext::NumImplicitMoveConstructors;
6430
Richard Smith6b02d462012-12-08 08:32:28 +00006431 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6432 DeclareImplicitMoveConstructor(ClassDecl);
6433 }
6434
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006435 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6436 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006437
6438 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006439 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006440 // it shows up in the right place in the vtable and that we diagnose
6441 // problems with the implicit exception specification.
6442 if (ClassDecl->isDynamicClass() ||
6443 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006444 DeclareImplicitCopyAssignment(ClassDecl);
6445 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006446
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006447 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006448 ++ASTContext::NumImplicitMoveAssignmentOperators;
6449
6450 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006451 if (ClassDecl->isDynamicClass() ||
6452 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006453 DeclareImplicitMoveAssignment(ClassDecl);
6454 }
6455
Douglas Gregor7454c562010-07-02 20:37:36 +00006456 if (!ClassDecl->hasUserDeclaredDestructor()) {
6457 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006458
6459 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006460 // have to declare the destructor immediately. This ensures that, e.g., it
6461 // shows up in the right place in the vtable and that we diagnose problems
6462 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006463 if (ClassDecl->isDynamicClass() ||
6464 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006465 DeclareImplicitDestructor(ClassDecl);
6466 }
Douglas Gregor05379422008-11-03 17:51:48 +00006467}
6468
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006469unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006470 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006471 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006472
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006473 // The order of template parameters is not important here. All names
6474 // get added to the same scope.
6475 SmallVector<TemplateParameterList *, 4> ParameterLists;
6476
6477 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6478 D = TD->getTemplatedDecl();
6479
6480 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6481 ParameterLists.push_back(PSD->getTemplateParameters());
6482
6483 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6484 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6485 ParameterLists.push_back(DD->getTemplateParameterList(i));
6486
6487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6488 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6489 ParameterLists.push_back(FTD->getTemplateParameters());
6490 }
6491 }
6492
6493 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6494 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6495 ParameterLists.push_back(TD->getTemplateParameterList(i));
6496
6497 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6498 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6499 ParameterLists.push_back(CTD->getTemplateParameters());
6500 }
6501 }
6502
6503 unsigned Count = 0;
6504 for (TemplateParameterList *Params : ParameterLists) {
6505 if (Params->size() > 0)
6506 // Ignore explicit specializations; they don't contribute to the template
6507 // depth.
6508 ++Count;
6509 for (NamedDecl *Param : *Params) {
6510 if (Param->getDeclName()) {
6511 S->AddDecl(Param);
6512 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006513 }
6514 }
6515 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006516
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006517 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006518}
6519
John McCall48871652010-08-21 09:40:31 +00006520void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006521 if (!RecordD) return;
6522 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006523 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006524 PushDeclContext(S, Record);
6525}
6526
John McCall48871652010-08-21 09:40:31 +00006527void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006528 if (!RecordD) return;
6529 PopDeclContext();
6530}
6531
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006532/// This is used to implement the constant expression evaluation part of the
6533/// attribute enable_if extension. There is nothing in standard C++ which would
6534/// require reentering parameters.
6535void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6536 if (!Param)
6537 return;
6538
6539 S->AddDecl(Param);
6540 if (Param->getDeclName())
6541 IdResolver.AddDecl(Param);
6542}
6543
Douglas Gregor4d87df52008-12-16 21:30:33 +00006544/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6545/// parsing a top-level (non-nested) C++ class, and we are now
6546/// parsing those parts of the given Method declaration that could
6547/// not be parsed earlier (C++ [class.mem]p2), such as default
6548/// arguments. This action should enter the scope of the given
6549/// Method declaration as if we had just parsed the qualified method
6550/// name. However, it should not bring the parameters into scope;
6551/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006552void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006553}
6554
6555/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6556/// C++ method declaration. We're (re-)introducing the given
6557/// function parameter into scope for use in parsing later parts of
6558/// the method declaration. For example, we could see an
6559/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006560void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006561 if (!ParamD)
6562 return;
Mike Stump11289f42009-09-09 15:08:12 +00006563
John McCall48871652010-08-21 09:40:31 +00006564 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006565
6566 // If this parameter has an unparsed default argument, clear it out
6567 // to make way for the parsed default argument.
6568 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006569 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006570
John McCall48871652010-08-21 09:40:31 +00006571 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006572 if (Param->getDeclName())
6573 IdResolver.AddDecl(Param);
6574}
6575
6576/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6577/// processing the delayed method declaration for Method. The method
6578/// declaration is now considered finished. There may be a separate
6579/// ActOnStartOfFunctionDef action later (not necessarily
6580/// immediately!) for this method, if it was also defined inside the
6581/// class body.
John McCall48871652010-08-21 09:40:31 +00006582void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006583 if (!MethodD)
6584 return;
Mike Stump11289f42009-09-09 15:08:12 +00006585
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006586 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006587
John McCall48871652010-08-21 09:40:31 +00006588 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006589
6590 // Now that we have our default arguments, check the constructor
6591 // again. It could produce additional diagnostics or affect whether
6592 // the class has implicitly-declared destructors, among other
6593 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006594 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6595 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006596
6597 // Check the default arguments, which we may have added.
6598 if (!Method->isInvalidDecl())
6599 CheckCXXDefaultArguments(Method);
6600}
6601
Douglas Gregor831c93f2008-11-05 20:51:48 +00006602/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006603/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006604/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006605/// emit diagnostics and set the invalid bit to true. In any case, the type
6606/// will be updated to reflect a well-formed type for the constructor and
6607/// returned.
6608QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006609 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006610 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006611
6612 // C++ [class.ctor]p3:
6613 // A constructor shall not be virtual (10.3) or static (9.4). A
6614 // constructor can be invoked for a const, volatile or const
6615 // volatile object. A constructor shall not be declared const,
6616 // volatile, or const volatile (9.3.2).
6617 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006618 if (!D.isInvalidType())
6619 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6620 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6621 << SourceRange(D.getIdentifierLoc());
6622 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006623 }
John McCall8e7d6562010-08-26 03:08:43 +00006624 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006625 if (!D.isInvalidType())
6626 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6627 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6628 << SourceRange(D.getIdentifierLoc());
6629 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006630 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006631 }
Mike Stump11289f42009-09-09 15:08:12 +00006632
David Majnemer03f705f2014-07-08 18:18:04 +00006633 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6634 diagnoseIgnoredQualifiers(
6635 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6636 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6637 D.getDeclSpec().getRestrictSpecLoc(),
6638 D.getDeclSpec().getAtomicSpecLoc());
6639 D.setInvalidType();
6640 }
6641
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006643 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006644 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006645 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6646 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006647 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006648 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6649 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006650 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006651 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6652 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006653 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
Douglas Gregordb9d6642011-01-26 05:01:58 +00006656 // C++0x [class.ctor]p4:
6657 // A constructor shall not be declared with a ref-qualifier.
6658 if (FTI.hasRefQualifier()) {
6659 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6660 << FTI.RefQualifierIsLValueRef
6661 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6662 D.setInvalidType();
6663 }
6664
Douglas Gregor831c93f2008-11-05 20:51:48 +00006665 // Rebuild the function type "R" without any type qualifiers (in
6666 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006667 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006668 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006669 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006670 return R;
6671
6672 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6673 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006674 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006675
6676 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006677}
6678
Douglas Gregor4d87df52008-12-16 21:30:33 +00006679/// CheckConstructor - Checks a fully-formed constructor for
6680/// well-formedness, issuing any diagnostics required. Returns true if
6681/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006682void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006683 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006684 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6685 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006686 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006687
6688 // C++ [class.copy]p3:
6689 // A declaration of a constructor for a class X is ill-formed if
6690 // its first parameter is of type (optionally cv-qualified) X and
6691 // either there are no other parameters or else all other
6692 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006693 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006694 ((Constructor->getNumParams() == 1) ||
6695 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006696 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6697 Constructor->getTemplateSpecializationKind()
6698 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006699 QualType ParamType = Constructor->getParamDecl(0)->getType();
6700 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6701 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006702 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006703 const char *ConstRef
6704 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6705 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006706 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006707 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006708
6709 // FIXME: Rather that making the constructor invalid, we should endeavor
6710 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006711 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006712 }
6713 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006714}
6715
John McCalldeb646e2010-08-04 01:04:25 +00006716/// CheckDestructor - Checks a fully-formed destructor definition for
6717/// well-formedness, issuing any diagnostics required. Returns true
6718/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006719bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006720 CXXRecordDecl *RD = Destructor->getParent();
6721
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006722 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006723 SourceLocation Loc;
6724
6725 if (!Destructor->isImplicit())
6726 Loc = Destructor->getLocation();
6727 else
6728 Loc = RD->getLocation();
6729
6730 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006731 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006732 DeclarationName Name =
6733 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006734 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006735 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006736 // If there's no class-specific operator delete, look up the global
6737 // non-array delete.
6738 if (!OperatorDelete)
6739 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006740
Eli Friedmanfa0df832012-02-02 03:46:19 +00006741 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006742
6743 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006744 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006745
6746 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006747}
6748
Douglas Gregor831c93f2008-11-05 20:51:48 +00006749/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6750/// the well-formednes of the destructor declarator @p D with type @p
6751/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006752/// emit diagnostics and set the declarator to invalid. Even if this happens,
6753/// will be updated to reflect a well-formed type for the destructor and
6754/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006755QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006756 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006757 // C++ [class.dtor]p1:
6758 // [...] A typedef-name that names a class is a class-name
6759 // (7.1.3); however, a typedef-name that names a class shall not
6760 // be used as the identifier in the declarator for a destructor
6761 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006762 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006763 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006764 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006765 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006766 else if (const TemplateSpecializationType *TST =
6767 DeclaratorType->getAs<TemplateSpecializationType>())
6768 if (TST->isTypeAlias())
6769 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6770 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006771
6772 // C++ [class.dtor]p2:
6773 // A destructor is used to destroy objects of its class type. A
6774 // destructor takes no parameters, and no return type can be
6775 // specified for it (not even void). The address of a destructor
6776 // shall not be taken. A destructor shall not be static. A
6777 // destructor can be invoked for a const, volatile or const
6778 // volatile object. A destructor shall not be declared const,
6779 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006780 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006781 if (!D.isInvalidType())
6782 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6783 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006784 << SourceRange(D.getIdentifierLoc())
6785 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6786
John McCall8e7d6562010-08-26 03:08:43 +00006787 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006788 }
David Majnemer03f705f2014-07-08 18:18:04 +00006789 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006790 // Destructors don't have return types, but the parser will
6791 // happily parse something like:
6792 //
6793 // class X {
6794 // float ~X();
6795 // };
6796 //
6797 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006798 if (D.getDeclSpec().hasTypeSpecifier())
6799 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6800 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6801 << SourceRange(D.getIdentifierLoc());
6802 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6803 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6804 SourceLocation(),
6805 D.getDeclSpec().getConstSpecLoc(),
6806 D.getDeclSpec().getVolatileSpecLoc(),
6807 D.getDeclSpec().getRestrictSpecLoc(),
6808 D.getDeclSpec().getAtomicSpecLoc());
6809 D.setInvalidType();
6810 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006811 }
Mike Stump11289f42009-09-09 15:08:12 +00006812
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006814 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006815 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6817 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006818 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6820 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006821 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6823 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006824 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006825 }
6826
Douglas Gregordb9d6642011-01-26 05:01:58 +00006827 // C++0x [class.dtor]p2:
6828 // A destructor shall not be declared with a ref-qualifier.
6829 if (FTI.hasRefQualifier()) {
6830 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6831 << FTI.RefQualifierIsLValueRef
6832 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6833 D.setInvalidType();
6834 }
6835
Douglas Gregor831c93f2008-11-05 20:51:48 +00006836 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006837 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006838 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6839
6840 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006841 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006842 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006843 }
6844
Mike Stump11289f42009-09-09 15:08:12 +00006845 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006846 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006847 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006848 D.setInvalidType();
6849 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006850
6851 // Rebuild the function type "R" without any type qualifiers or
6852 // parameters (in case any of the errors above fired) and with
6853 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006854 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006855 if (!D.isInvalidType())
6856 return R;
6857
Douglas Gregor95755162010-07-01 05:10:53 +00006858 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006859 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6860 EPI.Variadic = false;
6861 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006862 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006863 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006864}
6865
Richard Smitha865a162014-12-19 02:07:47 +00006866static void extendLeft(SourceRange &R, const SourceRange &Before) {
6867 if (Before.isInvalid())
6868 return;
6869 R.setBegin(Before.getBegin());
6870 if (R.getEnd().isInvalid())
6871 R.setEnd(Before.getEnd());
6872}
6873
6874static void extendRight(SourceRange &R, const SourceRange &After) {
6875 if (After.isInvalid())
6876 return;
6877 if (R.getBegin().isInvalid())
6878 R.setBegin(After.getBegin());
6879 R.setEnd(After.getEnd());
6880}
6881
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006882/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6883/// well-formednes of the conversion function declarator @p D with
6884/// type @p R. If there are any errors in the declarator, this routine
6885/// will emit diagnostics and return true. Otherwise, it will return
6886/// false. Either way, the type @p R will be updated to reflect a
6887/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006888void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006889 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006890 // C++ [class.conv.fct]p1:
6891 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006892 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006893 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006894 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006895 if (!D.isInvalidType())
6896 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006897 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6898 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006899 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006900 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006901 }
John McCall212fa2e2010-04-13 00:04:31 +00006902
Richard Smitha865a162014-12-19 02:07:47 +00006903 TypeSourceInfo *ConvTSI = nullptr;
6904 QualType ConvType =
6905 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006906
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006907 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006908 // Conversion functions don't have return types, but the parser will
6909 // happily parse something like:
6910 //
6911 // class X {
6912 // float operator bool();
6913 // };
6914 //
6915 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006916 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6917 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6918 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006919 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006920 }
6921
John McCall212fa2e2010-04-13 00:04:31 +00006922 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6923
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006924 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006925 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006926 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6927
6928 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006929 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006930 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006931 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006932 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006933 D.setInvalidType();
6934 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006935
John McCall212fa2e2010-04-13 00:04:31 +00006936 // Diagnose "&operator bool()" and other such nonsense. This
6937 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006938 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006939 bool NeedsTypedef = false;
6940 SourceRange Before, After;
6941
6942 // Walk the chunks and extract information on them for our diagnostic.
6943 bool PastFunctionChunk = false;
6944 for (auto &Chunk : D.type_objects()) {
6945 switch (Chunk.Kind) {
6946 case DeclaratorChunk::Function:
6947 if (!PastFunctionChunk) {
6948 if (Chunk.Fun.HasTrailingReturnType) {
6949 TypeSourceInfo *TRT = nullptr;
6950 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6951 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6952 }
6953 PastFunctionChunk = true;
6954 break;
6955 }
6956 // Fall through.
6957 case DeclaratorChunk::Array:
6958 NeedsTypedef = true;
6959 extendRight(After, Chunk.getSourceRange());
6960 break;
6961
6962 case DeclaratorChunk::Pointer:
6963 case DeclaratorChunk::BlockPointer:
6964 case DeclaratorChunk::Reference:
6965 case DeclaratorChunk::MemberPointer:
6966 extendLeft(Before, Chunk.getSourceRange());
6967 break;
6968
6969 case DeclaratorChunk::Paren:
6970 extendLeft(Before, Chunk.Loc);
6971 extendRight(After, Chunk.EndLoc);
6972 break;
6973 }
6974 }
6975
6976 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6977 After.isValid() ? After.getBegin() :
6978 D.getIdentifierLoc();
6979 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6980 DB << Before << After;
6981
6982 if (!NeedsTypedef) {
6983 DB << /*don't need a typedef*/0;
6984
6985 // If we can provide a correct fix-it hint, do so.
6986 if (After.isInvalid() && ConvTSI) {
6987 SourceLocation InsertLoc =
6988 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6989 DB << FixItHint::CreateInsertion(InsertLoc, " ")
6990 << FixItHint::CreateInsertionFromRange(
6991 InsertLoc, CharSourceRange::getTokenRange(Before))
6992 << FixItHint::CreateRemoval(Before);
6993 }
6994 } else if (!Proto->getReturnType()->isDependentType()) {
6995 DB << /*typedef*/1 << Proto->getReturnType();
6996 } else if (getLangOpts().CPlusPlus11) {
6997 DB << /*alias template*/2 << Proto->getReturnType();
6998 } else {
6999 DB << /*might not be fixable*/3;
7000 }
7001
7002 // Recover by incorporating the other type chunks into the result type.
7003 // Note, this does *not* change the name of the function. This is compatible
7004 // with the GCC extension:
7005 // struct S { &operator int(); } s;
7006 // int &r = s.operator int(); // ok in GCC
7007 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007008 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007009 }
7010
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007011 // C++ [class.conv.fct]p4:
7012 // The conversion-type-id shall not represent a function type nor
7013 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007014 if (ConvType->isArrayType()) {
7015 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7016 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007017 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007018 } else if (ConvType->isFunctionType()) {
7019 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7020 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007021 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007022 }
7023
7024 // Rebuild the function type "R" without any parameters (in case any
7025 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007026 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007027 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007028 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007029
Douglas Gregor5fb53972009-01-14 15:45:31 +00007030 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007031 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007032 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007033 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007034 diag::warn_cxx98_compat_explicit_conversion_functions :
7035 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007036 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007037}
7038
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007039/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7040/// the declaration of the given C++ conversion function. This routine
7041/// is responsible for recording the conversion function in the C++
7042/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007043Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007044 assert(Conversion && "Expected to receive a conversion function declaration");
7045
Douglas Gregor4287b372008-12-12 08:25:50 +00007046 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007047
7048 // Make sure we aren't redeclaring the conversion function.
7049 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007050
7051 // C++ [class.conv.fct]p1:
7052 // [...] A conversion function is never used to convert a
7053 // (possibly cv-qualified) object to the (possibly cv-qualified)
7054 // same object type (or a reference to it), to a (possibly
7055 // cv-qualified) base class of that type (or a reference to it),
7056 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007057 // FIXME: Suppress this warning if the conversion function ends up being a
7058 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007059 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007060 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007061 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007062 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007063 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7064 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007065 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007066 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007067 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7068 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007069 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007070 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007071 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007072 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007073 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007074 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007075 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007076 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007077 }
7078
Douglas Gregor457104e2010-09-29 04:25:11 +00007079 if (FunctionTemplateDecl *ConversionTemplate
7080 = Conversion->getDescribedFunctionTemplate())
7081 return ConversionTemplate;
7082
John McCall48871652010-08-21 09:40:31 +00007083 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007084}
7085
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007086//===----------------------------------------------------------------------===//
7087// Namespace Handling
7088//===----------------------------------------------------------------------===//
7089
Richard Smith45bb8852012-10-04 22:13:39 +00007090/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7091/// reopened.
7092static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7093 SourceLocation Loc,
7094 IdentifierInfo *II, bool *IsInline,
7095 NamespaceDecl *PrevNS) {
7096 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007097
Richard Smithf501cc32012-10-05 01:46:25 +00007098 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7099 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7100 // inline namespaces, with the intention of bringing names into namespace std.
7101 //
7102 // We support this just well enough to get that case working; this is not
7103 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007104 if (*IsInline && II && II->getName().startswith("__atomic") &&
7105 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007106 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007107 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7108 NS = NS->getPreviousDecl())
7109 NS->setInline(*IsInline);
7110 // Patch up the lookup table for the containing namespace. This isn't really
7111 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007112 for (auto *I : PrevNS->decls())
7113 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007114 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7115 return;
7116 }
7117
7118 if (PrevNS->isInline())
7119 // The user probably just forgot the 'inline', so suggest that it
7120 // be added back.
7121 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7122 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7123 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007124 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007125
7126 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7127 *IsInline = PrevNS->isInline();
7128}
John McCallb1be5232010-08-26 09:15:37 +00007129
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007130/// ActOnStartNamespaceDef - This is called at the start of a namespace
7131/// definition.
John McCall48871652010-08-21 09:40:31 +00007132Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007133 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007134 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007135 SourceLocation IdentLoc,
7136 IdentifierInfo *II,
7137 SourceLocation LBrace,
7138 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007139 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7140 // For anonymous namespace, take the location of the left brace.
7141 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007142 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007143 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007144 bool IsStd = false;
7145 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007146 Scope *DeclRegionScope = NamespcScope->getParent();
7147
Craig Topperc3ec1492014-05-26 06:22:03 +00007148 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007149 if (II) {
7150 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007151 // The identifier in an original-namespace-definition shall not
7152 // have been previously defined in the declarative region in
7153 // which the original-namespace-definition appears. The
7154 // identifier in an original-namespace-definition is the name of
7155 // the namespace. Subsequently in that declarative region, it is
7156 // treated as an original-namespace-name.
7157 //
7158 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007159 // look through using directives, just look for any ordinary names.
7160
7161 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007162 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7163 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007164 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007165 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7166 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7167 ++I) {
7168 if ((*I)->getIdentifierNamespace() & IDNS) {
7169 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007170 break;
7171 }
7172 }
7173
Douglas Gregore57e7522012-01-07 09:11:48 +00007174 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7175
7176 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007177 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007178 if (IsInline != PrevNS->isInline())
7179 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7180 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007181 } else if (PrevDecl) {
7182 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007183 Diag(Loc, diag::err_redefinition_different_kind)
7184 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007185 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007186 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007187 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007188 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007189 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007190 // This is the first "real" definition of the namespace "std", so update
7191 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007192 PrevNS = getStdNamespace();
7193 IsStd = true;
7194 AddToKnown = !IsInline;
7195 } else {
7196 // We've seen this namespace for the first time.
7197 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007198 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007199 } else {
John McCall4fa53422009-10-01 00:25:31 +00007200 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007201
7202 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007203 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007204 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007205 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007206 } else {
7207 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007208 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007209 }
7210
Richard Smith45bb8852012-10-04 22:13:39 +00007211 if (PrevNS && IsInline != PrevNS->isInline())
7212 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7213 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007214 }
7215
7216 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7217 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007218 if (IsInvalid)
7219 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007220
7221 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007222
Douglas Gregore57e7522012-01-07 09:11:48 +00007223 // FIXME: Should we be merging attributes?
7224 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007225 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007226
7227 if (IsStd)
7228 StdNamespace = Namespc;
7229 if (AddToKnown)
7230 KnownNamespaces[Namespc] = false;
7231
7232 if (II) {
7233 PushOnScopeChains(Namespc, DeclRegionScope);
7234 } else {
7235 // Link the anonymous namespace into its parent.
7236 DeclContext *Parent = CurContext->getRedeclContext();
7237 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7238 TU->setAnonymousNamespace(Namespc);
7239 } else {
7240 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007241 }
John McCall4fa53422009-10-01 00:25:31 +00007242
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007243 CurContext->addDecl(Namespc);
7244
John McCall4fa53422009-10-01 00:25:31 +00007245 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7246 // behaves as if it were replaced by
7247 // namespace unique { /* empty body */ }
7248 // using namespace unique;
7249 // namespace unique { namespace-body }
7250 // where all occurrences of 'unique' in a translation unit are
7251 // replaced by the same identifier and this identifier differs
7252 // from all other identifiers in the entire program.
7253
7254 // We just create the namespace with an empty name and then add an
7255 // implicit using declaration, just like the standard suggests.
7256 //
7257 // CodeGen enforces the "universally unique" aspect by giving all
7258 // declarations semantically contained within an anonymous
7259 // namespace internal linkage.
7260
Douglas Gregore57e7522012-01-07 09:11:48 +00007261 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007262 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007263 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007264 /* 'using' */ LBrace,
7265 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007266 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007267 /* identifier */ SourceLocation(),
7268 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007269 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007270 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007271 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007272 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007273 }
7274
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007275 ActOnDocumentableDecl(Namespc);
7276
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007277 // Although we could have an invalid decl (i.e. the namespace name is a
7278 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007279 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7280 // for the namespace has the declarations that showed up in that particular
7281 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007282 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007283 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007284}
7285
Sebastian Redla6602e92009-11-23 15:34:23 +00007286/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7287/// is a namespace alias, returns the namespace it points to.
7288static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7289 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7290 return AD->getNamespace();
7291 return dyn_cast_or_null<NamespaceDecl>(D);
7292}
7293
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007294/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7295/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007296void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007297 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7298 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007299 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007300 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007301 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007302 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007303}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007304
John McCall28a0cf72010-08-25 07:42:41 +00007305CXXRecordDecl *Sema::getStdBadAlloc() const {
7306 return cast_or_null<CXXRecordDecl>(
7307 StdBadAlloc.get(Context.getExternalSource()));
7308}
7309
7310NamespaceDecl *Sema::getStdNamespace() const {
7311 return cast_or_null<NamespaceDecl>(
7312 StdNamespace.get(Context.getExternalSource()));
7313}
7314
Douglas Gregorcdf87022010-06-29 17:53:46 +00007315/// \brief Retrieve the special "std" namespace, which may require us to
7316/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007317NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007318 if (!StdNamespace) {
7319 // The "std" namespace has not yet been defined, so build one implicitly.
7320 StdNamespace = NamespaceDecl::Create(Context,
7321 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007322 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007323 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007324 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007325 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007326 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007327 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007328
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007329 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007330}
7331
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007332bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007333 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007334 "Looking for std::initializer_list outside of C++.");
7335
7336 // We're looking for implicit instantiations of
7337 // template <typename E> class std::initializer_list.
7338
7339 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7340 return false;
7341
Craig Topperc3ec1492014-05-26 06:22:03 +00007342 ClassTemplateDecl *Template = nullptr;
7343 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007344
Sebastian Redl43144e72012-01-17 22:49:58 +00007345 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007346
Sebastian Redl43144e72012-01-17 22:49:58 +00007347 ClassTemplateSpecializationDecl *Specialization =
7348 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7349 if (!Specialization)
7350 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007351
Sebastian Redl43144e72012-01-17 22:49:58 +00007352 Template = Specialization->getSpecializedTemplate();
7353 Arguments = Specialization->getTemplateArgs().data();
7354 } else if (const TemplateSpecializationType *TST =
7355 Ty->getAs<TemplateSpecializationType>()) {
7356 Template = dyn_cast_or_null<ClassTemplateDecl>(
7357 TST->getTemplateName().getAsTemplateDecl());
7358 Arguments = TST->getArgs();
7359 }
7360 if (!Template)
7361 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007362
7363 if (!StdInitializerList) {
7364 // Haven't recognized std::initializer_list yet, maybe this is it.
7365 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7366 if (TemplateClass->getIdentifier() !=
7367 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007368 !getStdNamespace()->InEnclosingNamespaceSetOf(
7369 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007370 return false;
7371 // This is a template called std::initializer_list, but is it the right
7372 // template?
7373 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007374 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007375 return false;
7376 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7377 return false;
7378
7379 // It's the right template.
7380 StdInitializerList = Template;
7381 }
7382
Richard Smith7d7dee72015-02-24 03:30:14 +00007383 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007384 return false;
7385
7386 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007387 if (Element)
7388 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007389 return true;
7390}
7391
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007392static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7393 NamespaceDecl *Std = S.getStdNamespace();
7394 if (!Std) {
7395 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007396 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007397 }
7398
7399 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7400 Loc, Sema::LookupOrdinaryName);
7401 if (!S.LookupQualifiedName(Result, Std)) {
7402 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007403 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007404 }
7405 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7406 if (!Template) {
7407 Result.suppressDiagnostics();
7408 // We found something weird. Complain about the first thing we found.
7409 NamedDecl *Found = *Result.begin();
7410 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007411 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007412 }
7413
7414 // We found some template called std::initializer_list. Now verify that it's
7415 // correct.
7416 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007417 if (Params->getMinRequiredArguments() != 1 ||
7418 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007419 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007420 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007421 }
7422
7423 return Template;
7424}
7425
7426QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7427 if (!StdInitializerList) {
7428 StdInitializerList = LookupStdInitializerList(*this, Loc);
7429 if (!StdInitializerList)
7430 return QualType();
7431 }
7432
7433 TemplateArgumentListInfo Args(Loc, Loc);
7434 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7435 Context.getTrivialTypeSourceInfo(Element,
7436 Loc)));
7437 return Context.getCanonicalType(
7438 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7439}
7440
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007441bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7442 // C++ [dcl.init.list]p2:
7443 // A constructor is an initializer-list constructor if its first parameter
7444 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7445 // std::initializer_list<E> for some type E, and either there are no other
7446 // parameters or else all other parameters have default arguments.
7447 if (Ctor->getNumParams() < 1 ||
7448 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7449 return false;
7450
7451 QualType ArgType = Ctor->getParamDecl(0)->getType();
7452 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7453 ArgType = RT->getPointeeType().getUnqualifiedType();
7454
Craig Topperc3ec1492014-05-26 06:22:03 +00007455 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007456}
7457
Douglas Gregora172e082011-03-26 22:25:30 +00007458/// \brief Determine whether a using statement is in a context where it will be
7459/// apply in all contexts.
7460static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7461 switch (CurContext->getDeclKind()) {
7462 case Decl::TranslationUnit:
7463 return true;
7464 case Decl::LinkageSpec:
7465 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7466 default:
7467 return false;
7468 }
7469}
7470
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007471namespace {
7472
7473// Callback to only accept typo corrections that are namespaces.
7474class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007475public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007476 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007477 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007478 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007479 return false;
7480 }
7481};
7482
7483}
7484
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007485static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7486 CXXScopeSpec &SS,
7487 SourceLocation IdentLoc,
7488 IdentifierInfo *Ident) {
7489 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007490 if (TypoCorrection Corrected =
7491 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7492 llvm::make_unique<NamespaceValidatorCCC>(),
7493 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007494 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007495 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7496 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007497 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007498 S.diagnoseTypo(Corrected,
7499 S.PDiag(diag::err_using_directive_member_suggest)
7500 << Ident << DC << DroppedSpecifier << SS.getRange(),
7501 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007502 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007503 S.diagnoseTypo(Corrected,
7504 S.PDiag(diag::err_using_directive_suggest) << Ident,
7505 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007506 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007507 R.addDecl(Corrected.getCorrectionDecl());
7508 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007509 }
7510 return false;
7511}
7512
John McCall48871652010-08-21 09:40:31 +00007513Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007514 SourceLocation UsingLoc,
7515 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007516 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007517 SourceLocation IdentLoc,
7518 IdentifierInfo *NamespcName,
7519 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007520 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7521 assert(NamespcName && "Invalid NamespcName.");
7522 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007523
7524 // This can only happen along a recovery path.
7525 while (S->getFlags() & Scope::TemplateParamScope)
7526 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007527 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007528
Craig Topperc3ec1492014-05-26 06:22:03 +00007529 UsingDirectiveDecl *UDir = nullptr;
7530 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007531 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007532 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007533
Douglas Gregor34074322009-01-14 22:20:51 +00007534 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007535 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7536 LookupParsedName(R, S, &SS);
7537 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007538 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007539
Douglas Gregorcdf87022010-06-29 17:53:46 +00007540 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007541 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007542 // Allow "using namespace std;" or "using namespace ::std;" even if
7543 // "std" hasn't been defined yet, for GCC compatibility.
7544 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7545 NamespcName->isStr("std")) {
7546 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007547 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007548 R.resolveKind();
7549 }
7550 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007551 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007552 }
7553
John McCall9f3059a2009-10-09 21:13:30 +00007554 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007555 NamedDecl *Named = R.getFoundDecl();
7556 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7557 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007558
Nico Riecke50e59a2014-11-24 17:29:52 +00007559 // The use of a nested name specifier may trigger deprecation warnings.
7560 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007561
Douglas Gregor889ceb72009-02-03 19:21:40 +00007562 // C++ [namespace.udir]p1:
7563 // A using-directive specifies that the names in the nominated
7564 // namespace can be used in the scope in which the
7565 // using-directive appears after the using-directive. During
7566 // unqualified name lookup (3.4.1), the names appear as if they
7567 // were declared in the nearest enclosing namespace which
7568 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007569 // namespace. [Note: in this context, "contains" means "contains
7570 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007571
7572 // Find enclosing context containing both using-directive and
7573 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007574 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007575 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7576 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7577 CommonAncestor = CommonAncestor->getParent();
7578
Sebastian Redla6602e92009-11-23 15:34:23 +00007579 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007580 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007581 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007582
Douglas Gregora172e082011-03-26 22:25:30 +00007583 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007584 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007585 Diag(IdentLoc, diag::warn_using_directive_in_header);
7586 }
7587
Douglas Gregor889ceb72009-02-03 19:21:40 +00007588 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007589 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007590 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007591 }
7592
Richard Smith54ecd982013-02-20 19:22:51 +00007593 if (UDir)
7594 ProcessDeclAttributeList(S, UDir, AttrList);
7595
John McCall48871652010-08-21 09:40:31 +00007596 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007597}
7598
7599void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007600 // If the scope has an associated entity and the using directive is at
7601 // namespace or translation unit scope, add the UsingDirectiveDecl into
7602 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007603 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007604 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007605 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007606 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007607 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007608 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007609 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007610}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007611
Douglas Gregorfec52632009-06-20 00:51:54 +00007612
John McCall48871652010-08-21 09:40:31 +00007613Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007614 AccessSpecifier AS,
7615 bool HasUsingKeyword,
7616 SourceLocation UsingLoc,
7617 CXXScopeSpec &SS,
7618 UnqualifiedId &Name,
7619 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007620 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007621 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007622 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007623
Douglas Gregor220f4272009-11-04 16:30:06 +00007624 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007625 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007626 case UnqualifiedId::IK_Identifier:
7627 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007628 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007629 case UnqualifiedId::IK_ConversionFunctionId:
7630 break;
7631
7632 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007633 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007634 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007635 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007636 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007637 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007638 diag::err_using_decl_constructor)
7639 << SS.getRange();
7640
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007641 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007642
Craig Topperc3ec1492014-05-26 06:22:03 +00007643 return nullptr;
7644
Douglas Gregor220f4272009-11-04 16:30:06 +00007645 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007646 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007647 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007648 return nullptr;
7649
Douglas Gregor220f4272009-11-04 16:30:06 +00007650 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007651 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007652 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007653 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007654 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007655
7656 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7657 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007658 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007659 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007660
Richard Smithc2bc61b2013-03-18 21:12:30 +00007661 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007662 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007663 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007664 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7665 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007666 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007667 }
7668
Douglas Gregorc4356532010-12-16 00:46:58 +00007669 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7670 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007671 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007672
John McCall3f746822009-11-17 05:59:44 +00007673 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007674 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007675 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007676 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007677 if (UD)
7678 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007679
John McCall48871652010-08-21 09:40:31 +00007680 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007681}
7682
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007683/// \brief Determine whether a using declaration considers the given
7684/// declarations as "equivalent", e.g., if they are redeclarations of
7685/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007686static bool
7687IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7688 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007689 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007690
Richard Smithdda56e42011-04-15 14:24:37 +00007691 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007692 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007693 return Context.hasSameType(TD1->getUnderlyingType(),
7694 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007695
7696 return false;
7697}
7698
7699
John McCall84d87672009-12-10 09:41:52 +00007700/// Determines whether to create a using shadow decl for a particular
7701/// decl, given the set of decls existing prior to this using lookup.
7702bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007703 const LookupResult &Previous,
7704 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007705 // Diagnose finding a decl which is not from a base class of the
7706 // current class. We do this now because there are cases where this
7707 // function will silently decide not to build a shadow decl, which
7708 // will pre-empt further diagnostics.
7709 //
7710 // We don't need to do this in C++0x because we do the check once on
7711 // the qualifier.
7712 //
7713 // FIXME: diagnose the following if we care enough:
7714 // struct A { int foo; };
7715 // struct B : A { using A::foo; };
7716 // template <class T> struct C : A {};
7717 // template <class T> struct D : C<T> { using B::foo; } // <---
7718 // This is invalid (during instantiation) in C++03 because B::foo
7719 // resolves to the using decl in B, which is not a base class of D<T>.
7720 // We can't diagnose it immediately because C<T> is an unknown
7721 // specialization. The UsingShadowDecl in D<T> then points directly
7722 // to A::foo, which will look well-formed when we instantiate.
7723 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007724 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007725 DeclContext *OrigDC = Orig->getDeclContext();
7726
7727 // Handle enums and anonymous structs.
7728 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7729 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7730 while (OrigRec->isAnonymousStructOrUnion())
7731 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7732
7733 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7734 if (OrigDC == CurContext) {
7735 Diag(Using->getLocation(),
7736 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007737 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007738 Diag(Orig->getLocation(), diag::note_using_decl_target);
7739 return true;
7740 }
7741
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007742 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007743 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007744 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007745 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007746 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007747 Diag(Orig->getLocation(), diag::note_using_decl_target);
7748 return true;
7749 }
7750 }
7751
7752 if (Previous.empty()) return false;
7753
7754 NamedDecl *Target = Orig;
7755 if (isa<UsingShadowDecl>(Target))
7756 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7757
John McCalla17e83e2009-12-11 02:33:26 +00007758 // If the target happens to be one of the previous declarations, we
7759 // don't have a conflict.
7760 //
7761 // FIXME: but we might be increasing its access, in which case we
7762 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007763 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007764 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007765 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7766 I != E; ++I) {
7767 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007768 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7769 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7770 PrevShadow = Shadow;
7771 FoundEquivalentDecl = true;
7772 }
John McCalla17e83e2009-12-11 02:33:26 +00007773
7774 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7775 }
7776
Richard Smithfd8634a2013-10-23 02:17:46 +00007777 if (FoundEquivalentDecl)
7778 return false;
7779
Alp Tokera2794f92014-01-22 07:29:52 +00007780 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007781 NamedDecl *OldDecl = nullptr;
7782 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7783 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007784 case Ovl_Overload:
7785 return false;
7786
7787 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007788 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007789 break;
Richard Smith18819302014-02-06 01:31:33 +00007790
John McCall84d87672009-12-10 09:41:52 +00007791 // We found a decl with the exact signature.
7792 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007793 // If we're in a record, we want to hide the target, so we
7794 // return true (without a diagnostic) to tell the caller not to
7795 // build a shadow decl.
7796 if (CurContext->isRecord())
7797 return true;
7798
7799 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007800 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007801 break;
7802 }
7803
7804 Diag(Target->getLocation(), diag::note_using_decl_target);
7805 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7806 return true;
7807 }
7808
7809 // Target is not a function.
7810
John McCall84d87672009-12-10 09:41:52 +00007811 if (isa<TagDecl>(Target)) {
7812 // No conflict between a tag and a non-tag.
7813 if (!Tag) return false;
7814
John McCalle29c5cd2009-12-10 19:51:03 +00007815 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007816 Diag(Target->getLocation(), diag::note_using_decl_target);
7817 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7818 return true;
7819 }
7820
7821 // No conflict between a tag and a non-tag.
7822 if (!NonTag) return false;
7823
John McCalle29c5cd2009-12-10 19:51:03 +00007824 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007825 Diag(Target->getLocation(), diag::note_using_decl_target);
7826 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7827 return true;
7828}
7829
John McCall3f746822009-11-17 05:59:44 +00007830/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007831UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007832 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007833 NamedDecl *Orig,
7834 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007835
7836 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007837 NamedDecl *Target = Orig;
7838 if (isa<UsingShadowDecl>(Target)) {
7839 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7840 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007841 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007842
John McCall3f746822009-11-17 05:59:44 +00007843 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007844 = UsingShadowDecl::Create(Context, CurContext,
7845 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007846 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007847
Douglas Gregor457104e2010-09-29 04:25:11 +00007848 Shadow->setAccess(UD->getAccess());
7849 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7850 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007851
7852 Shadow->setPreviousDecl(PrevDecl);
7853
John McCall3f746822009-11-17 05:59:44 +00007854 if (S)
John McCall3969e302009-12-08 07:46:18 +00007855 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007856 else
John McCall3969e302009-12-08 07:46:18 +00007857 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007858
John McCall3969e302009-12-08 07:46:18 +00007859
John McCall84d87672009-12-10 09:41:52 +00007860 return Shadow;
7861}
John McCall3969e302009-12-08 07:46:18 +00007862
John McCall84d87672009-12-10 09:41:52 +00007863/// Hides a using shadow declaration. This is required by the current
7864/// using-decl implementation when a resolvable using declaration in a
7865/// class is followed by a declaration which would hide or override
7866/// one or more of the using decl's targets; for example:
7867///
7868/// struct Base { void foo(int); };
7869/// struct Derived : Base {
7870/// using Base::foo;
7871/// void foo(int);
7872/// };
7873///
7874/// The governing language is C++03 [namespace.udecl]p12:
7875///
7876/// When a using-declaration brings names from a base class into a
7877/// derived class scope, member functions in the derived class
7878/// override and/or hide member functions with the same name and
7879/// parameter types in a base class (rather than conflicting).
7880///
7881/// There are two ways to implement this:
7882/// (1) optimistically create shadow decls when they're not hidden
7883/// by existing declarations, or
7884/// (2) don't create any shadow decls (or at least don't make them
7885/// visible) until we've fully parsed/instantiated the class.
7886/// The problem with (1) is that we might have to retroactively remove
7887/// a shadow decl, which requires several O(n) operations because the
7888/// decl structures are (very reasonably) not designed for removal.
7889/// (2) avoids this but is very fiddly and phase-dependent.
7890void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007891 if (Shadow->getDeclName().getNameKind() ==
7892 DeclarationName::CXXConversionFunctionName)
7893 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7894
John McCall84d87672009-12-10 09:41:52 +00007895 // Remove it from the DeclContext...
7896 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007897
John McCall84d87672009-12-10 09:41:52 +00007898 // ...and the scope, if applicable...
7899 if (S) {
John McCall48871652010-08-21 09:40:31 +00007900 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007901 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007902 }
7903
John McCall84d87672009-12-10 09:41:52 +00007904 // ...and the using decl.
7905 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7906
7907 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007908 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007909}
7910
Richard Smith09d5b3a2014-05-01 00:35:04 +00007911/// Find the base specifier for a base class with the given type.
7912static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7913 QualType DesiredBase,
7914 bool &AnyDependentBases) {
7915 // Check whether the named type is a direct base class.
7916 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7917 for (auto &Base : Derived->bases()) {
7918 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7919 if (CanonicalDesiredBase == BaseType)
7920 return &Base;
7921 if (BaseType->isDependentType())
7922 AnyDependentBases = true;
7923 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007924 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007925}
7926
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007927namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007928class UsingValidatorCCC : public CorrectionCandidateCallback {
7929public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007930 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007931 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007932 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007933 IsInstantiation(IsInstantiation), OldNNS(NNS),
7934 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007935
Craig Toppera798a9d2014-03-02 09:32:10 +00007936 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007937 NamedDecl *ND = Candidate.getCorrectionDecl();
7938
7939 // Keywords are not valid here.
7940 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007941 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007942
7943 // Completely unqualified names are invalid for a 'using' declaration.
7944 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7945 return false;
7946
Richard Smith09d5b3a2014-05-01 00:35:04 +00007947 if (RequireMemberOf) {
7948 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7949 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7950 // No-one ever wants a using-declaration to name an injected-class-name
7951 // of a base class, unless they're declaring an inheriting constructor.
7952 ASTContext &Ctx = ND->getASTContext();
7953 if (!Ctx.getLangOpts().CPlusPlus11)
7954 return false;
7955 QualType FoundType = Ctx.getRecordType(FoundRecord);
7956
7957 // Check that the injected-class-name is named as a member of its own
7958 // type; we don't want to suggest 'using Derived::Base;', since that
7959 // means something else.
7960 NestedNameSpecifier *Specifier =
7961 Candidate.WillReplaceSpecifier()
7962 ? Candidate.getCorrectionSpecifier()
7963 : OldNNS;
7964 if (!Specifier->getAsType() ||
7965 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7966 return false;
7967
7968 // Check that this inheriting constructor declaration actually names a
7969 // direct base class of the current class.
7970 bool AnyDependentBases = false;
7971 if (!findDirectBaseWithType(RequireMemberOf,
7972 Ctx.getRecordType(FoundRecord),
7973 AnyDependentBases) &&
7974 !AnyDependentBases)
7975 return false;
7976 } else {
7977 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7978 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7979 return false;
7980
7981 // FIXME: Check that the base class member is accessible?
7982 }
7983 }
7984
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007985 if (isa<TypeDecl>(ND))
7986 return HasTypenameKeyword || !IsInstantiation;
7987
7988 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007989 }
7990
7991private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007992 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007993 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007994 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007995 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007996};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007997} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007998
John McCalle61f2ba2009-11-18 02:36:19 +00007999/// Builds a using declaration.
8000///
8001/// \param IsInstantiation - Whether this call arises from an
8002/// instantiation of an unresolved using declaration. We treat
8003/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008004NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8005 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008006 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008007 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008008 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008009 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008010 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008011 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008012 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008013 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008014 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008015
Anders Carlssonf038fc22009-08-28 05:49:21 +00008016 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008017
Anders Carlsson59140b32009-08-28 03:16:11 +00008018 if (SS.isEmpty()) {
8019 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008020 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008021 }
Mike Stump11289f42009-09-09 15:08:12 +00008022
John McCall84d87672009-12-10 09:41:52 +00008023 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008024 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008025 ForRedeclaration);
8026 Previous.setHideTags(false);
8027 if (S) {
8028 LookupName(Previous, S);
8029
8030 // It is really dumb that we have to do this.
8031 LookupResult::Filter F = Previous.makeFilter();
8032 while (F.hasNext()) {
8033 NamedDecl *D = F.next();
8034 if (!isDeclInScope(D, CurContext, S))
8035 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008036 // If we found a local extern declaration that's not ordinarily visible,
8037 // and this declaration is being added to a non-block scope, ignore it.
8038 // We're only checking for scope conflicts here, not also for violations
8039 // of the linkage rules.
8040 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8041 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8042 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008043 }
8044 F.done();
8045 } else {
8046 assert(IsInstantiation && "no scope in non-instantiation");
8047 assert(CurContext->isRecord() && "scope not record in instantiation");
8048 LookupQualifiedName(Previous, CurContext);
8049 }
8050
John McCall84d87672009-12-10 09:41:52 +00008051 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008052 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8053 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008054 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008055
8056 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008057 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008058 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008059
John McCall84c16cf2009-11-12 03:15:40 +00008060 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008061 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008062 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008063 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008064 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008065 // FIXME: not all declaration name kinds are legal here
8066 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8067 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008068 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008069 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008070 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008071 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8072 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008073 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008074 D->setAccess(AS);
8075 CurContext->addDecl(D);
8076 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008077 }
John McCallb96ec562009-12-04 22:46:56 +00008078
Richard Smith09d5b3a2014-05-01 00:35:04 +00008079 auto Build = [&](bool Invalid) {
8080 UsingDecl *UD =
8081 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8082 HasTypenameKeyword);
8083 UD->setAccess(AS);
8084 CurContext->addDecl(UD);
8085 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008086 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008087 };
8088 auto BuildInvalid = [&]{ return Build(true); };
8089 auto BuildValid = [&]{ return Build(false); };
8090
8091 if (RequireCompleteDeclContext(SS, LookupContext))
8092 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008093
Richard Smith23d55872012-04-02 01:30:27 +00008094 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00008095 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00008096 UsingDecl *UD = BuildValid();
8097 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00008098 return UD;
8099 }
8100
8101 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00008102
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008103 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008104
John McCall3969e302009-12-08 07:46:18 +00008105 // Unlike most lookups, we don't always want to hide tag
8106 // declarations: tag names are visible through the using declaration
8107 // even if hidden by ordinary names, *except* in a dependent context
8108 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008109 if (!IsInstantiation)
8110 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008111
John McCall5dadb652012-04-07 03:04:20 +00008112 // For the purposes of this lookup, we have a base object type
8113 // equal to that of the current context.
8114 if (CurContext->isRecord()) {
8115 R.setBaseObjectType(
8116 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8117 }
8118
John McCall27b18f82009-11-17 02:14:36 +00008119 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008120
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008121 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00008122 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008123 if (TypoCorrection Corrected = CorrectTypo(
8124 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8125 llvm::make_unique<UsingValidatorCCC>(
8126 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8127 dyn_cast<CXXRecordDecl>(CurContext)),
8128 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008129 // We reject any correction for which ND would be NULL.
8130 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008131
Richard Smithf9b15102013-08-17 00:46:16 +00008132 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008133 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008134 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8135 << NameInfo.getName() << LookupContext << 0
8136 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008137
8138 // If we corrected to an inheriting constructor, handle it as one.
8139 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8140 if (RD && RD->isInjectedClassName()) {
8141 // Fix up the information we'll use to build the using declaration.
8142 if (Corrected.WillReplaceSpecifier()) {
8143 NestedNameSpecifierLocBuilder Builder;
8144 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8145 QualifierLoc.getSourceRange());
8146 QualifierLoc = Builder.getWithLocInContext(Context);
8147 }
8148
8149 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8150 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008151 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008152
8153 // Build it and process it as an inheriting constructor.
8154 UsingDecl *UD = BuildValid();
8155 CheckInheritingConstructorUsingDecl(UD);
8156 return UD;
8157 }
8158
8159 // FIXME: Pick up all the declarations if we found an overloaded function.
8160 R.setLookupName(Corrected.getCorrection());
8161 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008162 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008163 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008164 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008165 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008166 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008167 }
8168
Richard Smith09d5b3a2014-05-01 00:35:04 +00008169 if (R.isAmbiguous())
8170 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008171
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008172 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008173 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008174 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008175 Diag(IdentLoc, diag::err_using_typename_non_type);
8176 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8177 Diag((*I)->getUnderlyingDecl()->getLocation(),
8178 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008179 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008180 }
8181 } else {
8182 // If we asked for a non-typename and we got a type, error out,
8183 // but only if this is an instantiation of an unresolved using
8184 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008185 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008186 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8187 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008188 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008189 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008190 }
8191
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008192 // C++0x N2914 [namespace.udecl]p6:
8193 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008194 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008195 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8196 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008197 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008198 }
Mike Stump11289f42009-09-09 15:08:12 +00008199
Richard Smith09d5b3a2014-05-01 00:35:04 +00008200 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008201 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008202 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008203 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8204 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008205 }
John McCall3f746822009-11-17 05:59:44 +00008206
8207 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008208}
8209
Sebastian Redl08905022011-02-05 19:23:19 +00008210/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008211bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008212 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008213
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008214 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008215 assert(SourceType &&
8216 "Using decl naming constructor doesn't have type in scope spec.");
8217 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8218
8219 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008220 bool AnyDependentBases = false;
8221 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8222 AnyDependentBases);
8223 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008224 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008225 diag::err_using_decl_constructor_not_in_direct_base)
8226 << UD->getNameInfo().getSourceRange()
8227 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008228 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008229 return true;
8230 }
8231
Richard Smith09d5b3a2014-05-01 00:35:04 +00008232 if (Base)
8233 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008234
8235 return false;
8236}
8237
John McCall84d87672009-12-10 09:41:52 +00008238/// Checks that the given using declaration is not an invalid
8239/// redeclaration. Note that this is checking only for the using decl
8240/// itself, not for any ill-formedness among the UsingShadowDecls.
8241bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008242 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008243 const CXXScopeSpec &SS,
8244 SourceLocation NameLoc,
8245 const LookupResult &Prev) {
8246 // C++03 [namespace.udecl]p8:
8247 // C++0x [namespace.udecl]p10:
8248 // A using-declaration is a declaration and can therefore be used
8249 // repeatedly where (and only where) multiple declarations are
8250 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008251 //
John McCall032092f2010-11-29 18:01:58 +00008252 // That's in non-member contexts.
8253 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008254 return false;
8255
Aaron Ballman4a979672014-01-03 13:56:08 +00008256 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008257
8258 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8259 NamedDecl *D = *I;
8260
8261 bool DTypename;
8262 NestedNameSpecifier *DQual;
8263 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008264 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008265 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008266 } else if (UnresolvedUsingValueDecl *UD
8267 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8268 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008269 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008270 } else if (UnresolvedUsingTypenameDecl *UD
8271 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8272 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008273 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008274 } else continue;
8275
8276 // using decls differ if one says 'typename' and the other doesn't.
8277 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008278 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008279
8280 // using decls differ if they name different scopes (but note that
8281 // template instantiation can cause this check to trigger when it
8282 // didn't before instantiation).
8283 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8284 Context.getCanonicalNestedNameSpecifier(DQual))
8285 continue;
8286
8287 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008288 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008289 return true;
8290 }
8291
8292 return false;
8293}
8294
John McCall3969e302009-12-08 07:46:18 +00008295
John McCallb96ec562009-12-04 22:46:56 +00008296/// Checks that the given nested-name qualifier used in a using decl
8297/// in the current context is appropriately related to the current
8298/// scope. If an error is found, diagnoses it and returns true.
8299bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8300 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008301 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008302 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008303 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008304
John McCall3969e302009-12-08 07:46:18 +00008305 if (!CurContext->isRecord()) {
8306 // C++03 [namespace.udecl]p3:
8307 // C++0x [namespace.udecl]p8:
8308 // A using-declaration for a class member shall be a member-declaration.
8309
8310 // If we weren't able to compute a valid scope, it must be a
8311 // dependent class scope.
8312 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008313 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008314 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008315 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008316
John McCall3969e302009-12-08 07:46:18 +00008317 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8318 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008319
8320 // If we have a complete, non-dependent source type, try to suggest a
8321 // way to get the same effect.
8322 if (!RD)
8323 return true;
8324
8325 // Find what this using-declaration was referring to.
8326 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8327 R.setHideTags(false);
8328 R.suppressDiagnostics();
8329 LookupQualifiedName(R, RD);
8330
8331 if (R.getAsSingle<TypeDecl>()) {
8332 if (getLangOpts().CPlusPlus11) {
8333 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8334 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8335 << 0 // alias declaration
8336 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8337 NameInfo.getName().getAsString() +
8338 " = ");
8339 } else {
8340 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8341 SourceLocation InsertLoc =
8342 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8343 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8344 << 1 // typedef declaration
8345 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8346 << FixItHint::CreateInsertion(
8347 InsertLoc, " " + NameInfo.getName().getAsString());
8348 }
8349 } else if (R.getAsSingle<VarDecl>()) {
8350 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8351 // repeating the type of the static data member here.
8352 FixItHint FixIt;
8353 if (getLangOpts().CPlusPlus11) {
8354 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8355 FixIt = FixItHint::CreateReplacement(
8356 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8357 }
8358
8359 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8360 << 2 // reference declaration
8361 << FixIt;
8362 }
John McCall3969e302009-12-08 07:46:18 +00008363 return true;
8364 }
8365
8366 // Otherwise, everything is known to be fine.
8367 return false;
8368 }
8369
8370 // The current scope is a record.
8371
8372 // If the named context is dependent, we can't decide much.
8373 if (!NamedContext) {
8374 // FIXME: in C++0x, we can diagnose if we can prove that the
8375 // nested-name-specifier does not refer to a base class, which is
8376 // still possible in some cases.
8377
8378 // Otherwise we have to conservatively report that things might be
8379 // okay.
8380 return false;
8381 }
8382
8383 if (!NamedContext->isRecord()) {
8384 // Ideally this would point at the last name in the specifier,
8385 // but we don't have that level of source info.
8386 Diag(SS.getRange().getBegin(),
8387 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008388 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008389 return true;
8390 }
8391
Douglas Gregor7c842292010-12-21 07:41:49 +00008392 if (!NamedContext->isDependentContext() &&
8393 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8394 return true;
8395
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008396 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008397 // C++0x [namespace.udecl]p3:
8398 // In a using-declaration used as a member-declaration, the
8399 // nested-name-specifier shall name a base class of the class
8400 // being defined.
8401
8402 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8403 cast<CXXRecordDecl>(NamedContext))) {
8404 if (CurContext == NamedContext) {
8405 Diag(NameLoc,
8406 diag::err_using_decl_nested_name_specifier_is_current_class)
8407 << SS.getRange();
8408 return true;
8409 }
8410
8411 Diag(SS.getRange().getBegin(),
8412 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008413 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008414 << cast<CXXRecordDecl>(CurContext)
8415 << SS.getRange();
8416 return true;
8417 }
8418
8419 return false;
8420 }
8421
8422 // C++03 [namespace.udecl]p4:
8423 // A using-declaration used as a member-declaration shall refer
8424 // to a member of a base class of the class being defined [etc.].
8425
8426 // Salient point: SS doesn't have to name a base class as long as
8427 // lookup only finds members from base classes. Therefore we can
8428 // diagnose here only if we can prove that that can't happen,
8429 // i.e. if the class hierarchies provably don't intersect.
8430
8431 // TODO: it would be nice if "definitely valid" results were cached
8432 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8433 // need to be repeated.
8434
8435 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008436 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008437
8438 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8439 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8440 Data->Bases.insert(Base);
8441 return true;
8442 }
8443
8444 bool hasDependentBases(const CXXRecordDecl *Class) {
8445 return !Class->forallBases(collect, this);
8446 }
8447
8448 /// Returns true if the base is dependent or is one of the
8449 /// accumulated base classes.
8450 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8451 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8452 return !Data->Bases.count(Base);
8453 }
8454
8455 bool mightShareBases(const CXXRecordDecl *Class) {
8456 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8457 }
8458 };
8459
8460 UserData Data;
8461
8462 // Returns false if we find a dependent base.
8463 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8464 return false;
8465
8466 // Returns false if the class has a dependent base or if it or one
8467 // of its bases is present in the base set of the current context.
8468 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8469 return false;
8470
8471 Diag(SS.getRange().getBegin(),
8472 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008473 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008474 << cast<CXXRecordDecl>(CurContext)
8475 << SS.getRange();
8476
8477 return true;
John McCallb96ec562009-12-04 22:46:56 +00008478}
8479
Richard Smithdda56e42011-04-15 14:24:37 +00008480Decl *Sema::ActOnAliasDeclaration(Scope *S,
8481 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008482 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008483 SourceLocation UsingLoc,
8484 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008485 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00008486 TypeResult Type,
8487 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008488 // Skip up to the relevant declaration scope.
8489 while (S->getFlags() & Scope::TemplateParamScope)
8490 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008491 assert((S->getFlags() & Scope::DeclScope) &&
8492 "got alias-declaration outside of declaration scope");
8493
8494 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008495 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008496
8497 bool Invalid = false;
8498 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008499 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008500 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008501
8502 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008503 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008504
8505 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008506 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008507 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008508 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8509 TInfo->getTypeLoc().getBeginLoc());
8510 }
Richard Smithdda56e42011-04-15 14:24:37 +00008511
8512 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8513 LookupName(Previous, S);
8514
8515 // Warn about shadowing the name of a template parameter.
8516 if (Previous.isSingleResult() &&
8517 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008518 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008519 Previous.clear();
8520 }
8521
8522 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8523 "name in alias declaration must be an identifier");
8524 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8525 Name.StartLocation,
8526 Name.Identifier, TInfo);
8527
8528 NewTD->setAccess(AS);
8529
8530 if (Invalid)
8531 NewTD->setInvalidDecl();
8532
Richard Smith54ecd982013-02-20 19:22:51 +00008533 ProcessDeclAttributeList(S, NewTD, AttrList);
8534
Richard Smith3f1b5d02011-05-05 21:57:07 +00008535 CheckTypedefForVariablyModifiedType(S, NewTD);
8536 Invalid |= NewTD->isInvalidDecl();
8537
Richard Smithdda56e42011-04-15 14:24:37 +00008538 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008539
8540 NamedDecl *NewND;
8541 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008542 TypeAliasTemplateDecl *OldDecl = nullptr;
8543 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008544
8545 if (TemplateParamLists.size() != 1) {
8546 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008547 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8548 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008549 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008550 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008551
8552 // Only consider previous declarations in the same scope.
8553 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8554 /*ExplicitInstantiationOrSpecialization*/false);
8555 if (!Previous.empty()) {
8556 Redeclaration = true;
8557
8558 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8559 if (!OldDecl && !Invalid) {
8560 Diag(UsingLoc, diag::err_redefinition_different_kind)
8561 << Name.Identifier;
8562
8563 NamedDecl *OldD = Previous.getRepresentativeDecl();
8564 if (OldD->getLocation().isValid())
8565 Diag(OldD->getLocation(), diag::note_previous_definition);
8566
8567 Invalid = true;
8568 }
8569
8570 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8571 if (TemplateParameterListsAreEqual(TemplateParams,
8572 OldDecl->getTemplateParameters(),
8573 /*Complain=*/true,
8574 TPL_TemplateMatch))
8575 OldTemplateParams = OldDecl->getTemplateParameters();
8576 else
8577 Invalid = true;
8578
8579 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8580 if (!Invalid &&
8581 !Context.hasSameType(OldTD->getUnderlyingType(),
8582 NewTD->getUnderlyingType())) {
8583 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8584 // but we can't reasonably accept it.
8585 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8586 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8587 if (OldTD->getLocation().isValid())
8588 Diag(OldTD->getLocation(), diag::note_previous_definition);
8589 Invalid = true;
8590 }
8591 }
8592 }
8593
8594 // Merge any previous default template arguments into our parameters,
8595 // and check the parameter list.
8596 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8597 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008598 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008599
8600 TypeAliasTemplateDecl *NewDecl =
8601 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8602 Name.Identifier, TemplateParams,
8603 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008604 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008605
8606 NewDecl->setAccess(AS);
8607
8608 if (Invalid)
8609 NewDecl->setInvalidDecl();
8610 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008611 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008612
8613 NewND = NewDecl;
8614 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00008615 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8616 setTagNameForLinkagePurposes(TD, NewTD);
8617 handleTagNumbering(TD, S);
8618 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00008619 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8620 NewND = NewTD;
8621 }
Richard Smithdda56e42011-04-15 14:24:37 +00008622
8623 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008624 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008625
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008626 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008627 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008628}
8629
Richard Smithf4634362014-09-03 23:11:22 +00008630Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8631 SourceLocation AliasLoc,
8632 IdentifierInfo *Alias, CXXScopeSpec &SS,
8633 SourceLocation IdentLoc,
8634 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008635
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008636 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008637 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8638 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008639
John McCall27b18f82009-11-17 02:14:36 +00008640 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008641 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008642
John McCall9f3059a2009-10-09 21:13:30 +00008643 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008644 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008645 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008646 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008647 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008648 }
Richard Smithf4634362014-09-03 23:11:22 +00008649 assert(!R.isAmbiguous() && !R.empty());
8650
8651 // Check if we have a previous declaration with the same name.
8652 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8653 ForRedeclaration);
8654 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8655 PrevDecl = nullptr;
8656
Aaron Ballman43f40102014-11-14 22:34:56 +00008657 NamedDecl *ND = R.getFoundDecl();
8658
Richard Smithf4634362014-09-03 23:11:22 +00008659 if (PrevDecl) {
8660 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8661 // We already have an alias with the same name that points to the same
8662 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008663 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008664 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8665 << Alias;
8666 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8667 << AD->getNamespace();
8668 return nullptr;
8669 }
8670 } else {
8671 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8672 ? diag::err_redefinition
8673 : diag::err_redefinition_different_kind;
8674 Diag(AliasLoc, DiagID) << Alias;
8675 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8676 return nullptr;
8677 }
8678 }
Mike Stump11289f42009-09-09 15:08:12 +00008679
Nico Riecke50e59a2014-11-24 17:29:52 +00008680 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008681 DiagnoseUseOfDecl(ND, IdentLoc);
8682
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008683 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008684 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008685 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008686 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008687 if (PrevDecl)
8688 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008689
John McCalld8d0d432010-02-16 06:53:13 +00008690 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008691 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008692}
8693
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008694Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008695Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8696 CXXMethodDecl *MD) {
8697 CXXRecordDecl *ClassDecl = MD->getParent();
8698
Douglas Gregor6d880b12010-07-01 22:31:05 +00008699 // C++ [except.spec]p14:
8700 // An implicitly declared special member function (Clause 12) shall have an
8701 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008702 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008703 if (ClassDecl->isInvalidDecl())
8704 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008705
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008706 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008707 for (const auto &B : ClassDecl->bases()) {
8708 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008709 continue;
8710
Aaron Ballman574705e2014-03-13 15:41:46 +00008711 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008712 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008713 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8714 // If this is a deleted function, add it anyway. This might be conformant
8715 // with the standard. This might not. I'm not sure. It might not matter.
8716 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008717 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008718 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008719 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008720
8721 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008722 for (const auto &B : ClassDecl->vbases()) {
8723 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008724 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008725 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8726 // If this is a deleted function, add it anyway. This might be conformant
8727 // with the standard. This might not. I'm not sure. It might not matter.
8728 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008729 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008730 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008731 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008732
8733 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008734 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008735 if (F->hasInClassInitializer()) {
8736 if (Expr *E = F->getInClassInitializer())
8737 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008738 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008739 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008740 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8741 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8742 // If this is a deleted function, add it anyway. This might be conformant
8743 // with the standard. This might not. I'm not sure. It might not matter.
8744 // In particular, the problem is that this function never gets called. It
8745 // might just be ill-formed because this function attempts to refer to
8746 // a deleted function here.
8747 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008748 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008749 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008750 }
John McCalldb40c7f2010-12-14 08:05:40 +00008751
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008752 return ExceptSpec;
8753}
8754
Richard Smithc2bc61b2013-03-18 21:12:30 +00008755Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008756Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8757 CXXRecordDecl *ClassDecl = CD->getParent();
8758
8759 // C++ [except.spec]p14:
8760 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008761 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008762 if (ClassDecl->isInvalidDecl())
8763 return ExceptSpec;
8764
8765 // Inherited constructor.
8766 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8767 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8768 // FIXME: Copying or moving the parameters could add extra exceptions to the
8769 // set, as could the default arguments for the inherited constructor. This
8770 // will be addressed when we implement the resolution of core issue 1351.
8771 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8772
8773 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008774 for (const auto &B : ClassDecl->bases()) {
8775 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008776 continue;
8777
Aaron Ballman574705e2014-03-13 15:41:46 +00008778 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008779 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8780 if (BaseClassDecl == InheritedDecl)
8781 continue;
8782 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8783 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008784 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008785 }
8786 }
8787
8788 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008789 for (const auto &B : ClassDecl->vbases()) {
8790 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008791 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8792 if (BaseClassDecl == InheritedDecl)
8793 continue;
8794 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8795 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008796 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008797 }
8798 }
8799
8800 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008801 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008802 if (F->hasInClassInitializer()) {
8803 if (Expr *E = F->getInClassInitializer())
8804 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008805 } else if (const RecordType *RecordTy
8806 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8807 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8808 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8809 if (Constructor)
8810 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8811 }
8812 }
8813
Richard Smithc2bc61b2013-03-18 21:12:30 +00008814 return ExceptSpec;
8815}
8816
Richard Smith8bf22e52012-11-29 01:34:07 +00008817namespace {
8818/// RAII object to register a special member as being currently declared.
8819struct DeclaringSpecialMember {
8820 Sema &S;
8821 Sema::SpecialMemberDecl D;
8822 bool WasAlreadyBeingDeclared;
8823
8824 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8825 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008826 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008827 if (WasAlreadyBeingDeclared)
8828 // This almost never happens, but if it does, ensure that our cache
8829 // doesn't contain a stale result.
8830 S.SpecialMemberCache.clear();
8831
8832 // FIXME: Register a note to be produced if we encounter an error while
8833 // declaring the special member.
8834 }
8835 ~DeclaringSpecialMember() {
8836 if (!WasAlreadyBeingDeclared)
8837 S.SpecialMembersBeingDeclared.erase(D);
8838 }
8839
8840 /// \brief Are we already trying to declare this special member?
8841 bool isAlreadyBeingDeclared() const {
8842 return WasAlreadyBeingDeclared;
8843 }
8844};
8845}
8846
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008847CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8848 CXXRecordDecl *ClassDecl) {
8849 // C++ [class.ctor]p5:
8850 // A default constructor for a class X is a constructor of class X
8851 // that can be called without an argument. If there is no
8852 // user-declared constructor for class X, a default constructor is
8853 // implicitly declared. An implicitly-declared default constructor
8854 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008855 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008856 "Should not build implicit default constructor!");
8857
Richard Smith8bf22e52012-11-29 01:34:07 +00008858 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8859 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008860 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008861
Richard Smithb5800092012-06-10 05:43:50 +00008862 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8863 CXXDefaultConstructor,
8864 false);
8865
Douglas Gregor6d880b12010-07-01 22:31:05 +00008866 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008867 CanQualType ClassType
8868 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008869 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008870 DeclarationName Name
8871 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008872 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008873 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008874 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8875 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8876 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008877 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008878 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008879
8880 if (getLangOpts().CUDA) {
8881 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8882 DefaultCon,
8883 /* ConstRHS */ false,
8884 /* Diagnose */ false);
8885 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008886
8887 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008888 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008889 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008890
Richard Smith6b02d462012-12-08 08:32:28 +00008891 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8892 // constructors is easy to compute.
8893 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8894
8895 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008896 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008897
Douglas Gregor9672f922010-07-03 00:47:00 +00008898 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008899 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008900
Douglas Gregor0be31a22010-07-02 17:43:08 +00008901 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008902 PushOnScopeChains(DefaultCon, S, false);
8903 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008904
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008905 return DefaultCon;
8906}
8907
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008908void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8909 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008910 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008911 !Constructor->doesThisDeclarationHaveABody() &&
8912 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008913 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008914
Anders Carlsson423f5d82010-04-23 16:04:08 +00008915 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008916 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008917
Eli Friedmaneaf34142012-10-18 20:14:08 +00008918 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008919 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008920 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008921 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008922 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008923 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008924 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008925 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008926 }
Douglas Gregor73193272010-09-20 16:48:21 +00008927
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008928 // The exception specification is needed because we are defining the
8929 // function.
8930 ResolveExceptionSpec(CurrentLocation,
8931 Constructor->getType()->castAs<FunctionProtoType>());
8932
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008933 SourceLocation Loc = Constructor->getLocEnd().isValid()
8934 ? Constructor->getLocEnd()
8935 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008936 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008937
Eli Friedman276dd182013-09-05 00:02:25 +00008938 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008939 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008940
8941 if (ASTMutationListener *L = getASTMutationListener()) {
8942 L->CompletedImplicitDefinition(Constructor);
8943 }
Richard Trieuef64e942013-10-25 00:56:00 +00008944
8945 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008946}
8947
Richard Smith938f40b2011-06-11 17:19:42 +00008948void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008949 // Perform any delayed checks on exception specifications.
8950 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008951}
8952
Richard Smith185be182013-04-10 05:48:59 +00008953namespace {
8954/// Information on inheriting constructors to declare.
8955class InheritingConstructorInfo {
8956public:
8957 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8958 : SemaRef(SemaRef), Derived(Derived) {
8959 // Mark the constructors that we already have in the derived class.
8960 //
8961 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8962 // unless there is a user-declared constructor with the same signature in
8963 // the class where the using-declaration appears.
8964 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8965 }
8966
8967 void inheritAll(CXXRecordDecl *RD) {
8968 visitAll(RD, &InheritingConstructorInfo::inherit);
8969 }
8970
8971private:
8972 /// Information about an inheriting constructor.
8973 struct InheritingConstructor {
8974 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008975 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008976
8977 /// If \c true, a constructor with this signature is already declared
8978 /// in the derived class.
8979 bool DeclaredInDerived;
8980
8981 /// The constructor which is inherited.
8982 const CXXConstructorDecl *BaseCtor;
8983
8984 /// The derived constructor we declared.
8985 CXXConstructorDecl *DerivedCtor;
8986 };
8987
8988 /// Inheriting constructors with a given canonical type. There can be at
8989 /// most one such non-template constructor, and any number of templated
8990 /// constructors.
8991 struct InheritingConstructorsForType {
8992 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008993 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8994 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008995
8996 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8997 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8998 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8999 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9000 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9001 false, S.TPL_TemplateMatch))
9002 return Templates[I].second;
9003 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9004 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009005 }
Richard Smith185be182013-04-10 05:48:59 +00009006
9007 return NonTemplate;
9008 }
9009 };
9010
9011 /// Get or create the inheriting constructor record for a constructor.
9012 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9013 QualType CtorType) {
9014 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9015 .getEntry(SemaRef, Ctor);
9016 }
9017
9018 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9019
9020 /// Process all constructors for a class.
9021 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009022 for (const auto *Ctor : RD->ctors())
9023 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009024 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9025 I(RD->decls_begin()), E(RD->decls_end());
9026 I != E; ++I) {
9027 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9028 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9029 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009030 }
9031 }
Richard Smith185be182013-04-10 05:48:59 +00009032
9033 /// Note that a constructor (or constructor template) was declared in Derived.
9034 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9035 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9036 }
9037
9038 /// Inherit a single constructor.
9039 void inherit(const CXXConstructorDecl *Ctor) {
9040 const FunctionProtoType *CtorType =
9041 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009042 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009043 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9044
9045 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9046
9047 // Core issue (no number yet): the ellipsis is always discarded.
9048 if (EPI.Variadic) {
9049 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9050 SemaRef.Diag(Ctor->getLocation(),
9051 diag::note_using_decl_constructor_ellipsis);
9052 EPI.Variadic = false;
9053 }
9054
9055 // Declare a constructor for each number of parameters.
9056 //
9057 // C++11 [class.inhctor]p1:
9058 // The candidate set of inherited constructors from the class X named in
9059 // the using-declaration consists of [... modulo defects ...] for each
9060 // constructor or constructor template of X, the set of constructors or
9061 // constructor templates that results from omitting any ellipsis parameter
9062 // specification and successively omitting parameters with a default
9063 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009064 unsigned MinParams = minParamsToInherit(Ctor);
9065 unsigned Params = Ctor->getNumParams();
9066 if (Params >= MinParams) {
9067 do
9068 declareCtor(UsingLoc, Ctor,
9069 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009070 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009071 while (Params > MinParams &&
9072 Ctor->getParamDecl(--Params)->hasDefaultArg());
9073 }
Richard Smith185be182013-04-10 05:48:59 +00009074 }
9075
9076 /// Find the using-declaration which specified that we should inherit the
9077 /// constructors of \p Base.
9078 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9079 // No fancy lookup required; just look for the base constructor name
9080 // directly within the derived class.
9081 ASTContext &Context = SemaRef.Context;
9082 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9083 Context.getCanonicalType(Context.getRecordType(Base)));
Richard Smithcf4bdde2015-02-21 02:45:19 +00009084 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith185be182013-04-10 05:48:59 +00009085 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9086 }
9087
9088 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9089 // C++11 [class.inhctor]p3:
9090 // [F]or each constructor template in the candidate set of inherited
9091 // constructors, a constructor template is implicitly declared
9092 if (Ctor->getDescribedFunctionTemplate())
9093 return 0;
9094
9095 // For each non-template constructor in the candidate set of inherited
9096 // constructors other than a constructor having no parameters or a
9097 // copy/move constructor having a single parameter, a constructor is
9098 // implicitly declared [...]
9099 if (Ctor->getNumParams() == 0)
9100 return 1;
9101 if (Ctor->isCopyOrMoveConstructor())
9102 return 2;
9103
9104 // Per discussion on core reflector, never inherit a constructor which
9105 // would become a default, copy, or move constructor of Derived either.
9106 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9107 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9108 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9109 }
9110
9111 /// Declare a single inheriting constructor, inheriting the specified
9112 /// constructor, with the given type.
9113 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9114 QualType DerivedType) {
9115 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9116
9117 // C++11 [class.inhctor]p3:
9118 // ... a constructor is implicitly declared with the same constructor
9119 // characteristics unless there is a user-declared constructor with
9120 // the same signature in the class where the using-declaration appears
9121 if (Entry.DeclaredInDerived)
9122 return;
9123
9124 // C++11 [class.inhctor]p7:
9125 // If two using-declarations declare inheriting constructors with the
9126 // same signature, the program is ill-formed
9127 if (Entry.DerivedCtor) {
9128 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9129 // Only diagnose this once per constructor.
9130 if (Entry.DerivedCtor->isInvalidDecl())
9131 return;
9132 Entry.DerivedCtor->setInvalidDecl();
9133
9134 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9135 SemaRef.Diag(BaseCtor->getLocation(),
9136 diag::note_using_decl_constructor_conflict_current_ctor);
9137 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9138 diag::note_using_decl_constructor_conflict_previous_ctor);
9139 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9140 diag::note_using_decl_constructor_conflict_previous_using);
9141 } else {
9142 // Core issue (no number): if the same inheriting constructor is
9143 // produced by multiple base class constructors from the same base
9144 // class, the inheriting constructor is defined as deleted.
9145 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9146 }
9147
9148 return;
9149 }
9150
9151 ASTContext &Context = SemaRef.Context;
9152 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9153 Context.getCanonicalType(Context.getRecordType(Derived)));
9154 DeclarationNameInfo NameInfo(Name, UsingLoc);
9155
Craig Topperc3ec1492014-05-26 06:22:03 +00009156 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009157 if (const FunctionTemplateDecl *FTD =
9158 BaseCtor->getDescribedFunctionTemplate()) {
9159 TemplateParams = FTD->getTemplateParameters();
9160 // We're reusing template parameters from a different DeclContext. This
9161 // is questionable at best, but works out because the template depth in
9162 // both places is guaranteed to be 0.
9163 // FIXME: Rebuild the template parameters in the new context, and
9164 // transform the function type to refer to them.
9165 }
9166
9167 // Build type source info pointing at the using-declaration. This is
9168 // required by template instantiation.
9169 TypeSourceInfo *TInfo =
9170 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9171 FunctionProtoTypeLoc ProtoLoc =
9172 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9173
9174 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9175 Context, Derived, UsingLoc, NameInfo, DerivedType,
9176 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9177 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9178
9179 // Build an unevaluated exception specification for this constructor.
9180 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9181 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009182 EPI.ExceptionSpec.Type = EST_Unevaluated;
9183 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009184 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009185 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009186
9187 // Build the parameter declarations.
9188 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009189 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009190 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009191 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009192 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009193 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9194 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009195 PD->setScopeInfo(0, I);
9196 PD->setImplicit();
9197 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009198 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009199 }
9200
9201 // Set up the new constructor.
9202 DerivedCtor->setAccess(BaseCtor->getAccess());
9203 DerivedCtor->setParams(ParamDecls);
9204 DerivedCtor->setInheritedConstructor(BaseCtor);
9205 if (BaseCtor->isDeleted())
9206 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9207
9208 // If this is a constructor template, build the template declaration.
9209 if (TemplateParams) {
9210 FunctionTemplateDecl *DerivedTemplate =
9211 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9212 TemplateParams, DerivedCtor);
9213 DerivedTemplate->setAccess(BaseCtor->getAccess());
9214 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9215 Derived->addDecl(DerivedTemplate);
9216 } else {
9217 Derived->addDecl(DerivedCtor);
9218 }
9219
9220 Entry.BaseCtor = BaseCtor;
9221 Entry.DerivedCtor = DerivedCtor;
9222 }
9223
9224 Sema &SemaRef;
9225 CXXRecordDecl *Derived;
9226 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9227 MapType Map;
9228};
9229}
9230
9231void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9232 // Defer declaring the inheriting constructors until the class is
9233 // instantiated.
9234 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009235 return;
9236
Richard Smith185be182013-04-10 05:48:59 +00009237 // Find base classes from which we might inherit constructors.
9238 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009239 for (const auto &BaseIt : ClassDecl->bases())
9240 if (BaseIt.getInheritConstructors())
9241 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009242
Richard Smith185be182013-04-10 05:48:59 +00009243 // Go no further if we're not inheriting any constructors.
9244 if (InheritedBases.empty())
9245 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009246
Richard Smith185be182013-04-10 05:48:59 +00009247 // Declare the inherited constructors.
9248 InheritingConstructorInfo ICI(*this, ClassDecl);
9249 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9250 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009251}
9252
Richard Smithc2bc61b2013-03-18 21:12:30 +00009253void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9254 CXXConstructorDecl *Constructor) {
9255 CXXRecordDecl *ClassDecl = Constructor->getParent();
9256 assert(Constructor->getInheritedConstructor() &&
9257 !Constructor->doesThisDeclarationHaveABody() &&
9258 !Constructor->isDeleted());
9259
9260 SynthesizedFunctionScope Scope(*this, Constructor);
9261 DiagnosticErrorTrap Trap(Diags);
9262 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9263 Trap.hasErrorOccurred()) {
9264 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9265 << Context.getTagDeclType(ClassDecl);
9266 Constructor->setInvalidDecl();
9267 return;
9268 }
9269
9270 SourceLocation Loc = Constructor->getLocation();
9271 Constructor->setBody(new (Context) CompoundStmt(Loc));
9272
Eli Friedman276dd182013-09-05 00:02:25 +00009273 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009274 MarkVTableUsed(CurrentLocation, ClassDecl);
9275
9276 if (ASTMutationListener *L = getASTMutationListener()) {
9277 L->CompletedImplicitDefinition(Constructor);
9278 }
9279}
9280
9281
Alexis Huntf91729462011-05-12 22:46:25 +00009282Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009283Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9284 CXXRecordDecl *ClassDecl = MD->getParent();
9285
Douglas Gregorf1203042010-07-01 19:09:28 +00009286 // C++ [except.spec]p14:
9287 // An implicitly declared special member function (Clause 12) shall have
9288 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009289 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009290 if (ClassDecl->isInvalidDecl())
9291 return ExceptSpec;
9292
Douglas Gregorf1203042010-07-01 19:09:28 +00009293 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009294 for (const auto &B : ClassDecl->bases()) {
9295 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009296 continue;
9297
Aaron Ballman574705e2014-03-13 15:41:46 +00009298 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9299 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009300 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009301 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009302
Douglas Gregorf1203042010-07-01 19:09:28 +00009303 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009304 for (const auto &B : ClassDecl->vbases()) {
9305 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9306 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009307 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009308 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009309
Douglas Gregorf1203042010-07-01 19:09:28 +00009310 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009311 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009312 if (const RecordType *RecordTy
9313 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009314 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009315 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009316 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009317
Alexis Huntf91729462011-05-12 22:46:25 +00009318 return ExceptSpec;
9319}
9320
9321CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9322 // C++ [class.dtor]p2:
9323 // If a class has no user-declared destructor, a destructor is
9324 // declared implicitly. An implicitly-declared destructor is an
9325 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009326 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009327
Richard Smith8bf22e52012-11-29 01:34:07 +00009328 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9329 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009330 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009331
Douglas Gregor7454c562010-07-02 20:37:36 +00009332 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009333 CanQualType ClassType
9334 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009335 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009336 DeclarationName Name
9337 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009338 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009339 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009340 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009341 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009342 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009343 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009344 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009345
9346 if (getLangOpts().CUDA) {
9347 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9348 Destructor,
9349 /* ConstRHS */ false,
9350 /* Diagnose */ false);
9351 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009352
9353 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009354 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009355 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009356
Richard Smith6b02d462012-12-08 08:32:28 +00009357 AddOverriddenMethods(ClassDecl, Destructor);
9358
9359 // We don't need to use SpecialMemberIsTrivial here; triviality for
9360 // destructors is easy to compute.
9361 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9362
9363 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009364 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009365
Douglas Gregor7454c562010-07-02 20:37:36 +00009366 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009367 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009368
Douglas Gregor7454c562010-07-02 20:37:36 +00009369 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009370 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009371 PushOnScopeChains(Destructor, S, false);
9372 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009373
Douglas Gregorf1203042010-07-01 19:09:28 +00009374 return Destructor;
9375}
9376
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009377void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009378 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009379 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009380 !Destructor->doesThisDeclarationHaveABody() &&
9381 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009382 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009383 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009384 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009385
Douglas Gregor54818f02010-05-12 16:39:35 +00009386 if (Destructor->isInvalidDecl())
9387 return;
9388
Eli Friedmaneaf34142012-10-18 20:14:08 +00009389 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009390
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009391 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009392 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9393 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009394
Douglas Gregor54818f02010-05-12 16:39:35 +00009395 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009396 Diag(CurrentLocation, diag::note_member_synthesized_at)
9397 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9398
9399 Destructor->setInvalidDecl();
9400 return;
9401 }
9402
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009403 // The exception specification is needed because we are defining the
9404 // function.
9405 ResolveExceptionSpec(CurrentLocation,
9406 Destructor->getType()->castAs<FunctionProtoType>());
9407
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009408 SourceLocation Loc = Destructor->getLocEnd().isValid()
9409 ? Destructor->getLocEnd()
9410 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009411 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009412 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009413 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009414
9415 if (ASTMutationListener *L = getASTMutationListener()) {
9416 L->CompletedImplicitDefinition(Destructor);
9417 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009418}
9419
Richard Smith84973e52012-04-21 18:42:51 +00009420/// \brief Perform any semantic analysis which needs to be delayed until all
9421/// pending class member declarations have been parsed.
9422void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009423 // If the context is an invalid C++ class, just suppress these checks.
9424 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9425 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009426 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009427 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009428 return;
9429 }
9430 }
Richard Smith84973e52012-04-21 18:42:51 +00009431}
9432
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009433static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9434 // Don't do anything for template patterns.
9435 if (Class->getDescribedClassTemplate())
9436 return;
9437
9438 for (Decl *Member : Class->decls()) {
9439 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9440 if (!CD) {
9441 // Recurse on nested classes.
9442 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9443 getDefaultArgExprsForConstructors(S, NestedRD);
9444 continue;
9445 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9446 continue;
9447 }
9448
9449 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9450 // Skip any default arguments that we've already instantiated.
9451 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9452 continue;
9453
9454 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9455 CD->getParamDecl(I)).get();
9456 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9457 }
9458 }
9459}
9460
Reid Kleckner93f661a2015-03-17 21:51:43 +00009461void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009462 auto *RD = dyn_cast<CXXRecordDecl>(D);
9463
9464 // Default constructors that are annotated with __declspec(dllexport) which
9465 // have default arguments or don't use the standard calling convention are
9466 // wrapped with a thunk called the default constructor closure.
9467 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9468 getDefaultArgExprsForConstructors(*this, RD);
9469}
9470
Richard Smithd3b5c9082012-07-27 04:22:15 +00009471void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9472 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009473 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009474 "adjusting dtor exception specs was introduced in c++11");
9475
Sebastian Redl623ea822011-05-19 05:13:44 +00009476 // C++11 [class.dtor]p3:
9477 // A declaration of a destructor that does not have an exception-
9478 // specification is implicitly considered to have the same exception-
9479 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009480 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009481 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009482 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009483 return;
9484
Chandler Carruth9a797572011-09-20 04:55:26 +00009485 // Replace the destructor's type, building off the existing one. Fortunately,
9486 // the only thing of interest in the destructor type is its extended info.
9487 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009488 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009489 EPI.ExceptionSpec.Type = EST_Unevaluated;
9490 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009491 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009492
Sebastian Redl623ea822011-05-19 05:13:44 +00009493 // FIXME: If the destructor has a body that could throw, and the newly created
9494 // spec doesn't allow exceptions, we should emit a warning, because this
9495 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009496 // However, we don't have a body or an exception specification yet, so it
9497 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009498}
9499
Pavel Labath58934982013-08-30 08:52:28 +00009500namespace {
9501/// \brief An abstract base class for all helper classes used in building the
9502// copy/move operators. These classes serve as factory functions and help us
9503// avoid using the same Expr* in the AST twice.
9504class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +00009505 ExprBuilder(const ExprBuilder&) = delete;
9506 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +00009507
9508protected:
9509 static Expr *assertNotNull(Expr *E) {
9510 assert(E && "Expression construction must not fail.");
9511 return E;
9512 }
9513
9514public:
9515 ExprBuilder() {}
9516 virtual ~ExprBuilder() {}
9517
9518 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9519};
9520
9521class RefBuilder: public ExprBuilder {
9522 VarDecl *Var;
9523 QualType VarType;
9524
9525public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009526 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009527 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009528 }
9529
9530 RefBuilder(VarDecl *Var, QualType VarType)
9531 : Var(Var), VarType(VarType) {}
9532};
9533
9534class ThisBuilder: public ExprBuilder {
9535public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009536 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009537 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009538 }
9539};
9540
9541class CastBuilder: public ExprBuilder {
9542 const ExprBuilder &Builder;
9543 QualType Type;
9544 ExprValueKind Kind;
9545 const CXXCastPath &Path;
9546
9547public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009548 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009549 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9550 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009551 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009552 }
9553
9554 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9555 const CXXCastPath &Path)
9556 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9557};
9558
9559class DerefBuilder: public ExprBuilder {
9560 const ExprBuilder &Builder;
9561
9562public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009563 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009564 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009565 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009566 }
9567
9568 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9569};
9570
9571class MemberBuilder: public ExprBuilder {
9572 const ExprBuilder &Builder;
9573 QualType Type;
9574 CXXScopeSpec SS;
9575 bool IsArrow;
9576 LookupResult &MemberLookup;
9577
9578public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009579 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009580 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009581 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009582 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009583 }
9584
9585 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9586 LookupResult &MemberLookup)
9587 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9588 MemberLookup(MemberLookup) {}
9589};
9590
9591class MoveCastBuilder: public ExprBuilder {
9592 const ExprBuilder &Builder;
9593
9594public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009595 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009596 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9597 }
9598
9599 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9600};
9601
9602class LvalueConvBuilder: public ExprBuilder {
9603 const ExprBuilder &Builder;
9604
9605public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009606 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009607 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009608 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009609 }
9610
9611 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9612};
9613
9614class SubscriptBuilder: public ExprBuilder {
9615 const ExprBuilder &Base;
9616 const ExprBuilder &Index;
9617
9618public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009619 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009620 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009621 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009622 }
9623
9624 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9625 : Base(Base), Index(Index) {}
9626};
9627
9628} // end anonymous namespace
9629
Richard Smith41ae3282012-11-14 00:50:40 +00009630/// When generating a defaulted copy or move assignment operator, if a field
9631/// should be copied with __builtin_memcpy rather than via explicit assignments,
9632/// do so. This optimization only applies for arrays of scalars, and for arrays
9633/// of class type where the selected copy/move-assignment operator is trivial.
9634static StmtResult
9635buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009636 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009637 // Compute the size of the memory buffer to be copied.
9638 QualType SizeType = S.Context.getSizeType();
9639 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9640 S.Context.getTypeSizeInChars(T).getQuantity());
9641
9642 // Take the address of the field references for "from" and "to". We
9643 // directly construct UnaryOperators here because semantic analysis
9644 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009645 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009646 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9647 S.Context.getPointerType(From->getType()),
9648 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009649 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009650 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9651 S.Context.getPointerType(To->getType()),
9652 VK_RValue, OK_Ordinary, Loc);
9653
9654 const Type *E = T->getBaseElementTypeUnsafe();
9655 bool NeedsCollectableMemCpy =
9656 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9657
9658 // Create a reference to the __builtin_objc_memmove_collectable function
9659 StringRef MemCpyName = NeedsCollectableMemCpy ?
9660 "__builtin_objc_memmove_collectable" :
9661 "__builtin_memcpy";
9662 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9663 Sema::LookupOrdinaryName);
9664 S.LookupName(R, S.TUScope, true);
9665
9666 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9667 if (!MemCpy)
9668 // Something went horribly wrong earlier, and we will have complained
9669 // about it.
9670 return StmtError();
9671
9672 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009673 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009674 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9675
9676 Expr *CallArgs[] = {
9677 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9678 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009679 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009680 Loc, CallArgs, Loc);
9681
9682 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009683 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009684}
9685
Sebastian Redl22653ba2011-08-30 19:58:05 +00009686/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009687/// \c To.
9688///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009689/// This routine is used to copy/move the members of a class with an
9690/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009691/// copied are arrays, this routine builds for loops to copy them.
9692///
9693/// \param S The Sema object used for type-checking.
9694///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009695/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009696///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009697/// \param T The type of the expressions being copied/moved. Both expressions
9698/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009699///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009700/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009701///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009702/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009703///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009704/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009705/// Otherwise, it's a non-static member subobject.
9706///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009707/// \param Copying Whether we're copying or moving.
9708///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009709/// \param Depth Internal parameter recording the depth of the recursion.
9710///
Richard Smith41ae3282012-11-14 00:50:40 +00009711/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9712/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009713static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009714buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009715 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009716 bool CopyingBaseSubobject, bool Copying,
9717 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009718 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009719 // Each subobject is assigned in the manner appropriate to its type:
9720 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009721 // - if the subobject is of class type, as if by a call to operator= with
9722 // the subobject as the object expression and the corresponding
9723 // subobject of x as a single function argument (as if by explicit
9724 // qualification; that is, ignoring any possible virtual overriding
9725 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009726 //
9727 // C++03 [class.copy]p13:
9728 // - if the subobject is of class type, the copy assignment operator for
9729 // the class is used (as if by explicit qualification; that is,
9730 // ignoring any possible virtual overriding functions in more derived
9731 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009732 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9733 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009734
Douglas Gregorb139cd52010-05-01 20:49:11 +00009735 // Look for operator=.
9736 DeclarationName Name
9737 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9738 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9739 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009740
Richard Smith52c0b582012-11-13 00:54:12 +00009741 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9742 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009743 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009744 LookupResult::Filter F = OpLookup.makeFilter();
9745 while (F.hasNext()) {
9746 NamedDecl *D = F.next();
9747 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9748 if (Method->isCopyAssignmentOperator() ||
9749 (!Copying && Method->isMoveAssignmentOperator()))
9750 continue;
9751
9752 F.erase();
9753 }
9754 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009755 }
Richard Smith52c0b582012-11-13 00:54:12 +00009756
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009757 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009758 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009759 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009760 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009761 // ambiguities), we need to cast "this" to that subobject type; to
9762 // ensure that we don't go through the virtual call mechanism, we need
9763 // to qualify the operator= name with the base class (see below). However,
9764 // this means that if the base class has a protected copy assignment
9765 // operator, the protected member access check will fail. So, we
9766 // rewrite "protected" access to "public" access in this case, since we
9767 // know by construction that we're calling from a derived class.
9768 if (CopyingBaseSubobject) {
9769 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9770 L != LEnd; ++L) {
9771 if (L.getAccess() == AS_protected)
9772 L.setAccess(AS_public);
9773 }
9774 }
Richard Smith52c0b582012-11-13 00:54:12 +00009775
Douglas Gregorb139cd52010-05-01 20:49:11 +00009776 // Create the nested-name-specifier that will be used to qualify the
9777 // reference to operator=; this is required to suppress the virtual
9778 // call mechanism.
9779 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009780 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009781 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009782 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009783 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009784 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009785
Douglas Gregorb139cd52010-05-01 20:49:11 +00009786 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009787 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009788 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9789 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009790 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009791 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009792 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009793 /*SuppressQualifierCheck=*/true);
9794 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009795 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009796
Douglas Gregorb139cd52010-05-01 20:49:11 +00009797 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009798
Pavel Labath58934982013-08-30 08:52:28 +00009799 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009800 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009801 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009802 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009803 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009804 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009805
Richard Smith41ae3282012-11-14 00:50:40 +00009806 // If we built a call to a trivial 'operator=' while copying an array,
9807 // bail out. We'll replace the whole shebang with a memcpy.
9808 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9809 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009810 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009811
Richard Smith52c0b582012-11-13 00:54:12 +00009812 // Convert to an expression-statement, and clean up any produced
9813 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009814 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009815 }
John McCallab8c2732010-03-16 06:11:48 +00009816
Richard Smith52c0b582012-11-13 00:54:12 +00009817 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009818 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009819 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009820 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009821 ExprResult Assignment = S.CreateBuiltinBinOp(
9822 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009823 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009824 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009825 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009826 }
Richard Smith52c0b582012-11-13 00:54:12 +00009827
9828 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009829 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009830
Douglas Gregorb139cd52010-05-01 20:49:11 +00009831 // Construct a loop over the array bounds, e.g.,
9832 //
9833 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9834 //
9835 // that will copy each of the array elements.
9836 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009837
Douglas Gregorb139cd52010-05-01 20:49:11 +00009838 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009839 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009840 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009841 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009842 llvm::raw_svector_ostream OS(Str);
9843 OS << "__i" << Depth;
9844 IterationVarName = &S.Context.Idents.get(OS.str());
9845 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009846 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009847 IterationVarName, SizeType,
9848 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009849 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009850
Douglas Gregorb139cd52010-05-01 20:49:11 +00009851 // Initialize the iteration variable to zero.
9852 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009853 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009854
Pavel Labath58934982013-08-30 08:52:28 +00009855 // Creates a reference to the iteration variable.
9856 RefBuilder IterationVarRef(IterationVar, SizeType);
9857 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009858
Douglas Gregorb139cd52010-05-01 20:49:11 +00009859 // Create the DeclStmt that holds the iteration variable.
9860 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009861
Douglas Gregorb139cd52010-05-01 20:49:11 +00009862 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009863 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9864 MoveCastBuilder FromIndexMove(FromIndexCopy);
9865 const ExprBuilder *FromIndex;
9866 if (Copying)
9867 FromIndex = &FromIndexCopy;
9868 else
9869 FromIndex = &FromIndexMove;
9870
9871 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872
9873 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009874 StmtResult Copy =
9875 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009876 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009877 Copying, Depth + 1);
9878 // Bail out if copying fails or if we determined that we should use memcpy.
9879 if (Copy.isInvalid() || !Copy.get())
9880 return Copy;
9881
9882 // Create the comparison against the array bound.
9883 llvm::APInt Upper
9884 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9885 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009886 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009887 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9888 BO_NE, S.Context.BoolTy,
9889 VK_RValue, OK_Ordinary, Loc, false);
9890
9891 // Create the pre-increment of the iteration variable.
9892 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009893 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9894 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009895
Douglas Gregorb139cd52010-05-01 20:49:11 +00009896 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009897 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009898 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009899 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009900 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009901}
9902
Richard Smith41ae3282012-11-14 00:50:40 +00009903static StmtResult
9904buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009905 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009906 bool CopyingBaseSubobject, bool Copying) {
9907 // Maybe we should use a memcpy?
9908 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9909 T.isTriviallyCopyableType(S.Context))
9910 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9911
9912 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9913 CopyingBaseSubobject,
9914 Copying, 0));
9915
9916 // If we ended up picking a trivial assignment operator for an array of a
9917 // non-trivially-copyable class type, just emit a memcpy.
9918 if (!Result.isInvalid() && !Result.get())
9919 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9920
9921 return Result;
9922}
9923
Richard Smithd3b5c9082012-07-27 04:22:15 +00009924Sema::ImplicitExceptionSpecification
9925Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9926 CXXRecordDecl *ClassDecl = MD->getParent();
9927
9928 ImplicitExceptionSpecification ExceptSpec(*this);
9929 if (ClassDecl->isInvalidDecl())
9930 return ExceptSpec;
9931
9932 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009933 assert(T->getNumParams() == 1 && "not a copy assignment op");
9934 unsigned ArgQuals =
9935 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009936
Douglas Gregor68e11362010-07-01 17:48:08 +00009937 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009938 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009939 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009940
9941 // It is unspecified whether or not an implicit copy assignment operator
9942 // attempts to deduplicate calls to assignment operators of virtual bases are
9943 // made. As such, this exception specification is effectively unspecified.
9944 // Based on a similar decision made for constness in C++0x, we're erring on
9945 // the side of assuming such calls to be made regardless of whether they
9946 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009947 for (const auto &Base : ClassDecl->bases()) {
9948 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009949 continue;
9950
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009951 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009952 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009953 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9954 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009955 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009956 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009957
Aaron Ballman445a9392014-03-13 16:15:17 +00009958 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009959 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009960 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009961 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9962 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009963 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009964 }
9965
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009966 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009967 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009968 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9969 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009970 LookupCopyingAssignment(FieldClassDecl,
9971 ArgQuals | FieldType.getCVRQualifiers(),
9972 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009973 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009974 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009975 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009976
Richard Smithd3b5c9082012-07-27 04:22:15 +00009977 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009978}
9979
9980CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9981 // Note: The following rules are largely analoguous to the copy
9982 // constructor rules. Note that virtual bases are not taken into account
9983 // for determining the argument type of the operator. Note also that
9984 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009985 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009986
Richard Smith8bf22e52012-11-29 01:34:07 +00009987 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9988 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009989 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009990
Alexis Hunt119f3652011-05-14 05:23:20 +00009991 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9992 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009993 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9994 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009995 ArgType = ArgType.withConst();
9996 ArgType = Context.getLValueReferenceType(ArgType);
9997
Richard Smith99005e62013-05-07 03:19:20 +00009998 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9999 CXXCopyAssignment,
10000 Const);
10001
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010002 // An implicitly-declared copy assignment operator is an inline public
10003 // member of its class.
10004 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010005 SourceLocation ClassLoc = ClassDecl->getLocation();
10006 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010007 CXXMethodDecl *CopyAssignment =
10008 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010009 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10010 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010011 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010012 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010013 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010014
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010015 if (getLangOpts().CUDA) {
10016 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10017 CopyAssignment,
10018 /* ConstRHS */ Const,
10019 /* Diagnose */ false);
10020 }
10021
Richard Smithd3b5c9082012-07-27 04:22:15 +000010022 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010023 FunctionProtoType::ExtProtoInfo EPI =
10024 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010025 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010026
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010027 // Add the parameter to the operator.
10028 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010029 ClassLoc, ClassLoc,
10030 /*Id=*/nullptr, ArgType,
10031 /*TInfo=*/nullptr, SC_None,
10032 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010033 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010034
Richard Smith6b02d462012-12-08 08:32:28 +000010035 AddOverriddenMethods(ClassDecl, CopyAssignment);
10036
10037 CopyAssignment->setTrivial(
10038 ClassDecl->needsOverloadResolutionForCopyAssignment()
10039 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10040 : ClassDecl->hasTrivialCopyAssignment());
10041
Richard Smith852265f2012-03-30 20:53:28 +000010042 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +000010043 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010044
Richard Smith6b02d462012-12-08 08:32:28 +000010045 // Note that we have added this copy-assignment operator.
10046 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10047
10048 if (Scope *S = getScopeForContext(ClassDecl))
10049 PushOnScopeChains(CopyAssignment, S, false);
10050 ClassDecl->addDecl(CopyAssignment);
10051
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010052 return CopyAssignment;
10053}
10054
Richard Smithd577fbb2013-06-13 03:23:42 +000010055/// Diagnose an implicit copy operation for a class which is odr-used, but
10056/// which is deprecated because the class has a user-declared copy constructor,
10057/// copy assignment operator, or destructor.
10058static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10059 SourceLocation UseLoc) {
10060 assert(CopyOp->isImplicit());
10061
10062 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010063 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010064
10065 // In Microsoft mode, assignment operations don't affect constructors and
10066 // vice versa.
10067 if (RD->hasUserDeclaredDestructor()) {
10068 UserDeclaredOperation = RD->getDestructor();
10069 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10070 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010071 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010072 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010073 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010074 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010075 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010076 break;
10077 }
10078 }
10079 assert(UserDeclaredOperation);
10080 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10081 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010082 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010083 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010084 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010085 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010086 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010087 break;
10088 }
10089 }
10090 assert(UserDeclaredOperation);
10091 }
10092
10093 if (UserDeclaredOperation) {
10094 S.Diag(UserDeclaredOperation->getLocation(),
10095 diag::warn_deprecated_copy_operation)
10096 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10097 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10098 S.Diag(UseLoc, diag::note_member_synthesized_at)
10099 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10100 : Sema::CXXCopyAssignment)
10101 << RD;
10102 }
10103}
10104
Douglas Gregorb139cd52010-05-01 20:49:11 +000010105void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10106 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010107 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010108 CopyAssignOperator->isOverloadedOperator() &&
10109 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010110 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10111 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010112 "DefineImplicitCopyAssignment called for wrong function");
10113
10114 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10115
10116 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10117 CopyAssignOperator->setInvalidDecl();
10118 return;
10119 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010120
10121 // C++11 [class.copy]p18:
10122 // The [definition of an implicitly declared copy assignment operator] is
10123 // deprecated if the class has a user-declared copy constructor or a
10124 // user-declared destructor.
10125 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10126 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10127
Eli Friedman276dd182013-09-05 00:02:25 +000010128 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010129
Eli Friedmaneaf34142012-10-18 20:14:08 +000010130 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010131 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010132
10133 // C++0x [class.copy]p30:
10134 // The implicitly-defined or explicitly-defaulted copy assignment operator
10135 // for a non-union class X performs memberwise copy assignment of its
10136 // subobjects. The direct base classes of X are assigned first, in the
10137 // order of their declaration in the base-specifier-list, and then the
10138 // immediate non-static data members of X are assigned, in the order in
10139 // which they were declared in the class definition.
10140
10141 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010142 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010143
10144 // The parameter for the "other" object, which we are copying from.
10145 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10146 Qualifiers OtherQuals = Other->getType().getQualifiers();
10147 QualType OtherRefType = Other->getType();
10148 if (const LValueReferenceType *OtherRef
10149 = OtherRefType->getAs<LValueReferenceType>()) {
10150 OtherRefType = OtherRef->getPointeeType();
10151 OtherQuals = OtherRefType.getQualifiers();
10152 }
10153
10154 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010155 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10156 ? CopyAssignOperator->getLocEnd()
10157 : CopyAssignOperator->getLocation();
10158
Pavel Labath58934982013-08-30 08:52:28 +000010159 // Builds a DeclRefExpr for the "other" object.
10160 RefBuilder OtherRef(Other, OtherRefType);
10161
10162 // Builds the "this" pointer.
10163 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010164
10165 // Assign base classes.
10166 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010167 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010168 // Form the assignment:
10169 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010170 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010171 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010172 Invalid = true;
10173 continue;
10174 }
10175
John McCallcf142162010-08-07 06:22:56 +000010176 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010177 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010178
Douglas Gregorb139cd52010-05-01 20:49:11 +000010179 // Construct the "from" expression, which is an implicit cast to the
10180 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010181 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10182 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010183
10184 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010185 DerefBuilder DerefThis(This);
10186 CastBuilder To(DerefThis,
10187 Context.getCVRQualifiedType(
10188 BaseType, CopyAssignOperator->getTypeQualifiers()),
10189 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010190
10191 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010192 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010193 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194 /*CopyingBaseSubobject=*/true,
10195 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010196 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010197 Diag(CurrentLocation, diag::note_member_synthesized_at)
10198 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10199 CopyAssignOperator->setInvalidDecl();
10200 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010201 }
10202
10203 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010204 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010205 }
10206
Douglas Gregorb139cd52010-05-01 20:49:11 +000010207 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010208 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010209 if (Field->isUnnamedBitfield())
10210 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010211
10212 if (Field->isInvalidDecl()) {
10213 Invalid = true;
10214 continue;
10215 }
10216
Douglas Gregorb139cd52010-05-01 20:49:11 +000010217 // Check for members of reference type; we can't copy those.
10218 if (Field->getType()->isReferenceType()) {
10219 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10220 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10221 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010222 Diag(CurrentLocation, diag::note_member_synthesized_at)
10223 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010224 Invalid = true;
10225 continue;
10226 }
10227
10228 // Check for members of const-qualified, non-class type.
10229 QualType BaseType = Context.getBaseElementType(Field->getType());
10230 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10231 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10232 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10233 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010234 Diag(CurrentLocation, diag::note_member_synthesized_at)
10235 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010236 Invalid = true;
10237 continue;
10238 }
John McCall1b1a1db2011-06-17 00:18:42 +000010239
10240 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010241 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10242 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010243
10244 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010245 if (FieldType->isIncompleteArrayType()) {
10246 assert(ClassDecl->hasFlexibleArrayMember() &&
10247 "Incomplete array type is not valid");
10248 continue;
10249 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010250
10251 // Build references to the field in the object we're copying from and to.
10252 CXXScopeSpec SS; // Intentionally empty
10253 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10254 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010255 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010256 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010257
10258 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10259
10260 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010261
Douglas Gregorb139cd52010-05-01 20:49:11 +000010262 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010263 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010264 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010265 /*CopyingBaseSubobject=*/false,
10266 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010267 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010268 Diag(CurrentLocation, diag::note_member_synthesized_at)
10269 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10270 CopyAssignOperator->setInvalidDecl();
10271 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010272 }
10273
10274 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010275 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010276 }
10277
10278 if (!Invalid) {
10279 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010280 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010281
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010282 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010283 if (Return.isInvalid())
10284 Invalid = true;
10285 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010286 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010287
10288 if (Trap.hasErrorOccurred()) {
10289 Diag(CurrentLocation, diag::note_member_synthesized_at)
10290 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10291 Invalid = true;
10292 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010293 }
10294 }
10295
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010296 // The exception specification is needed because we are defining the
10297 // function.
10298 ResolveExceptionSpec(CurrentLocation,
10299 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10300
Douglas Gregorb139cd52010-05-01 20:49:11 +000010301 if (Invalid) {
10302 CopyAssignOperator->setInvalidDecl();
10303 return;
10304 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010305
10306 StmtResult Body;
10307 {
10308 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010309 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010310 /*isStmtExpr=*/false);
10311 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10312 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010313 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010314
10315 if (ASTMutationListener *L = getASTMutationListener()) {
10316 L->CompletedImplicitDefinition(CopyAssignOperator);
10317 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010318}
10319
Sebastian Redl22653ba2011-08-30 19:58:05 +000010320Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010321Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10322 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010323
Richard Smithd3b5c9082012-07-27 04:22:15 +000010324 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010325 if (ClassDecl->isInvalidDecl())
10326 return ExceptSpec;
10327
10328 // C++0x [except.spec]p14:
10329 // An implicitly declared special member function (Clause 12) shall have an
10330 // exception-specification. [...]
10331
10332 // It is unspecified whether or not an implicit move assignment operator
10333 // attempts to deduplicate calls to assignment operators of virtual bases are
10334 // made. As such, this exception specification is effectively unspecified.
10335 // Based on a similar decision made for constness in C++0x, we're erring on
10336 // the side of assuming such calls to be made regardless of whether they
10337 // actually happen.
10338 // Note that a move constructor is not implicitly declared when there are
10339 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010340 for (const auto &Base : ClassDecl->bases()) {
10341 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010342 continue;
10343
10344 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010345 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010346 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010347 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010348 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010349 }
10350
Aaron Ballman445a9392014-03-13 16:15:17 +000010351 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010352 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010353 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010354 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010355 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010356 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010357 }
10358
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010359 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010360 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010361 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010362 if (CXXMethodDecl *MoveAssign =
10363 LookupMovingAssignment(FieldClassDecl,
10364 FieldType.getCVRQualifiers(),
10365 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010366 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010367 }
10368 }
10369
10370 return ExceptSpec;
10371}
10372
10373CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010374 assert(ClassDecl->needsImplicitMoveAssignment());
10375
Richard Smith8bf22e52012-11-29 01:34:07 +000010376 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10377 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010378 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010379
Sebastian Redl22653ba2011-08-30 19:58:05 +000010380 // Note: The following rules are largely analoguous to the move
10381 // constructor rules.
10382
Sebastian Redl22653ba2011-08-30 19:58:05 +000010383 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10384 QualType RetType = Context.getLValueReferenceType(ArgType);
10385 ArgType = Context.getRValueReferenceType(ArgType);
10386
Richard Smith99005e62013-05-07 03:19:20 +000010387 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10388 CXXMoveAssignment,
10389 false);
10390
Sebastian Redl22653ba2011-08-30 19:58:05 +000010391 // An implicitly-declared move assignment operator is an inline public
10392 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010393 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10394 SourceLocation ClassLoc = ClassDecl->getLocation();
10395 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010396 CXXMethodDecl *MoveAssignment =
10397 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010398 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010399 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010400 MoveAssignment->setAccess(AS_public);
10401 MoveAssignment->setDefaulted();
10402 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010403
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010404 if (getLangOpts().CUDA) {
10405 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10406 MoveAssignment,
10407 /* ConstRHS */ false,
10408 /* Diagnose */ false);
10409 }
10410
Richard Smithd3b5c9082012-07-27 04:22:15 +000010411 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010412 FunctionProtoType::ExtProtoInfo EPI =
10413 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010414 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010415
Sebastian Redl22653ba2011-08-30 19:58:05 +000010416 // Add the parameter to the operator.
10417 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010418 ClassLoc, ClassLoc,
10419 /*Id=*/nullptr, ArgType,
10420 /*TInfo=*/nullptr, SC_None,
10421 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010422 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010423
Richard Smith6b02d462012-12-08 08:32:28 +000010424 AddOverriddenMethods(ClassDecl, MoveAssignment);
10425
10426 MoveAssignment->setTrivial(
10427 ClassDecl->needsOverloadResolutionForMoveAssignment()
10428 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10429 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010430
Richard Smithd951a1d2012-02-18 02:02:13 +000010431 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010432 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10433 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010434 }
10435
Richard Smith6b02d462012-12-08 08:32:28 +000010436 // Note that we have added this copy-assignment operator.
10437 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10438
Sebastian Redl22653ba2011-08-30 19:58:05 +000010439 if (Scope *S = getScopeForContext(ClassDecl))
10440 PushOnScopeChains(MoveAssignment, S, false);
10441 ClassDecl->addDecl(MoveAssignment);
10442
Sebastian Redl22653ba2011-08-30 19:58:05 +000010443 return MoveAssignment;
10444}
10445
Richard Smithb2504bd2013-11-04 04:26:14 +000010446/// Check if we're implicitly defining a move assignment operator for a class
10447/// with virtual bases. Such a move assignment might move-assign the virtual
10448/// base multiple times.
10449static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10450 SourceLocation CurrentLocation) {
10451 assert(!Class->isDependentContext() && "should not define dependent move");
10452
10453 // Only a virtual base could get implicitly move-assigned multiple times.
10454 // Only a non-trivial move assignment can observe this. We only want to
10455 // diagnose if we implicitly define an assignment operator that assigns
10456 // two base classes, both of which move-assign the same virtual base.
10457 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10458 Class->getNumBases() < 2)
10459 return;
10460
10461 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10462 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10463 VBaseMap VBases;
10464
Aaron Ballman574705e2014-03-13 15:41:46 +000010465 for (auto &BI : Class->bases()) {
10466 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010467 while (!Worklist.empty()) {
10468 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10469 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10470
10471 // If the base has no non-trivial move assignment operators,
10472 // we don't care about moves from it.
10473 if (!Base->hasNonTrivialMoveAssignment())
10474 continue;
10475
10476 // If there's nothing virtual here, skip it.
10477 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10478 continue;
10479
10480 // If we're not actually going to call a move assignment for this base,
10481 // or the selected move assignment is trivial, skip it.
10482 Sema::SpecialMemberOverloadResult *SMOR =
10483 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10484 /*ConstArg*/false, /*VolatileArg*/false,
10485 /*RValueThis*/true, /*ConstThis*/false,
10486 /*VolatileThis*/false);
10487 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10488 !SMOR->getMethod()->isMoveAssignmentOperator())
10489 continue;
10490
10491 if (BaseSpec->isVirtual()) {
10492 // We're going to move-assign this virtual base, and its move
10493 // assignment operator is not trivial. If this can happen for
10494 // multiple distinct direct bases of Class, diagnose it. (If it
10495 // only happens in one base, we'll diagnose it when synthesizing
10496 // that base class's move assignment operator.)
10497 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010498 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010499 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010500 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010501 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10502 << Class << Base;
10503 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10504 << (Base->getCanonicalDecl() ==
10505 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10506 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010507 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010508 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010509 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10510 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010511
10512 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010513 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010514 }
10515 } else {
10516 // Only walk over bases that have defaulted move assignment operators.
10517 // We assume that any user-provided move assignment operator handles
10518 // the multiple-moves-of-vbase case itself somehow.
10519 if (!SMOR->getMethod()->isDefaulted())
10520 continue;
10521
10522 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010523 for (auto &BI : Base->bases())
10524 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010525 }
10526 }
10527 }
10528}
10529
Sebastian Redl22653ba2011-08-30 19:58:05 +000010530void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10531 CXXMethodDecl *MoveAssignOperator) {
10532 assert((MoveAssignOperator->isDefaulted() &&
10533 MoveAssignOperator->isOverloadedOperator() &&
10534 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010535 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10536 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010537 "DefineImplicitMoveAssignment called for wrong function");
10538
10539 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10540
10541 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10542 MoveAssignOperator->setInvalidDecl();
10543 return;
10544 }
10545
Eli Friedman276dd182013-09-05 00:02:25 +000010546 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010547
Eli Friedmaneaf34142012-10-18 20:14:08 +000010548 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010549 DiagnosticErrorTrap Trap(Diags);
10550
10551 // C++0x [class.copy]p28:
10552 // The implicitly-defined or move assignment operator for a non-union class
10553 // X performs memberwise move assignment of its subobjects. The direct base
10554 // classes of X are assigned first, in the order of their declaration in the
10555 // base-specifier-list, and then the immediate non-static data members of X
10556 // are assigned, in the order in which they were declared in the class
10557 // definition.
10558
Richard Smithb2504bd2013-11-04 04:26:14 +000010559 // Issue a warning if our implicit move assignment operator will move
10560 // from a virtual base more than once.
10561 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010562
Sebastian Redl22653ba2011-08-30 19:58:05 +000010563 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010564 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010565
10566 // The parameter for the "other" object, which we are move from.
10567 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10568 QualType OtherRefType = Other->getType()->
10569 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010570 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010571 "Bad argument type of defaulted move assignment");
10572
10573 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010574 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10575 ? MoveAssignOperator->getLocEnd()
10576 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010577
Pavel Labath58934982013-08-30 08:52:28 +000010578 // Builds a reference to the "other" object.
10579 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010580 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010581 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010582
Pavel Labath58934982013-08-30 08:52:28 +000010583 // Builds the "this" pointer.
10584 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010585
Sebastian Redl22653ba2011-08-30 19:58:05 +000010586 // Assign base classes.
10587 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010588 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010589 // C++11 [class.copy]p28:
10590 // It is unspecified whether subobjects representing virtual base classes
10591 // are assigned more than once by the implicitly-defined copy assignment
10592 // operator.
10593 // FIXME: Do not assign to a vbase that will be assigned by some other base
10594 // class. For a move-assignment, this can result in the vbase being moved
10595 // multiple times.
10596
Sebastian Redl22653ba2011-08-30 19:58:05 +000010597 // Form the assignment:
10598 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010599 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010600 if (!BaseType->isRecordType()) {
10601 Invalid = true;
10602 continue;
10603 }
10604
10605 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010606 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010607
10608 // Construct the "from" expression, which is an implicit cast to the
10609 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010610 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010611
10612 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010613 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010614
10615 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010616 CastBuilder To(DerefThis,
10617 Context.getCVRQualifiedType(
10618 BaseType, MoveAssignOperator->getTypeQualifiers()),
10619 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010620
10621 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010622 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010623 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010624 /*CopyingBaseSubobject=*/true,
10625 /*Copying=*/false);
10626 if (Move.isInvalid()) {
10627 Diag(CurrentLocation, diag::note_member_synthesized_at)
10628 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10629 MoveAssignOperator->setInvalidDecl();
10630 return;
10631 }
10632
10633 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010634 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010635 }
10636
Sebastian Redl22653ba2011-08-30 19:58:05 +000010637 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010638 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010639 if (Field->isUnnamedBitfield())
10640 continue;
10641
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010642 if (Field->isInvalidDecl()) {
10643 Invalid = true;
10644 continue;
10645 }
10646
Sebastian Redl22653ba2011-08-30 19:58:05 +000010647 // Check for members of reference type; we can't move those.
10648 if (Field->getType()->isReferenceType()) {
10649 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10650 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10651 Diag(Field->getLocation(), diag::note_declared_at);
10652 Diag(CurrentLocation, diag::note_member_synthesized_at)
10653 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10654 Invalid = true;
10655 continue;
10656 }
10657
10658 // Check for members of const-qualified, non-class type.
10659 QualType BaseType = Context.getBaseElementType(Field->getType());
10660 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10661 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10662 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10663 Diag(Field->getLocation(), diag::note_declared_at);
10664 Diag(CurrentLocation, diag::note_member_synthesized_at)
10665 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10666 Invalid = true;
10667 continue;
10668 }
10669
10670 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010671 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10672 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010673
10674 QualType FieldType = Field->getType().getNonReferenceType();
10675 if (FieldType->isIncompleteArrayType()) {
10676 assert(ClassDecl->hasFlexibleArrayMember() &&
10677 "Incomplete array type is not valid");
10678 continue;
10679 }
10680
10681 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010682 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10683 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010684 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010685 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010686 MemberBuilder From(MoveOther, OtherRefType,
10687 /*IsArrow=*/false, MemberLookup);
10688 MemberBuilder To(This, getCurrentThisType(),
10689 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010690
Pavel Labath58934982013-08-30 08:52:28 +000010691 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010692 "Member reference with rvalue base must be rvalue except for reference "
10693 "members, which aren't allowed for move assignment.");
10694
Sebastian Redl22653ba2011-08-30 19:58:05 +000010695 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010696 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010697 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010698 /*CopyingBaseSubobject=*/false,
10699 /*Copying=*/false);
10700 if (Move.isInvalid()) {
10701 Diag(CurrentLocation, diag::note_member_synthesized_at)
10702 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10703 MoveAssignOperator->setInvalidDecl();
10704 return;
10705 }
Richard Smith11d19592012-11-12 23:33:00 +000010706
Sebastian Redl22653ba2011-08-30 19:58:05 +000010707 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010708 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010709 }
10710
10711 if (!Invalid) {
10712 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010713 ExprResult ThisObj =
10714 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10715
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010716 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010717 if (Return.isInvalid())
10718 Invalid = true;
10719 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010720 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010721
10722 if (Trap.hasErrorOccurred()) {
10723 Diag(CurrentLocation, diag::note_member_synthesized_at)
10724 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10725 Invalid = true;
10726 }
10727 }
10728 }
10729
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010730 // The exception specification is needed because we are defining the
10731 // function.
10732 ResolveExceptionSpec(CurrentLocation,
10733 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10734
Sebastian Redl22653ba2011-08-30 19:58:05 +000010735 if (Invalid) {
10736 MoveAssignOperator->setInvalidDecl();
10737 return;
10738 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010739
10740 StmtResult Body;
10741 {
10742 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010743 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010744 /*isStmtExpr=*/false);
10745 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10746 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010747 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010748
10749 if (ASTMutationListener *L = getASTMutationListener()) {
10750 L->CompletedImplicitDefinition(MoveAssignOperator);
10751 }
10752}
10753
Richard Smithd3b5c9082012-07-27 04:22:15 +000010754Sema::ImplicitExceptionSpecification
10755Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10756 CXXRecordDecl *ClassDecl = MD->getParent();
10757
10758 ImplicitExceptionSpecification ExceptSpec(*this);
10759 if (ClassDecl->isInvalidDecl())
10760 return ExceptSpec;
10761
10762 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010763 assert(T->getNumParams() >= 1 && "not a copy ctor");
10764 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010765
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010766 // C++ [except.spec]p14:
10767 // An implicitly declared special member function (Clause 12) shall have an
10768 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010769 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010770 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010771 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010772 continue;
10773
Douglas Gregora6d69502010-07-02 23:41:54 +000010774 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010775 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010776 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010777 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010778 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010779 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010780 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010781 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010782 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010783 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010784 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010785 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010786 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010787 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010788 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010789 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10790 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010791 LookupCopyingConstructor(FieldClassDecl,
10792 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010793 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010794 }
10795 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010796
Richard Smithd3b5c9082012-07-27 04:22:15 +000010797 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010798}
10799
10800CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10801 CXXRecordDecl *ClassDecl) {
10802 // C++ [class.copy]p4:
10803 // If the class definition does not explicitly declare a copy
10804 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010805 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010806
Richard Smith8bf22e52012-11-29 01:34:07 +000010807 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10808 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010809 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010810
Alexis Hunt913820d2011-05-13 06:10:58 +000010811 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10812 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010813 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010814 if (Const)
10815 ArgType = ArgType.withConst();
10816 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010817
Richard Smithb5800092012-06-10 05:43:50 +000010818 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10819 CXXCopyConstructor,
10820 Const);
10821
Douglas Gregor54be3392010-07-01 17:57:27 +000010822 DeclarationName Name
10823 = Context.DeclarationNames.getCXXConstructorName(
10824 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010825 SourceLocation ClassLoc = ClassDecl->getLocation();
10826 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010827
10828 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010829 // member of its class.
10830 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010831 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010832 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010833 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010834 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010835 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010836
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010837 if (getLangOpts().CUDA) {
10838 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10839 CopyConstructor,
10840 /* ConstRHS */ Const,
10841 /* Diagnose */ false);
10842 }
10843
Richard Smithd3b5c9082012-07-27 04:22:15 +000010844 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010845 FunctionProtoType::ExtProtoInfo EPI =
10846 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010847 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010848 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010849
Douglas Gregor54be3392010-07-01 17:57:27 +000010850 // Add the parameter to the constructor.
10851 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010852 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010853 /*IdentifierInfo=*/nullptr,
10854 ArgType, /*TInfo=*/nullptr,
10855 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010856 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010857
Richard Smith6b02d462012-12-08 08:32:28 +000010858 CopyConstructor->setTrivial(
10859 ClassDecl->needsOverloadResolutionForCopyConstructor()
10860 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10861 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010862
Richard Smith852265f2012-03-30 20:53:28 +000010863 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010864 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010865
Richard Smith6b02d462012-12-08 08:32:28 +000010866 // Note that we have declared this constructor.
10867 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10868
10869 if (Scope *S = getScopeForContext(ClassDecl))
10870 PushOnScopeChains(CopyConstructor, S, false);
10871 ClassDecl->addDecl(CopyConstructor);
10872
Douglas Gregor54be3392010-07-01 17:57:27 +000010873 return CopyConstructor;
10874}
10875
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010876void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010877 CXXConstructorDecl *CopyConstructor) {
10878 assert((CopyConstructor->isDefaulted() &&
10879 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010880 !CopyConstructor->doesThisDeclarationHaveABody() &&
10881 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010882 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010883
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010884 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010885 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010886
Richard Smithd577fbb2013-06-13 03:23:42 +000010887 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010888 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010889 // deprecated if the class has a user-declared copy assignment operator
10890 // or a user-declared destructor.
10891 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10892 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10893
Eli Friedmaneaf34142012-10-18 20:14:08 +000010894 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010895 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010896
David Blaikie3fc2f912013-01-17 05:26:25 +000010897 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010898 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010899 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010900 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010901 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010902 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010903 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10904 ? CopyConstructor->getLocEnd()
10905 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010906 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010907 CopyConstructor->setBody(
10908 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010909 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010910
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010911 // The exception specification is needed because we are defining the
10912 // function.
10913 ResolveExceptionSpec(CurrentLocation,
10914 CopyConstructor->getType()->castAs<FunctionProtoType>());
10915
Eli Friedman276dd182013-09-05 00:02:25 +000010916 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010917 MarkVTableUsed(CurrentLocation, ClassDecl);
10918
Sebastian Redlab238a72011-04-24 16:28:06 +000010919 if (ASTMutationListener *L = getASTMutationListener()) {
10920 L->CompletedImplicitDefinition(CopyConstructor);
10921 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010922}
10923
Sebastian Redl22653ba2011-08-30 19:58:05 +000010924Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010925Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10926 CXXRecordDecl *ClassDecl = MD->getParent();
10927
Sebastian Redl22653ba2011-08-30 19:58:05 +000010928 // C++ [except.spec]p14:
10929 // An implicitly declared special member function (Clause 12) shall have an
10930 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010931 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010932 if (ClassDecl->isInvalidDecl())
10933 return ExceptSpec;
10934
10935 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010936 for (const auto &B : ClassDecl->bases()) {
10937 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010938 continue;
10939
Aaron Ballman574705e2014-03-13 15:41:46 +000010940 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010941 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010942 CXXConstructorDecl *Constructor =
10943 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010944 // If this is a deleted function, add it anyway. This might be conformant
10945 // with the standard. This might not. I'm not sure. It might not matter.
10946 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010947 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010948 }
10949 }
10950
10951 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010952 for (const auto &B : ClassDecl->vbases()) {
10953 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010954 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010955 CXXConstructorDecl *Constructor =
10956 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010957 // If this is a deleted function, add it anyway. This might be conformant
10958 // with the standard. This might not. I'm not sure. It might not matter.
10959 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010960 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010961 }
10962 }
10963
10964 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010965 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010966 QualType FieldType = Context.getBaseElementType(F->getType());
10967 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10968 CXXConstructorDecl *Constructor =
10969 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010970 // If this is a deleted function, add it anyway. This might be conformant
10971 // with the standard. This might not. I'm not sure. It might not matter.
10972 // In particular, the problem is that this function never gets called. It
10973 // might just be ill-formed because this function attempts to refer to
10974 // a deleted function here.
10975 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010976 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010977 }
10978 }
10979
10980 return ExceptSpec;
10981}
10982
10983CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10984 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010985 assert(ClassDecl->needsImplicitMoveConstructor());
10986
Richard Smith8bf22e52012-11-29 01:34:07 +000010987 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10988 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010989 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010990
Sebastian Redl22653ba2011-08-30 19:58:05 +000010991 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10992 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010993
Richard Smithb5800092012-06-10 05:43:50 +000010994 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10995 CXXMoveConstructor,
10996 false);
10997
Sebastian Redl22653ba2011-08-30 19:58:05 +000010998 DeclarationName Name
10999 = Context.DeclarationNames.getCXXConstructorName(
11000 Context.getCanonicalType(ClassType));
11001 SourceLocation ClassLoc = ClassDecl->getLocation();
11002 DeclarationNameInfo NameInfo(Name, ClassLoc);
11003
Richard Smith99005e62013-05-07 03:19:20 +000011004 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011005 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011006 // member of its class.
11007 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011008 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011009 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011010 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011011 MoveConstructor->setAccess(AS_public);
11012 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011013
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011014 if (getLangOpts().CUDA) {
11015 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11016 MoveConstructor,
11017 /* ConstRHS */ false,
11018 /* Diagnose */ false);
11019 }
11020
Richard Smithd3b5c9082012-07-27 04:22:15 +000011021 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011022 FunctionProtoType::ExtProtoInfo EPI =
11023 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011024 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011025 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011026
Sebastian Redl22653ba2011-08-30 19:58:05 +000011027 // Add the parameter to the constructor.
11028 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11029 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011030 /*IdentifierInfo=*/nullptr,
11031 ArgType, /*TInfo=*/nullptr,
11032 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011033 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011034
Richard Smith6b02d462012-12-08 08:32:28 +000011035 MoveConstructor->setTrivial(
11036 ClassDecl->needsOverloadResolutionForMoveConstructor()
11037 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11038 : ClassDecl->hasTrivialMoveConstructor());
11039
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000011040 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011041 ClassDecl->setImplicitMoveConstructorIsDeleted();
11042 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011043 }
11044
11045 // Note that we have declared this constructor.
11046 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11047
11048 if (Scope *S = getScopeForContext(ClassDecl))
11049 PushOnScopeChains(MoveConstructor, S, false);
11050 ClassDecl->addDecl(MoveConstructor);
11051
11052 return MoveConstructor;
11053}
11054
11055void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11056 CXXConstructorDecl *MoveConstructor) {
11057 assert((MoveConstructor->isDefaulted() &&
11058 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011059 !MoveConstructor->doesThisDeclarationHaveABody() &&
11060 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011061 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11062
11063 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11064 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11065
Eli Friedmaneaf34142012-10-18 20:14:08 +000011066 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011067 DiagnosticErrorTrap Trap(Diags);
11068
David Blaikie3fc2f912013-01-17 05:26:25 +000011069 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011070 Trap.hasErrorOccurred()) {
11071 Diag(CurrentLocation, diag::note_member_synthesized_at)
11072 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11073 MoveConstructor->setInvalidDecl();
11074 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011075 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11076 ? MoveConstructor->getLocEnd()
11077 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011078 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011079 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011080 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011081 }
11082
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011083 // The exception specification is needed because we are defining the
11084 // function.
11085 ResolveExceptionSpec(CurrentLocation,
11086 MoveConstructor->getType()->castAs<FunctionProtoType>());
11087
Eli Friedman276dd182013-09-05 00:02:25 +000011088 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011089 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011090
11091 if (ASTMutationListener *L = getASTMutationListener()) {
11092 L->CompletedImplicitDefinition(MoveConstructor);
11093 }
11094}
11095
Douglas Gregor74f7d502012-02-15 19:33:52 +000011096bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011097 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011098}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011099
11100void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011101 SourceLocation CurrentLocation,
11102 CXXConversionDecl *Conv) {
11103 CXXRecordDecl *Lambda = Conv->getParent();
11104 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11105 // If we are defining a specialization of a conversion to function-ptr
11106 // cache the deduced template arguments for this specialization
11107 // so that we can use them to retrieve the corresponding call-operator
11108 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011109 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11110
Faisal Vali571df122013-09-29 08:45:24 +000011111 // Retrieve the corresponding call-operator specialization.
11112 if (Lambda->isGenericLambda()) {
11113 assert(Conv->isFunctionTemplateSpecialization());
11114 FunctionTemplateDecl *CallOpTemplate =
11115 CallOp->getDescribedFunctionTemplate();
11116 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011117 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011118 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011119 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011120 InsertPos);
11121 assert(CallOpSpec &&
11122 "Conversion operator must have a corresponding call operator");
11123 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11124 }
11125 // Mark the call operator referenced (and add to pending instantiations
11126 // if necessary).
11127 // For both the conversion and static-invoker template specializations
11128 // we construct their body's in this function, so no need to add them
11129 // to the PendingInstantiations.
11130 MarkFunctionReferenced(CurrentLocation, CallOp);
11131
Eli Friedmaneaf34142012-10-18 20:14:08 +000011132 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011133 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011134
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011135 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011136 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11137 // ... and get the corresponding specialization for a generic lambda.
11138 if (Lambda->isGenericLambda()) {
11139 assert(DeducedTemplateArgs &&
11140 "Must have deduced template arguments from Conversion Operator");
11141 FunctionTemplateDecl *InvokeTemplate =
11142 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011143 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011144 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011145 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011146 InsertPos);
11147 assert(InvokeSpec &&
11148 "Must have a corresponding static invoker specialization");
11149 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11150 }
11151 // Construct the body of the conversion function { return __invoke; }.
11152 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011153 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011154 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011155 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011156 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11157 Conv->getLocation(),
11158 Conv->getLocation()));
11159
11160 Conv->markUsed(Context);
11161 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011162
Faisal Vali571df122013-09-29 08:45:24 +000011163 // Fill in the __invoke function with a dummy implementation. IR generation
11164 // will fill in the actual details.
11165 Invoker->markUsed(Context);
11166 Invoker->setReferenced();
11167 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11168
Douglas Gregord3b672c2012-02-16 01:06:16 +000011169 if (ASTMutationListener *L = getASTMutationListener()) {
11170 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011171 L->CompletedImplicitDefinition(Invoker);
11172 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011173}
11174
Faisal Vali571df122013-09-29 08:45:24 +000011175
11176
Douglas Gregord3b672c2012-02-16 01:06:16 +000011177void Sema::DefineImplicitLambdaToBlockPointerConversion(
11178 SourceLocation CurrentLocation,
11179 CXXConversionDecl *Conv)
11180{
Faisal Vali850da1a2013-09-29 17:08:32 +000011181 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011182
Eli Friedman276dd182013-09-05 00:02:25 +000011183 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011184
Eli Friedmaneaf34142012-10-18 20:14:08 +000011185 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011186 DiagnosticErrorTrap Trap(Diags);
11187
Douglas Gregored90df32012-02-22 05:02:47 +000011188 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011189 Expr *This = ActOnCXXThis(CurrentLocation).get();
11190 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011191
Eli Friedman98b01ed2012-03-01 04:01:32 +000011192 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11193 Conv->getLocation(),
11194 Conv, DerefThis);
11195
11196 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11197 // behavior. Note that only the general conversion function does this
11198 // (since it's unusable otherwise); in the case where we inline the
11199 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011200 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011201 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11202 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011203 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011204
11205 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011206 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011207 Conv->setInvalidDecl();
11208 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011209 }
Douglas Gregored90df32012-02-22 05:02:47 +000011210
Douglas Gregored90df32012-02-22 05:02:47 +000011211 // Create the return statement that returns the block from the conversion
11212 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011213 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011214 if (Return.isInvalid()) {
11215 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11216 Conv->setInvalidDecl();
11217 return;
11218 }
11219
11220 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011221 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011222 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011223 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011224 Conv->getLocation()));
11225
Douglas Gregored90df32012-02-22 05:02:47 +000011226 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011227 if (ASTMutationListener *L = getASTMutationListener()) {
11228 L->CompletedImplicitDefinition(Conv);
11229 }
11230}
11231
Douglas Gregord2f70072012-03-10 06:53:13 +000011232/// \brief Determine whether the given list arguments contains exactly one
11233/// "real" (non-default) argument.
11234static bool hasOneRealArgument(MultiExprArg Args) {
11235 switch (Args.size()) {
11236 case 0:
11237 return false;
11238
11239 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011240 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011241 return false;
11242
11243 // fall through
11244 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011245 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011246 }
11247
11248 return false;
11249}
11250
John McCalldadc5752010-08-24 06:29:42 +000011251ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011252Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011253 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011254 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011255 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011256 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011257 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011258 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011259 unsigned ConstructKind,
11260 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011261 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011262
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011263 // C++0x [class.copy]p34:
11264 // When certain criteria are met, an implementation is allowed to
11265 // omit the copy/move construction of a class object, even if the
11266 // copy/move constructor and/or destructor for the object have
11267 // side effects. [...]
11268 // - when a temporary class object that has not been bound to a
11269 // reference (12.2) would be copied/moved to a class object
11270 // with the same cv-unqualified type, the copy/move operation
11271 // can be omitted by constructing the temporary object
11272 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011273 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011274 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011275 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011276 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011277 }
Mike Stump11289f42009-09-09 15:08:12 +000011278
11279 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011280 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011281 IsListInitialization,
11282 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011283 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011284}
11285
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011286/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11287/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011288ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011289Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11290 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011291 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011292 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011293 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011294 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011295 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011296 unsigned ConstructKind,
11297 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011298 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011299 return CXXConstructExpr::Create(
11300 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011301 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11302 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011303 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11304 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011305}
11306
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011307ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11308 assert(Field->hasInClassInitializer());
11309
11310 // If we already have the in-class initializer nothing needs to be done.
11311 if (Field->getInClassInitializer())
11312 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11313
11314 // Maybe we haven't instantiated the in-class initializer. Go check the
11315 // pattern FieldDecl to see if it has one.
11316 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11317
11318 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11319 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11320 DeclContext::lookup_result Lookup =
11321 ClassPattern->lookup(Field->getDeclName());
11322 assert(Lookup.size() == 1);
11323 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11324 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11325 getTemplateInstantiationArgs(Field)))
11326 return ExprError();
11327 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11328 }
11329
11330 // DR1351:
11331 // If the brace-or-equal-initializer of a non-static data member
11332 // invokes a defaulted default constructor of its class or of an
11333 // enclosing class in a potentially evaluated subexpression, the
11334 // program is ill-formed.
11335 //
11336 // This resolution is unworkable: the exception specification of the
11337 // default constructor can be needed in an unevaluated context, in
11338 // particular, in the operand of a noexcept-expression, and we can be
11339 // unable to compute an exception specification for an enclosed class.
11340 //
11341 // Any attempt to resolve the exception specification of a defaulted default
11342 // constructor before the initializer is lexically complete will ultimately
11343 // come here at which point we can diagnose it.
11344 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11345 if (OutermostClass == ParentRD) {
11346 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11347 << ParentRD << Field;
11348 } else {
11349 Diag(Field->getLocEnd(),
11350 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11351 << ParentRD << OutermostClass << Field;
11352 }
11353
11354 return ExprError();
11355}
11356
John McCall03c48482010-02-02 09:10:11 +000011357void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011358 if (VD->isInvalidDecl()) return;
11359
John McCall03c48482010-02-02 09:10:11 +000011360 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011361 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011362 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011363 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011364
Chandler Carruth86d17d32011-03-27 21:26:48 +000011365 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011366 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011367 CheckDestructorAccess(VD->getLocation(), Destructor,
11368 PDiag(diag::err_access_dtor_var)
11369 << VD->getDeclName()
11370 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011371 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011372
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011373 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011374 if (!VD->hasGlobalStorage()) return;
11375
11376 // Emit warning for non-trivial dtor in global scope (a real global,
11377 // class-static, function-static).
11378 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11379
11380 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011381 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011382 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011383}
11384
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011385/// \brief Given a constructor and the set of arguments provided for the
11386/// constructor, convert the arguments and add any required default arguments
11387/// to form a proper call to this constructor.
11388///
11389/// \returns true if an error occurred, false otherwise.
11390bool
11391Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11392 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011393 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011394 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011395 bool AllowExplicit,
11396 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011397 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11398 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011399 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011400
11401 const FunctionProtoType *Proto
11402 = Constructor->getType()->getAs<FunctionProtoType>();
11403 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011404 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011405
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011406 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011407 if (NumArgs < NumParams)
11408 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011409 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011410 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011411
11412 VariadicCallType CallType =
11413 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011414 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011415 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011416 Proto, 0,
11417 llvm::makeArrayRef(Args, NumArgs),
11418 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011419 CallType, AllowExplicit,
11420 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011421 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011422
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011423 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011424
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011425 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011426 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011427 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011428
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011429 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011430}
11431
Anders Carlssone363c8e2009-12-12 00:32:00 +000011432static inline bool
11433CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11434 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011435 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011436 if (isa<NamespaceDecl>(DC)) {
11437 return SemaRef.Diag(FnDecl->getLocation(),
11438 diag::err_operator_new_delete_declared_in_namespace)
11439 << FnDecl->getDeclName();
11440 }
11441
11442 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011443 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011444 return SemaRef.Diag(FnDecl->getLocation(),
11445 diag::err_operator_new_delete_declared_static)
11446 << FnDecl->getDeclName();
11447 }
11448
Anders Carlsson60659a82009-12-12 02:43:16 +000011449 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011450}
11451
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011452static inline bool
11453CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11454 CanQualType ExpectedResultType,
11455 CanQualType ExpectedFirstParamType,
11456 unsigned DependentParamTypeDiag,
11457 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011458 QualType ResultType =
11459 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011460
11461 // Check that the result type is not dependent.
11462 if (ResultType->isDependentType())
11463 return SemaRef.Diag(FnDecl->getLocation(),
11464 diag::err_operator_new_delete_dependent_result_type)
11465 << FnDecl->getDeclName() << ExpectedResultType;
11466
11467 // Check that the result type is what we expect.
11468 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11469 return SemaRef.Diag(FnDecl->getLocation(),
11470 diag::err_operator_new_delete_invalid_result_type)
11471 << FnDecl->getDeclName() << ExpectedResultType;
11472
11473 // A function template must have at least 2 parameters.
11474 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11475 return SemaRef.Diag(FnDecl->getLocation(),
11476 diag::err_operator_new_delete_template_too_few_parameters)
11477 << FnDecl->getDeclName();
11478
11479 // The function decl must have at least 1 parameter.
11480 if (FnDecl->getNumParams() == 0)
11481 return SemaRef.Diag(FnDecl->getLocation(),
11482 diag::err_operator_new_delete_too_few_parameters)
11483 << FnDecl->getDeclName();
11484
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011485 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011486 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11487 if (FirstParamType->isDependentType())
11488 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11489 << FnDecl->getDeclName() << ExpectedFirstParamType;
11490
11491 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011492 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011493 ExpectedFirstParamType)
11494 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11495 << FnDecl->getDeclName() << ExpectedFirstParamType;
11496
11497 return false;
11498}
11499
Anders Carlsson12308f42009-12-11 23:23:22 +000011500static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011501CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011502 // C++ [basic.stc.dynamic.allocation]p1:
11503 // A program is ill-formed if an allocation function is declared in a
11504 // namespace scope other than global scope or declared static in global
11505 // scope.
11506 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11507 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011508
11509 CanQualType SizeTy =
11510 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11511
11512 // C++ [basic.stc.dynamic.allocation]p1:
11513 // The return type shall be void*. The first parameter shall have type
11514 // std::size_t.
11515 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11516 SizeTy,
11517 diag::err_operator_new_dependent_param_type,
11518 diag::err_operator_new_param_type))
11519 return true;
11520
11521 // C++ [basic.stc.dynamic.allocation]p1:
11522 // The first parameter shall not have an associated default argument.
11523 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011524 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011525 diag::err_operator_new_default_arg)
11526 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11527
11528 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011529}
11530
11531static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011532CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011533 // C++ [basic.stc.dynamic.deallocation]p1:
11534 // A program is ill-formed if deallocation functions are declared in a
11535 // namespace scope other than global scope or declared static in global
11536 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011537 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11538 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011539
11540 // C++ [basic.stc.dynamic.deallocation]p2:
11541 // Each deallocation function shall return void and its first parameter
11542 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011543 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11544 SemaRef.Context.VoidPtrTy,
11545 diag::err_operator_delete_dependent_param_type,
11546 diag::err_operator_delete_param_type))
11547 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011548
Anders Carlsson12308f42009-12-11 23:23:22 +000011549 return false;
11550}
11551
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011552/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11553/// of this overloaded operator is well-formed. If so, returns false;
11554/// otherwise, emits appropriate diagnostics and returns true.
11555bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011556 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011557 "Expected an overloaded operator declaration");
11558
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011559 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11560
Mike Stump11289f42009-09-09 15:08:12 +000011561 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011562 // The allocation and deallocation functions, operator new,
11563 // operator new[], operator delete and operator delete[], are
11564 // described completely in 3.7.3. The attributes and restrictions
11565 // found in the rest of this subclause do not apply to them unless
11566 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011567 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011568 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011569
Anders Carlsson22f443f2009-12-12 00:26:23 +000011570 if (Op == OO_New || Op == OO_Array_New)
11571 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011572
11573 // C++ [over.oper]p6:
11574 // An operator function shall either be a non-static member
11575 // function or be a non-member function and have at least one
11576 // parameter whose type is a class, a reference to a class, an
11577 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011578 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11579 if (MethodDecl->isStatic())
11580 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011581 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011582 } else {
11583 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011584 for (auto Param : FnDecl->params()) {
11585 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011586 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11587 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011588 ClassOrEnumParam = true;
11589 break;
11590 }
11591 }
11592
Douglas Gregord69246b2008-11-17 16:14:12 +000011593 if (!ClassOrEnumParam)
11594 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011595 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011596 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011597 }
11598
11599 // C++ [over.oper]p8:
11600 // An operator function cannot have default arguments (8.3.6),
11601 // except where explicitly stated below.
11602 //
Mike Stump11289f42009-09-09 15:08:12 +000011603 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011604 // (C++ [over.call]p1).
11605 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011606 for (auto Param : FnDecl->params()) {
11607 if (Param->hasDefaultArg())
11608 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011609 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011610 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011611 }
11612 }
11613
Douglas Gregor6cf08062008-11-10 13:38:07 +000011614 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11615 { false, false, false }
11616#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11617 , { Unary, Binary, MemberOnly }
11618#include "clang/Basic/OperatorKinds.def"
11619 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011620
Douglas Gregor6cf08062008-11-10 13:38:07 +000011621 bool CanBeUnaryOperator = OperatorUses[Op][0];
11622 bool CanBeBinaryOperator = OperatorUses[Op][1];
11623 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011624
11625 // C++ [over.oper]p8:
11626 // [...] Operator functions cannot have more or fewer parameters
11627 // than the number required for the corresponding operator, as
11628 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011629 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011630 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011631 if (Op != OO_Call &&
11632 ((NumParams == 1 && !CanBeUnaryOperator) ||
11633 (NumParams == 2 && !CanBeBinaryOperator) ||
11634 (NumParams < 1) || (NumParams > 2))) {
11635 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011636 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011637 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011638 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011639 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011640 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011641 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011642 assert(CanBeBinaryOperator &&
11643 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011644 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011645 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011646
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011647 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011648 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011649 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011650
Douglas Gregord69246b2008-11-17 16:14:12 +000011651 // Overloaded operators other than operator() cannot be variadic.
11652 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011653 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011654 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011655 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011656 }
11657
11658 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011659 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11660 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011661 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011662 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011663 }
11664
11665 // C++ [over.inc]p1:
11666 // The user-defined function called operator++ implements the
11667 // prefix and postfix ++ operator. If this function is a member
11668 // function with no parameters, or a non-member function with one
11669 // parameter of class or enumeration type, it defines the prefix
11670 // increment operator ++ for objects of that type. If the function
11671 // is a member function with one parameter (which shall be of type
11672 // int) or a non-member function with two parameters (the second
11673 // of which shall be of type int), it defines the postfix
11674 // increment operator ++ for objects of that type.
11675 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11676 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011677 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011678
Richard Smith538b52a2014-01-30 22:24:05 +000011679 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11680 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011681 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011682 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011683 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011684 }
11685
Douglas Gregord69246b2008-11-17 16:14:12 +000011686 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011687}
Chris Lattner3b024a32008-12-17 07:09:26 +000011688
Alexis Huntc88db062010-01-13 09:01:02 +000011689/// CheckLiteralOperatorDeclaration - Check whether the declaration
11690/// of this literal operator function is well-formed. If so, returns
11691/// false; otherwise, emits appropriate diagnostics and returns true.
11692bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011693 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011694 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11695 << FnDecl->getDeclName();
11696 return true;
11697 }
11698
Richard Smith72eebee2012-03-04 09:41:16 +000011699 if (FnDecl->isExternC()) {
11700 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11701 return true;
11702 }
11703
Alexis Huntc88db062010-01-13 09:01:02 +000011704 bool Valid = false;
11705
Richard Smithbcc22fc2012-03-09 08:00:36 +000011706 // This might be the definition of a literal operator template.
11707 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11708 // This might be a specialization of a literal operator template.
11709 if (!TpDecl)
11710 TpDecl = FnDecl->getPrimaryTemplate();
11711
Richard Smithb8b41d32013-10-07 19:57:58 +000011712 // template <char...> type operator "" name() and
11713 // template <class T, T...> type operator "" name() are the only valid
11714 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011715 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011716 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011717 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011718 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11719 if (Params->size() == 1) {
11720 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011721 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011722
Alexis Hunt7dd26172010-04-07 23:11:06 +000011723 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011724 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11725 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11726 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011727 } else if (Params->size() == 2) {
11728 TemplateTypeParmDecl *PmType =
11729 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11730 NonTypeTemplateParmDecl *PmArgs =
11731 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11732
11733 // The second template parameter must be a parameter pack with the
11734 // first template parameter as its type.
11735 if (PmType && PmArgs &&
11736 !PmType->isTemplateParameterPack() &&
11737 PmArgs->isTemplateParameterPack()) {
11738 const TemplateTypeParmType *TArgs =
11739 PmArgs->getType()->getAs<TemplateTypeParmType>();
11740 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11741 TArgs->getIndex() == PmType->getIndex()) {
11742 Valid = true;
11743 if (ActiveTemplateInstantiations.empty())
11744 Diag(FnDecl->getLocation(),
11745 diag::ext_string_literal_operator_template);
11746 }
11747 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011748 }
11749 }
Richard Smith72eebee2012-03-04 09:41:16 +000011750 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011751 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011752 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11753
Richard Smith72eebee2012-03-04 09:41:16 +000011754 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011755
Alexis Hunt079a6f72010-04-07 22:57:35 +000011756 // unsigned long long int, long double, and any character type are allowed
11757 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011758 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11759 Context.hasSameType(T, Context.LongDoubleTy) ||
11760 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011761 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011762 Context.hasSameType(T, Context.Char16Ty) ||
11763 Context.hasSameType(T, Context.Char32Ty)) {
11764 if (++Param == FnDecl->param_end())
11765 Valid = true;
11766 goto FinishedParams;
11767 }
11768
Alexis Hunt079a6f72010-04-07 22:57:35 +000011769 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011770 const PointerType *PT = T->getAs<PointerType>();
11771 if (!PT)
11772 goto FinishedParams;
11773 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011774 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011775 goto FinishedParams;
11776 T = T.getUnqualifiedType();
11777
11778 // Move on to the second parameter;
11779 ++Param;
11780
11781 // If there is no second parameter, the first must be a const char *
11782 if (Param == FnDecl->param_end()) {
11783 if (Context.hasSameType(T, Context.CharTy))
11784 Valid = true;
11785 goto FinishedParams;
11786 }
11787
11788 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11789 // are allowed as the first parameter to a two-parameter function
11790 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011791 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011792 Context.hasSameType(T, Context.Char16Ty) ||
11793 Context.hasSameType(T, Context.Char32Ty)))
11794 goto FinishedParams;
11795
11796 // The second and final parameter must be an std::size_t
11797 T = (*Param)->getType().getUnqualifiedType();
11798 if (Context.hasSameType(T, Context.getSizeType()) &&
11799 ++Param == FnDecl->param_end())
11800 Valid = true;
11801 }
11802
11803 // FIXME: This diagnostic is absolutely terrible.
11804FinishedParams:
11805 if (!Valid) {
11806 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11807 << FnDecl->getDeclName();
11808 return true;
11809 }
11810
Richard Smith768cecc2012-03-09 08:16:22 +000011811 // A parameter-declaration-clause containing a default argument is not
11812 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011813 for (auto Param : FnDecl->params()) {
11814 if (Param->hasDefaultArg()) {
11815 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011816 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011817 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011818 break;
11819 }
11820 }
11821
Richard Smith0df56f42012-03-08 02:39:21 +000011822 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011823 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11824 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011825 // C++11 [usrlit.suffix]p1:
11826 // Literal suffix identifiers that do not start with an underscore
11827 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011828 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11829 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011830 }
Richard Smith0df56f42012-03-08 02:39:21 +000011831
Alexis Huntc88db062010-01-13 09:01:02 +000011832 return false;
11833}
11834
Douglas Gregor07665a62009-01-05 19:45:36 +000011835/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11836/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011837/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11838/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011839/// the '{' brace. Otherwise, this linkage specification does not
11840/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011841Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011842 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011843 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011844 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11845 if (!Lit->isAscii()) {
11846 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11847 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011848 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011849 }
11850
11851 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011852 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011853 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011854 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011855 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011856 Language = LinkageSpecDecl::lang_cxx;
11857 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011858 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11859 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011860 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011861 }
Mike Stump11289f42009-09-09 15:08:12 +000011862
Chris Lattner438e5012008-12-17 07:13:27 +000011863 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011864
Richard Smith4ee696d2014-02-17 23:25:27 +000011865 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11866 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011867 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011868 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011869 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011870 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011871}
11872
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011873/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011874/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11875/// valid, it's the position of the closing '}' brace in a linkage
11876/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011877Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011878 Decl *LinkageSpec,
11879 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011880 if (RBraceLoc.isValid()) {
11881 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11882 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011883 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011884 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011885 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011886}
11887
Michael Han84324352013-02-22 17:15:32 +000011888Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11889 AttributeList *AttrList,
11890 SourceLocation SemiLoc) {
11891 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11892 // Attribute declarations appertain to empty declaration so we handle
11893 // them here.
11894 if (AttrList)
11895 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011896
Michael Han84324352013-02-22 17:15:32 +000011897 CurContext->addDecl(ED);
11898 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011899}
11900
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011901/// \brief Perform semantic analysis for the variable declaration that
11902/// occurs within a C++ catch clause, returning the newly-created
11903/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011904VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011905 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011906 SourceLocation StartLoc,
11907 SourceLocation Loc,
11908 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011909 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011910 QualType ExDeclType = TInfo->getType();
11911
Sebastian Redl54c04d42008-12-22 19:15:10 +000011912 // Arrays and functions decay.
11913 if (ExDeclType->isArrayType())
11914 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11915 else if (ExDeclType->isFunctionType())
11916 ExDeclType = Context.getPointerType(ExDeclType);
11917
11918 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11919 // The exception-declaration shall not denote a pointer or reference to an
11920 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011921 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011922 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011923 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011924 Invalid = true;
11925 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011926
Sebastian Redl54c04d42008-12-22 19:15:10 +000011927 QualType BaseType = ExDeclType;
11928 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011929 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011930 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011931 BaseType = Ptr->getPointeeType();
11932 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011933 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011934 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011935 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011936 BaseType = Ref->getPointeeType();
11937 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011938 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011939 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011940 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011941 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011942 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011943
Mike Stump11289f42009-09-09 15:08:12 +000011944 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011945 RequireNonAbstractType(Loc, ExDeclType,
11946 diag::err_abstract_type_in_decl,
11947 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011948 Invalid = true;
11949
John McCall2ca705e2010-07-24 00:37:23 +000011950 // Only the non-fragile NeXT runtime currently supports C++ catches
11951 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011952 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011953 QualType T = ExDeclType;
11954 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11955 T = RT->getPointeeType();
11956
11957 if (T->isObjCObjectType()) {
11958 Diag(Loc, diag::err_objc_object_catch);
11959 Invalid = true;
11960 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011961 // FIXME: should this be a test for macosx-fragile specifically?
11962 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011963 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011964 }
11965 }
11966
Abramo Bagnaradff19302011-03-08 08:55:46 +000011967 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011968 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011969 ExDecl->setExceptionVariable(true);
11970
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011971 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011972 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011973 Invalid = true;
11974
Douglas Gregor750734c2011-07-06 18:14:43 +000011975 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011976 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011977 // Insulate this from anything else we might currently be parsing.
11978 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11979
Douglas Gregor6de584c2010-03-05 23:38:39 +000011980 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011981 // The object declared in an exception-declaration or, if the
11982 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011983 // copy-initialized (8.5) from the exception object. [...]
11984 // The object is destroyed when the handler exits, after the destruction
11985 // of any automatic objects initialized within the handler.
11986 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011987 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011988 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000011989 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000011990
11991 InitializedEntity entity =
11992 InitializedEntity::InitializeVariable(ExDecl);
11993 InitializationKind initKind =
11994 InitializationKind::CreateCopy(Loc, SourceLocation());
11995
11996 Expr *opaqueValue =
11997 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011998 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11999 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000012000 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000012001 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000012002 else {
12003 // If the constructor used was non-trivial, set this as the
12004 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012005 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000012006 if (!construct->getConstructor()->isTrivial()) {
12007 Expr *init = MaybeCreateExprWithCleanups(construct);
12008 ExDecl->setInit(init);
12009 }
12010
12011 // And make sure it's destructable.
12012 FinalizeVarWithDestructor(ExDecl, recordType);
12013 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000012014 }
12015 }
12016
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012017 if (Invalid)
12018 ExDecl->setInvalidDecl();
12019
12020 return ExDecl;
12021}
12022
12023/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12024/// handler.
John McCall48871652010-08-21 09:40:31 +000012025Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000012026 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000012027 bool Invalid = D.isInvalidType();
12028
12029 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000012030 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12031 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000012032 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12033 D.getIdentifierLoc());
12034 Invalid = true;
12035 }
12036
Sebastian Redl54c04d42008-12-22 19:15:10 +000012037 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012038 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000012039 LookupOrdinaryName,
12040 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012041 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012042 // it contains any previous declaration, except for function parameters in
12043 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012044 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012045 if (isDeclInScope(PrevDecl, CurContext, S)) {
12046 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12047 << D.getIdentifier();
12048 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12049 Invalid = true;
12050 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012051 // Maybe we will complain about the shadowed template parameter.
12052 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012053 }
12054
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012055 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012056 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12057 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012058 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012059 }
12060
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012061 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012062 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012063 D.getIdentifierLoc(),
12064 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012065 if (Invalid)
12066 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012067
Sebastian Redl54c04d42008-12-22 19:15:10 +000012068 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012069 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012070 PushOnScopeChains(ExDecl, S);
12071 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012072 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012073
Douglas Gregor758a8692009-06-17 21:51:59 +000012074 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012075 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012076}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012077
Abramo Bagnaraea947882011-03-08 16:41:52 +000012078Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012079 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012080 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012081 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012082 StringLiteral *AssertMessage =
12083 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012084
Richard Smithded9c2e2012-07-11 22:37:56 +000012085 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012086 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012087
12088 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12089 AssertMessage, RParenLoc, false);
12090}
12091
12092Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12093 Expr *AssertExpr,
12094 StringLiteral *AssertMessage,
12095 SourceLocation RParenLoc,
12096 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012097 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012098 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12099 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012100 // In a static_assert-declaration, the constant-expression shall be a
12101 // constant expression that can be contextually converted to bool.
12102 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12103 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012104 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012105
Richard Smith902ca212011-12-14 23:32:26 +000012106 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012107 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012108 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012109 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012110 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012111
Richard Smithded9c2e2012-07-11 22:37:56 +000012112 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012113 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012114 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012115 if (AssertMessage)
12116 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012117 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012118 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012119 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012120 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012121 }
Mike Stump11289f42009-09-09 15:08:12 +000012122
Abramo Bagnaraea947882011-03-08 16:41:52 +000012123 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012124 AssertExpr, AssertMessage, RParenLoc,
12125 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012126
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012127 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012128 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012129}
Sebastian Redlf769df52009-03-24 22:27:57 +000012130
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012131/// \brief Perform semantic analysis of the given friend type declaration.
12132///
12133/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012134FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012135 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012136 TypeSourceInfo *TSInfo) {
12137 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12138
12139 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012140 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012141
Richard Smithc8239732011-10-18 21:39:00 +000012142 // C++03 [class.friend]p2:
12143 // An elaborated-type-specifier shall be used in a friend declaration
12144 // for a class.*
12145 //
12146 // * The class-key of the elaborated-type-specifier is required.
12147 if (!ActiveTemplateInstantiations.empty()) {
12148 // Do not complain about the form of friend template types during
12149 // template instantiation; we will already have complained when the
12150 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012151 } else {
12152 if (!T->isElaboratedTypeSpecifier()) {
12153 // If we evaluated the type to a record type, suggest putting
12154 // a tag in front.
12155 if (const RecordType *RT = T->getAs<RecordType>()) {
12156 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012157
12158 SmallString<16> InsertionText(" ");
12159 InsertionText += RD->getKindName();
12160
Nick Lewycky36722d22013-02-06 05:59:33 +000012161 Diag(TypeRange.getBegin(),
12162 getLangOpts().CPlusPlus11 ?
12163 diag::warn_cxx98_compat_unelaborated_friend_type :
12164 diag::ext_unelaborated_friend_type)
12165 << (unsigned) RD->getTagKind()
12166 << T
12167 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12168 InsertionText);
12169 } else {
12170 Diag(FriendLoc,
12171 getLangOpts().CPlusPlus11 ?
12172 diag::warn_cxx98_compat_nonclass_type_friend :
12173 diag::ext_nonclass_type_friend)
12174 << T
12175 << TypeRange;
12176 }
12177 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012178 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012179 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012180 diag::warn_cxx98_compat_enum_friend :
12181 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012182 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012183 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012184 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012185
Nick Lewycky36722d22013-02-06 05:59:33 +000012186 // C++11 [class.friend]p3:
12187 // A friend declaration that does not declare a function shall have one
12188 // of the following forms:
12189 // friend elaborated-type-specifier ;
12190 // friend simple-type-specifier ;
12191 // friend typename-specifier ;
12192 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12193 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12194 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012195
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012196 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012197 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012198 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012199 return FriendDecl::Create(Context, CurContext,
12200 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12201 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012202}
12203
John McCallace48cd2010-10-19 01:40:49 +000012204/// Handle a friend tag declaration where the scope specifier was
12205/// templated.
12206Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12207 unsigned TagSpec, SourceLocation TagLoc,
12208 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012209 IdentifierInfo *Name,
12210 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012211 AttributeList *Attr,
12212 MultiTemplateParamsArg TempParamLists) {
12213 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12214
12215 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012216 bool Invalid = false;
12217
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012218 if (TemplateParameterList *TemplateParams =
12219 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012220 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012221 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012222 if (TemplateParams->size() > 0) {
12223 // This is a declaration of a class template.
12224 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012225 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012226
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012227 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12228 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012229 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012230 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012231 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012232 } else {
12233 // The "template<>" header is extraneous.
12234 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12235 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12236 isExplicitSpecialization = true;
12237 }
12238 }
12239
Craig Topperc3ec1492014-05-26 06:22:03 +000012240 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012241
John McCallace48cd2010-10-19 01:40:49 +000012242 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012243 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012244 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012245 isAllExplicitSpecializations = false;
12246 break;
12247 }
12248 }
12249
12250 // FIXME: don't ignore attributes.
12251
12252 // If it's explicit specializations all the way down, just forget
12253 // about the template header and build an appropriate non-templated
12254 // friend. TODO: for source fidelity, remember the headers.
12255 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012256 if (SS.isEmpty()) {
12257 bool Owned = false;
12258 bool IsDependent = false;
12259 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012260 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012261 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012262 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012263 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012264 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012265 /*UnderlyingType=*/TypeResult(),
12266 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012267 }
Richard Smith649c7b062014-01-08 00:56:48 +000012268
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012269 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012270 ElaboratedTypeKeyword Keyword
12271 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012272 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012273 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012274 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012275 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012276
12277 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12278 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012279 DependentNameTypeLoc TL =
12280 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012281 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012282 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012283 TL.setNameLoc(NameLoc);
12284 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012285 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012286 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012287 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012288 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012289 }
12290
12291 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012292 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012293 Friend->setAccess(AS_public);
12294 CurContext->addDecl(Friend);
12295 return Friend;
12296 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012297
12298 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12299
12300
John McCallace48cd2010-10-19 01:40:49 +000012301
12302 // Handle the case of a templated-scope friend class. e.g.
12303 // template <class T> class A<T>::B;
12304 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012305 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12306 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012307 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12308 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12309 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012310 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012311 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012312 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012313 TL.setNameLoc(NameLoc);
12314
12315 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012316 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012317 Friend->setAccess(AS_public);
12318 Friend->setUnsupportedFriend(true);
12319 CurContext->addDecl(Friend);
12320 return Friend;
12321}
12322
12323
John McCall11083da2009-09-16 22:47:08 +000012324/// Handle a friend type declaration. This works in tandem with
12325/// ActOnTag.
12326///
12327/// Notes on friend class templates:
12328///
12329/// We generally treat friend class declarations as if they were
12330/// declaring a class. So, for example, the elaborated type specifier
12331/// in a friend declaration is required to obey the restrictions of a
12332/// class-head (i.e. no typedefs in the scope chain), template
12333/// parameters are required to match up with simple template-ids, &c.
12334/// However, unlike when declaring a template specialization, it's
12335/// okay to refer to a template specialization without an empty
12336/// template parameter declaration, e.g.
12337/// friend class A<T>::B<unsigned>;
12338/// We permit this as a special case; if there are any template
12339/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012340/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012341Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012342 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012343 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012344
12345 assert(DS.isFriendSpecified());
12346 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12347
John McCall11083da2009-09-16 22:47:08 +000012348 // Try to convert the decl specifier to a type. This works for
12349 // friend templates because ActOnTag never produces a ClassTemplateDecl
12350 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012351 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012352 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12353 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012354 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012355 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012356
Douglas Gregor6c110f32010-12-16 01:14:37 +000012357 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012358 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012359
John McCall11083da2009-09-16 22:47:08 +000012360 // This is definitely an error in C++98. It's probably meant to
12361 // be forbidden in C++0x, too, but the specification is just
12362 // poorly written.
12363 //
12364 // The problem is with declarations like the following:
12365 // template <T> friend A<T>::foo;
12366 // where deciding whether a class C is a friend or not now hinges
12367 // on whether there exists an instantiation of A that causes
12368 // 'foo' to equal C. There are restrictions on class-heads
12369 // (which we declare (by fiat) elaborated friend declarations to
12370 // be) that makes this tractable.
12371 //
12372 // FIXME: handle "template <> friend class A<T>;", which
12373 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012374 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012375 Diag(Loc, diag::err_tagless_friend_type_template)
12376 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012377 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012378 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012379
John McCallaa74a0c2009-08-28 07:59:38 +000012380 // C++98 [class.friend]p1: A friend of a class is a function
12381 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012382 // This is fixed in DR77, which just barely didn't make the C++03
12383 // deadline. It's also a very silly restriction that seriously
12384 // affects inner classes and which nobody else seems to implement;
12385 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012386 //
12387 // But note that we could warn about it: it's always useless to
12388 // friend one of your own members (it's not, however, worthless to
12389 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012390
John McCall11083da2009-09-16 22:47:08 +000012391 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012392 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012393 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012394 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012395 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012396 TSI,
John McCall11083da2009-09-16 22:47:08 +000012397 DS.getFriendSpecLoc());
12398 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012399 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012400
12401 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012402 return nullptr;
12403
John McCall11083da2009-09-16 22:47:08 +000012404 D->setAccess(AS_public);
12405 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012406
John McCall48871652010-08-21 09:40:31 +000012407 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012408}
12409
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012410NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12411 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012412 const DeclSpec &DS = D.getDeclSpec();
12413
12414 assert(DS.isFriendSpecified());
12415 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12416
12417 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012418 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012419
12420 // C++ [class.friend]p1
12421 // A friend of a class is a function or class....
12422 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012423 // It *doesn't* see through dependent types, which is correct
12424 // according to [temp.arg.type]p3:
12425 // If a declaration acquires a function type through a
12426 // type dependent on a template-parameter and this causes
12427 // a declaration that does not use the syntactic form of a
12428 // function declarator to have a function type, the program
12429 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012430 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012431 Diag(Loc, diag::err_unexpected_friend);
12432
12433 // It might be worthwhile to try to recover by creating an
12434 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012435 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012436 }
12437
12438 // C++ [namespace.memdef]p3
12439 // - If a friend declaration in a non-local class first declares a
12440 // class or function, the friend class or function is a member
12441 // of the innermost enclosing namespace.
12442 // - The name of the friend is not found by simple name lookup
12443 // until a matching declaration is provided in that namespace
12444 // scope (either before or after the class declaration granting
12445 // friendship).
12446 // - If a friend function is called, its name may be found by the
12447 // name lookup that considers functions from namespaces and
12448 // classes associated with the types of the function arguments.
12449 // - When looking for a prior declaration of a class or a function
12450 // declared as a friend, scopes outside the innermost enclosing
12451 // namespace scope are not considered.
12452
John McCallde3fd222010-10-12 23:13:28 +000012453 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012454 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12455 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012456 assert(Name);
12457
Douglas Gregor6c110f32010-12-16 01:14:37 +000012458 // Check for unexpanded parameter packs.
12459 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12460 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12461 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012462 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012463
John McCall07e91c02009-08-06 02:15:43 +000012464 // The context we found the declaration in, or in which we should
12465 // create the declaration.
12466 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012467 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012468 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012469 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012470
Richard Smith114394f2013-08-09 04:35:01 +000012471 // There are five cases here.
12472 // - There's no scope specifier and we're in a local class. Only look
12473 // for functions declared in the immediately-enclosing block scope.
12474 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012475 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012476 if ((SS.isInvalid() || !SS.isSet()) &&
12477 (FunctionContainingLocalClass =
12478 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12479 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012480 // If a friend declaration appears in a local class and the name
12481 // specified is an unqualified name, a prior declaration is
12482 // looked up without considering scopes that are outside the
12483 // innermost enclosing non-class scope. For a friend function
12484 // declaration, if there is no prior declaration, the program is
12485 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012486
12487 // Find the innermost enclosing non-class scope. This is the block
12488 // scope containing the local class definition (or for a nested class,
12489 // the outer local class).
12490 DCScope = S->getFnParent();
12491
12492 // Look up the function name in the scope.
12493 Previous.clear(LookupLocalFriendName);
12494 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12495
12496 if (!Previous.empty()) {
12497 // All possible previous declarations must have the same context:
12498 // either they were declared at block scope or they are members of
12499 // one of the enclosing local classes.
12500 DC = Previous.getRepresentativeDecl()->getDeclContext();
12501 } else {
12502 // This is ill-formed, but provide the context that we would have
12503 // declared the function in, if we were permitted to, for error recovery.
12504 DC = FunctionContainingLocalClass;
12505 }
Richard Smith541b38b2013-09-20 01:15:31 +000012506 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012507
12508 // C++ [class.friend]p6:
12509 // A function can be defined in a friend declaration of a class if and
12510 // only if the class is a non-local class (9.8), the function name is
12511 // unqualified, and the function has namespace scope.
12512 if (D.isFunctionDefinition()) {
12513 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12514 }
12515
12516 // - There's no scope specifier, in which case we just go to the
12517 // appropriate scope and look for a function or function template
12518 // there as appropriate.
12519 } else if (SS.isInvalid() || !SS.isSet()) {
12520 // C++11 [namespace.memdef]p3:
12521 // If the name in a friend declaration is neither qualified nor
12522 // a template-id and the declaration is a function or an
12523 // elaborated-type-specifier, the lookup to determine whether
12524 // the entity has been previously declared shall not consider
12525 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012526 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012527
John McCallf7cfb222010-10-13 05:45:15 +000012528 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012529 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012530
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012531 // Skip class contexts. If someone can cite chapter and verse
12532 // for this behavior, that would be nice --- it's what GCC and
12533 // EDG do, and it seems like a reasonable intent, but the spec
12534 // really only says that checks for unqualified existing
12535 // declarations should stop at the nearest enclosing namespace,
12536 // not that they should only consider the nearest enclosing
12537 // namespace.
12538 while (DC->isRecord())
12539 DC = DC->getParent();
12540
12541 DeclContext *LookupDC = DC;
12542 while (LookupDC->isTransparentContext())
12543 LookupDC = LookupDC->getParent();
12544
12545 while (true) {
12546 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012547
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012548 if (!Previous.empty()) {
12549 DC = LookupDC;
12550 break;
John McCallf4776592010-10-14 22:22:28 +000012551 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012552
12553 if (isTemplateId) {
12554 if (isa<TranslationUnitDecl>(LookupDC)) break;
12555 } else {
12556 if (LookupDC->isFileContext()) break;
12557 }
12558 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012559 }
12560
John McCallccbc0322010-10-13 06:22:15 +000012561 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012562
John McCallde3fd222010-10-12 23:13:28 +000012563 // - There's a non-dependent scope specifier, in which case we
12564 // compute it and do a previous lookup there for a function
12565 // or function template.
12566 } else if (!SS.getScopeRep()->isDependent()) {
12567 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012568 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012569
Craig Topperc3ec1492014-05-26 06:22:03 +000012570 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012571
12572 LookupQualifiedName(Previous, DC);
12573
12574 // Ignore things found implicitly in the wrong scope.
12575 // TODO: better diagnostics for this case. Suggesting the right
12576 // qualified scope would be nice...
12577 LookupResult::Filter F = Previous.makeFilter();
12578 while (F.hasNext()) {
12579 NamedDecl *D = F.next();
12580 if (!DC->InEnclosingNamespaceSetOf(
12581 D->getDeclContext()->getRedeclContext()))
12582 F.erase();
12583 }
12584 F.done();
12585
12586 if (Previous.empty()) {
12587 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012588 Diag(Loc, diag::err_qualified_friend_not_found)
12589 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012590 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012591 }
12592
12593 // C++ [class.friend]p1: A friend of a class is a function or
12594 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012595 if (DC->Equals(CurContext))
12596 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012597 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012598 diag::warn_cxx98_compat_friend_is_member :
12599 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012600
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012601 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012602 // C++ [class.friend]p6:
12603 // A function can be defined in a friend declaration of a class if and
12604 // only if the class is a non-local class (9.8), the function name is
12605 // unqualified, and the function has namespace scope.
12606 SemaDiagnosticBuilder DB
12607 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12608
12609 DB << SS.getScopeRep();
12610 if (DC->isFileContext())
12611 DB << FixItHint::CreateRemoval(SS.getRange());
12612 SS.clear();
12613 }
John McCallde3fd222010-10-12 23:13:28 +000012614
12615 // - There's a scope specifier that does not match any template
12616 // parameter lists, in which case we use some arbitrary context,
12617 // create a method or method template, and wait for instantiation.
12618 // - There's a scope specifier that does match some template
12619 // parameter lists, which we don't handle right now.
12620 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012621 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012622 // C++ [class.friend]p6:
12623 // A function can be defined in a friend declaration of a class if and
12624 // only if the class is a non-local class (9.8), the function name is
12625 // unqualified, and the function has namespace scope.
12626 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12627 << SS.getScopeRep();
12628 }
12629
John McCallde3fd222010-10-12 23:13:28 +000012630 DC = CurContext;
12631 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012632 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012633
John McCallf7cfb222010-10-13 05:45:15 +000012634 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012635 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012636 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12637 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12638 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012639 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012640 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12641 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012642 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012643 }
John McCall07e91c02009-08-06 02:15:43 +000012644 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012645
Douglas Gregordd847ba2011-11-03 16:37:14 +000012646 // FIXME: This is an egregious hack to cope with cases where the scope stack
12647 // does not contain the declaration context, i.e., in an out-of-line
12648 // definition of a class.
12649 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12650 if (!DCScope) {
12651 FakeDCScope.setEntity(DC);
12652 DCScope = &FakeDCScope;
12653 }
Richard Smith114394f2013-08-09 04:35:01 +000012654
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012655 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012656 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012657 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012658 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012659
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012660 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012661
Richard Smith114394f2013-08-09 04:35:01 +000012662 // If we performed typo correction, we might have added a scope specifier
12663 // and changed the decl context.
12664 DC = ND->getDeclContext();
12665
John McCall759e32b2009-08-31 22:39:49 +000012666 // Add the function declaration to the appropriate lookup tables,
12667 // adjusting the redeclarations list as necessary. We don't
12668 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012669 //
John McCall759e32b2009-08-31 22:39:49 +000012670 // Also update the scope-based lookup if the target context's
12671 // lookup context is in lexical scope.
12672 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012673 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012674 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012675 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012676 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012677 }
John McCallaa74a0c2009-08-28 07:59:38 +000012678
12679 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012680 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012681 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012682 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012683 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012684
John McCalla0a96892012-08-10 03:15:35 +000012685 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012686 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012687 } else {
12688 if (DC->isRecord()) CheckFriendAccess(ND);
12689
John McCall2c2eb122010-10-16 06:59:13 +000012690 FunctionDecl *FD;
12691 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12692 FD = FTD->getTemplatedDecl();
12693 else
12694 FD = cast<FunctionDecl>(ND);
12695
David Majnemer502b0ed2013-06-25 23:09:30 +000012696 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12697 // default argument expression, that declaration shall be a definition
12698 // and shall be the only declaration of the function or function
12699 // template in the translation unit.
12700 if (functionDeclHasDefaultArgument(FD)) {
12701 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12702 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12703 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12704 } else if (!D.isFunctionDefinition())
12705 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12706 }
12707
John McCall2c2eb122010-10-16 06:59:13 +000012708 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012709 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12710 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12711 << SS.getScopeRep() << SS.getRange()
12712 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012713 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012714 }
John McCall2c2eb122010-10-16 06:59:13 +000012715 }
John McCallde3fd222010-10-12 23:13:28 +000012716
John McCall48871652010-08-21 09:40:31 +000012717 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012718}
12719
John McCall48871652010-08-21 09:40:31 +000012720void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12721 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012722
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012723 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012724 if (!Fn) {
12725 Diag(DelLoc, diag::err_deleted_non_function);
12726 return;
12727 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012728
Douglas Gregorec9fd132012-01-14 16:38:05 +000012729 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012730 // Don't consider the implicit declaration we generate for explicit
12731 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012732 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12733 Prev->getPreviousDecl()) &&
12734 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012735 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012736 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12737 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12738 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012739 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012740 // If the declaration wasn't the first, we delete the function anyway for
12741 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012742 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012743 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012744
Nico Rieck9de0a572014-05-29 16:51:19 +000012745 // dllimport/dllexport cannot be deleted.
12746 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12747 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12748 Fn->setInvalidDecl();
12749 }
12750
Richard Smithb4d2a152013-04-02 19:38:47 +000012751 if (Fn->isDeleted())
12752 return;
12753
12754 // See if we're deleting a function which is already known to override a
12755 // non-deleted virtual function.
12756 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12757 bool IssuedDiagnostic = false;
12758 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12759 E = MD->end_overridden_methods();
12760 I != E; ++I) {
12761 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12762 if (!IssuedDiagnostic) {
12763 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12764 IssuedDiagnostic = true;
12765 }
12766 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12767 }
12768 }
12769 }
12770
Richard Smithb63b6ee2014-01-22 01:43:19 +000012771 // C++11 [basic.start.main]p3:
12772 // A program that defines main as deleted [...] is ill-formed.
12773 if (Fn->isMain())
12774 Diag(DelLoc, diag::err_deleted_main);
12775
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012776 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012777}
Sebastian Redl4c018662009-04-27 21:33:24 +000012778
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012779void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012780 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012781
12782 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012783 if (MD->getParent()->isDependentType()) {
12784 MD->setDefaulted();
12785 MD->setExplicitlyDefaulted();
12786 return;
12787 }
12788
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012789 CXXSpecialMember Member = getSpecialMember(MD);
12790 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012791 if (!MD->isInvalidDecl())
12792 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012793 return;
12794 }
12795
12796 MD->setDefaulted();
12797 MD->setExplicitlyDefaulted();
12798
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012799 // If this definition appears within the record, do the checking when
12800 // the record is complete.
12801 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012802 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012803 // Find the uninstantiated declaration that actually had the '= default'
12804 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012805 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012806
Richard Smith3901dfe2013-03-27 00:22:47 +000012807 // If the method was defaulted on its first declaration, we will have
12808 // already performed the checking in CheckCompletedCXXClass. Such a
12809 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012810 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012811 return;
12812
Richard Smithd3b5c9082012-07-27 04:22:15 +000012813 CheckExplicitlyDefaultedSpecialMember(MD);
12814
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012815 if (MD->isInvalidDecl())
12816 return;
12817
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012818 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012819 case CXXDefaultConstructor:
12820 DefineImplicitDefaultConstructor(DefaultLoc,
12821 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012822 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012823 case CXXCopyConstructor:
12824 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012825 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012826 case CXXCopyAssignment:
12827 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012828 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012829 case CXXDestructor:
12830 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012831 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012832 case CXXMoveConstructor:
12833 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012834 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012835 case CXXMoveAssignment:
12836 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012837 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012838 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012839 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012840 }
12841 } else {
12842 Diag(DefaultLoc, diag::err_default_special_members);
12843 }
12844}
12845
Sebastian Redl4c018662009-04-27 21:33:24 +000012846static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012847 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012848 Stmt *SubStmt = *CI;
12849 if (!SubStmt)
12850 continue;
12851 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012852 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012853 diag::err_return_in_constructor_handler);
12854 if (!isa<Expr>(SubStmt))
12855 SearchForReturnInStmt(Self, SubStmt);
12856 }
12857}
12858
12859void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12860 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12861 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12862 SearchForReturnInStmt(*this, Handler);
12863 }
12864}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012865
David Blaikie68f71a32013-01-18 23:03:15 +000012866bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012867 const CXXMethodDecl *Old) {
12868 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12869 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12870
12871 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12872
12873 // If the calling conventions match, everything is fine
12874 if (NewCC == OldCC)
12875 return false;
12876
Hans Wennborg2545efe2013-12-11 17:42:11 +000012877 // If the calling conventions mismatch because the new function is static,
12878 // suppress the calling convention mismatch error; the error about static
12879 // function override (err_static_overrides_virtual from
12880 // Sema::CheckFunctionDeclaration) is more clear.
12881 if (New->getStorageClass() == SC_Static)
12882 return false;
12883
Reid Kleckner78af0702013-08-27 23:08:25 +000012884 Diag(New->getLocation(),
12885 diag::err_conflicting_overriding_cc_attributes)
12886 << New->getDeclName() << New->getType() << Old->getType();
12887 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12888 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012889}
12890
Mike Stump11289f42009-09-09 15:08:12 +000012891bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012892 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012893 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12894 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012895
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012896 if (Context.hasSameType(NewTy, OldTy) ||
12897 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012898 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012899
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012900 // Check if the return types are covariant
12901 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012902
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012903 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012904 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12905 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012906 NewClassTy = NewPT->getPointeeType();
12907 OldClassTy = OldPT->getPointeeType();
12908 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012909 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12910 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12911 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12912 NewClassTy = NewRT->getPointeeType();
12913 OldClassTy = OldRT->getPointeeType();
12914 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012915 }
12916 }
Mike Stump11289f42009-09-09 15:08:12 +000012917
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012918 // The return types aren't either both pointers or references to a class type.
12919 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012920 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012921 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012922 << New->getDeclName() << NewTy << OldTy
12923 << New->getReturnTypeSourceRange();
12924 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12925 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012926
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012927 return true;
12928 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012929
Anders Carlssone60365b2009-12-31 18:34:24 +000012930 // C++ [class.virtual]p6:
12931 // If the return type of D::f differs from the return type of B::f, the
12932 // class type in the return type of D::f shall be complete at the point of
12933 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012934 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12935 if (!RT->isBeingDefined() &&
12936 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012937 diag::err_covariant_return_incomplete,
12938 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012939 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012940 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012941
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012942 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012943 // Check if the new class derives from the old class.
12944 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012945 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12946 << New->getDeclName() << NewTy << OldTy
12947 << New->getReturnTypeSourceRange();
12948 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12949 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012950 return true;
12951 }
Mike Stump11289f42009-09-09 15:08:12 +000012952
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012953 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012954 if (CheckDerivedToBaseConversion(
12955 NewClassTy, OldClassTy,
12956 diag::err_covariant_return_inaccessible_base,
12957 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12958 New->getLocation(), New->getReturnTypeSourceRange(),
12959 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012960 // FIXME: this note won't trigger for delayed access control
12961 // diagnostics, and it's impossible to get an undelayed error
12962 // here from access control during the original parse because
12963 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012964 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12965 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012966 return true;
12967 }
12968 }
Mike Stump11289f42009-09-09 15:08:12 +000012969
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012970 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012971 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012972 Diag(New->getLocation(),
12973 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012974 << New->getDeclName() << NewTy << OldTy
12975 << New->getReturnTypeSourceRange();
12976 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12977 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012978 return true;
12979 };
Mike Stump11289f42009-09-09 15:08:12 +000012980
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012981
12982 // The new class type must have the same or less qualifiers as the old type.
12983 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12984 Diag(New->getLocation(),
12985 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012986 << New->getDeclName() << NewTy << OldTy
12987 << New->getReturnTypeSourceRange();
12988 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12989 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012990 return true;
12991 };
Mike Stump11289f42009-09-09 15:08:12 +000012992
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012993 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012994}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012995
Douglas Gregor21920e372009-12-01 17:24:26 +000012996/// \brief Mark the given method pure.
12997///
12998/// \param Method the method to be marked pure.
12999///
13000/// \param InitRange the source range that covers the "0" initializer.
13001bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013002 SourceLocation EndLoc = InitRange.getEnd();
13003 if (EndLoc.isValid())
13004 Method->setRangeEnd(EndLoc);
13005
Douglas Gregor21920e372009-12-01 17:24:26 +000013006 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13007 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000013008 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013009 }
Douglas Gregor21920e372009-12-01 17:24:26 +000013010
13011 if (!Method->isInvalidDecl())
13012 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13013 << Method->getDeclName() << InitRange;
13014 return true;
13015}
13016
Douglas Gregor926410d2012-02-21 02:22:07 +000013017/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013018static bool isStaticDataMember(const Decl *D) {
13019 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13020 return Var->isStaticDataMember();
13021
13022 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000013023}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013024
John McCall1f4ee7b2009-12-19 09:28:58 +000013025/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13026/// an initializer for the out-of-line declaration 'Dcl'. The scope
13027/// is a fresh scope pushed for just this purpose.
13028///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013029/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13030/// static data member of class X, names should be looked up in the scope of
13031/// class X.
John McCall48871652010-08-21 09:40:31 +000013032void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013033 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013034 if (!D || D->isInvalidDecl())
13035 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013036
Richard Smitha2302242013-12-05 07:51:02 +000013037 // We will always have a nested name specifier here, but this declaration
13038 // might not be out of line if the specifier names the current namespace:
13039 // extern int n;
13040 // int ::n = 0;
13041 if (D->isOutOfLine())
13042 EnterDeclaratorContext(S, D->getDeclContext());
13043
Douglas Gregor926410d2012-02-21 02:22:07 +000013044 // If we are parsing the initializer for a static data member, push a
13045 // new expression evaluation context that is associated with this static
13046 // data member.
13047 if (isStaticDataMember(D))
13048 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013049}
13050
13051/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013052/// initializer for the out-of-line declaration 'D'.
13053void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013054 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013055 if (!D || D->isInvalidDecl())
13056 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013057
Douglas Gregor926410d2012-02-21 02:22:07 +000013058 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013059 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013060
Richard Smitha2302242013-12-05 07:51:02 +000013061 if (D->isOutOfLine())
13062 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013063}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013064
13065/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13066/// C++ if/switch/while/for statement.
13067/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013068DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013069 // C++ 6.4p2:
13070 // The declarator shall not specify a function or an array.
13071 // The type-specifier-seq shall not contain typedef and shall not declare a
13072 // new class or enumeration.
13073 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13074 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013075
13076 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013077 if (!Dcl)
13078 return true;
13079
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013080 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13081 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013082 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013083 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013084 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013085
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013086 return Dcl;
13087}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013088
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013089void Sema::LoadExternalVTableUses() {
13090 if (!ExternalSource)
13091 return;
13092
13093 SmallVector<ExternalVTableUse, 4> VTables;
13094 ExternalSource->ReadUsedVTables(VTables);
13095 SmallVector<VTableUse, 4> NewUses;
13096 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13097 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13098 = VTablesUsed.find(VTables[I].Record);
13099 // Even if a definition wasn't required before, it may be required now.
13100 if (Pos != VTablesUsed.end()) {
13101 if (!Pos->second && VTables[I].DefinitionRequired)
13102 Pos->second = true;
13103 continue;
13104 }
13105
13106 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13107 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13108 }
13109
13110 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13111}
13112
Douglas Gregor88d292c2010-05-13 16:44:06 +000013113void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13114 bool DefinitionRequired) {
13115 // Ignore any vtable uses in unevaluated operands or for classes that do
13116 // not have a vtable.
13117 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013118 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013119 return;
13120
Douglas Gregor88d292c2010-05-13 16:44:06 +000013121 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013122 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013123 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13124 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13125 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13126 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013127 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013128 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013129 // list, since we may have already processed the first entry.
13130 if (DefinitionRequired && !Pos.first->second) {
13131 Pos.first->second = true;
13132 } else {
13133 // Otherwise, we can early exit.
13134 return;
13135 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013136 } else {
13137 // The Microsoft ABI requires that we perform the destructor body
13138 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13139 // the deleting destructor is emitted with the vtable, not with the
13140 // destructor definition as in the Itanium ABI.
13141 // If it has a definition, we do the check at that point instead.
13142 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13143 Class->hasUserDeclaredDestructor() &&
13144 !Class->getDestructor()->isDefined() &&
13145 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013146 CXXDestructorDecl *DD = Class->getDestructor();
13147 ContextRAII SavedContext(*this, DD);
13148 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013149 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013150 }
13151
13152 // Local classes need to have their virtual members marked
13153 // immediately. For all other classes, we mark their virtual members
13154 // at the end of the translation unit.
13155 if (Class->isLocalClass())
13156 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013157 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013158 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013159}
13160
Douglas Gregor88d292c2010-05-13 16:44:06 +000013161bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013162 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013163 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013164 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013165
Douglas Gregor88d292c2010-05-13 16:44:06 +000013166 // Note: The VTableUses vector could grow as a result of marking
13167 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013168 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013169 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013170 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013171 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013172 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013173 if (!Class)
13174 continue;
13175
13176 SourceLocation Loc = VTableUses[I].second;
13177
Richard Smithd3b5c9082012-07-27 04:22:15 +000013178 bool DefineVTable = true;
13179
Douglas Gregor88d292c2010-05-13 16:44:06 +000013180 // If this class has a key function, but that key function is
13181 // defined in another translation unit, we don't need to emit the
13182 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013183 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013184 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013185 // The key function is in another translation unit.
13186 DefineVTable = false;
13187 TemplateSpecializationKind TSK =
13188 KeyFunction->getTemplateSpecializationKind();
13189 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13190 TSK != TSK_ImplicitInstantiation &&
13191 "Instantiations don't have key functions");
13192 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013193 } else if (!KeyFunction) {
13194 // If we have a class with no key function that is the subject
13195 // of an explicit instantiation declaration, suppress the
13196 // vtable; it will live with the explicit instantiation
13197 // definition.
13198 bool IsExplicitInstantiationDeclaration
13199 = Class->getTemplateSpecializationKind()
13200 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013201 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013202 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013203 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013204 if (TSK == TSK_ExplicitInstantiationDeclaration)
13205 IsExplicitInstantiationDeclaration = true;
13206 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13207 IsExplicitInstantiationDeclaration = false;
13208 break;
13209 }
13210 }
13211
13212 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013213 DefineVTable = false;
13214 }
13215
13216 // The exception specifications for all virtual members may be needed even
13217 // if we are not providing an authoritative form of the vtable in this TU.
13218 // We may choose to emit it available_externally anyway.
13219 if (!DefineVTable) {
13220 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13221 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013222 }
13223
13224 // Mark all of the virtual members of this class as referenced, so
13225 // that we can build a vtable. Then, tell the AST consumer that a
13226 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013227 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013228 MarkVirtualMembersReferenced(Loc, Class);
13229 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013230 if (VTablesUsed[Canonical])
13231 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013232
13233 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013234 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013235 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013236 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013237 if (!KeyFunction ||
13238 (KeyFunction->hasBody(KeyFunctionDef) &&
13239 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013240 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13241 TSK_ExplicitInstantiationDefinition
13242 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13243 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013244 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013245 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013246 VTableUses.clear();
13247
Douglas Gregor97509692011-04-22 22:25:37 +000013248 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013249}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013250
Richard Smithd3b5c9082012-07-27 04:22:15 +000013251void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13252 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013253 for (const auto *I : RD->methods())
13254 if (I->isVirtual() && !I->isPure())
13255 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013256}
13257
Rafael Espindola5b334082010-03-26 00:36:59 +000013258void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13259 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013260 // Mark all functions which will appear in RD's vtable as used.
13261 CXXFinalOverriderMap FinalOverriders;
13262 RD->getFinalOverriders(FinalOverriders);
13263 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13264 E = FinalOverriders.end();
13265 I != E; ++I) {
13266 for (OverridingMethods::const_iterator OI = I->second.begin(),
13267 OE = I->second.end();
13268 OI != OE; ++OI) {
13269 assert(OI->second.size() > 0 && "no final overrider");
13270 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013271
Richard Smith4ff9ff92012-07-07 06:59:51 +000013272 // C++ [basic.def.odr]p2:
13273 // [...] A virtual member function is used if it is not pure. [...]
13274 if (!Overrider->isPure())
13275 MarkFunctionReferenced(Loc, Overrider);
13276 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013277 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013278
13279 // Only classes that have virtual bases need a VTT.
13280 if (RD->getNumVBases() == 0)
13281 return;
13282
Aaron Ballman574705e2014-03-13 15:41:46 +000013283 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013284 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013285 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013286 if (Base->getNumVBases() == 0)
13287 continue;
13288 MarkVirtualMembersReferenced(Loc, Base);
13289 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013290}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013291
13292/// SetIvarInitializers - This routine builds initialization ASTs for the
13293/// Objective-C implementation whose ivars need be initialized.
13294void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013295 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013296 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013297 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013298 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013299 CollectIvarsToConstructOrDestruct(OID, ivars);
13300 if (ivars.empty())
13301 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013302 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013303 for (unsigned i = 0; i < ivars.size(); i++) {
13304 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013305 if (Field->isInvalidDecl())
13306 continue;
13307
Alexis Hunt1d792652011-01-08 20:30:50 +000013308 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013309 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13310 InitializationKind InitKind =
13311 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013312
13313 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13314 ExprResult MemberInit =
13315 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013316 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013317 // Note, MemberInit could actually come back empty if no initialization
13318 // is required (e.g., because it would call a trivial default constructor)
13319 if (!MemberInit.get() || MemberInit.isInvalid())
13320 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013321
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013322 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013323 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13324 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013325 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013326 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013327 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013328
13329 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013330 if (const RecordType *RecordTy =
13331 Context.getBaseElementType(Field->getType())
13332 ->getAs<RecordType>()) {
13333 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013334 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013335 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013336 CheckDestructorAccess(Field->getLocation(), Destructor,
13337 PDiag(diag::err_access_dtor_ivar)
13338 << Context.getBaseElementType(Field->getType()));
13339 }
13340 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013341 }
13342 ObjCImplementation->setIvarInitializers(Context,
13343 AllToInit.data(), AllToInit.size());
13344 }
13345}
Alexis Hunt6118d662011-05-04 05:57:24 +000013346
Alexis Hunt27a761d2011-05-04 23:29:54 +000013347static
13348void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13349 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13350 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13351 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13352 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013353 if (Ctor->isInvalidDecl())
13354 return;
13355
Richard Smith802c4b72012-08-23 06:16:52 +000013356 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13357
13358 // Target may not be determinable yet, for instance if this is a dependent
13359 // call in an uninstantiated template.
13360 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013361 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013362 (void)Target->hasBody(FNTarget);
13363 Target = const_cast<CXXConstructorDecl*>(
13364 cast_or_null<CXXConstructorDecl>(FNTarget));
13365 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013366
13367 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13368 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013369 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013370
David Blaikie82e95a32014-11-19 07:49:47 +000013371 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013372 return;
13373
13374 // We know that beyond here, we aren't chaining into a cycle.
13375 if (!Target || !Target->isDelegatingConstructor() ||
13376 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013377 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013378 Current.clear();
13379 // We've hit a cycle.
13380 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13381 Current.count(TCanonical)) {
13382 // If we haven't diagnosed this cycle yet, do so now.
13383 if (!Invalid.count(TCanonical)) {
13384 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013385 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013386 << Ctor;
13387
Richard Smith802c4b72012-08-23 06:16:52 +000013388 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013389 if (TCanonical != Canonical)
13390 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13391
13392 CXXConstructorDecl *C = Target;
13393 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013394 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013395 (void)C->getTargetConstructor()->hasBody(FNTarget);
13396 assert(FNTarget && "Ctor cycle through bodiless function");
13397
Richard Smith802c4b72012-08-23 06:16:52 +000013398 C = const_cast<CXXConstructorDecl*>(
13399 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013400 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13401 }
13402 }
13403
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013404 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013405 Current.clear();
13406 } else {
13407 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13408 }
13409}
13410
13411
Alexis Hunt6118d662011-05-04 05:57:24 +000013412void Sema::CheckDelegatingCtorCycles() {
13413 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13414
Douglas Gregorbae31202011-07-27 21:57:17 +000013415 for (DelegatingCtorDeclsType::iterator
13416 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013417 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013418 I != E; ++I)
13419 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013420
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013421 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13422 CE = Invalid.end();
13423 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013424 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013425}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013426
Douglas Gregor3024f072012-04-16 07:05:22 +000013427namespace {
13428 /// \brief AST visitor that finds references to the 'this' expression.
13429 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13430 Sema &S;
13431
13432 public:
13433 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13434
13435 bool VisitCXXThisExpr(CXXThisExpr *E) {
13436 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13437 << E->isImplicit();
13438 return false;
13439 }
13440 };
13441}
13442
13443bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13444 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13445 if (!TSInfo)
13446 return false;
13447
13448 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013449 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013450 if (!ProtoTL)
13451 return false;
13452
13453 // C++11 [expr.prim.general]p3:
13454 // [The expression this] shall not appear before the optional
13455 // cv-qualifier-seq and it shall not appear within the declaration of a
13456 // static member function (although its type and value category are defined
13457 // within a static member function as they are within a non-static member
13458 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013459 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013460 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013461 FindCXXThisExpr Finder(*this);
13462
13463 // If the return type came after the cv-qualifier-seq, check it now.
13464 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013465 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013466 return true;
13467
13468 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013469 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13470 return true;
13471
13472 return checkThisInStaticMemberFunctionAttributes(Method);
13473}
13474
13475bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13476 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13477 if (!TSInfo)
13478 return false;
13479
13480 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013481 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013482 if (!ProtoTL)
13483 return false;
13484
David Blaikie6adc78e2013-02-18 22:06:02 +000013485 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013486 FindCXXThisExpr Finder(*this);
13487
Douglas Gregor3024f072012-04-16 07:05:22 +000013488 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013489 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013490 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013491 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013492 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013493 case EST_DynamicNone:
13494 case EST_MSAny:
13495 case EST_None:
13496 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013497
Douglas Gregor3024f072012-04-16 07:05:22 +000013498 case EST_ComputedNoexcept:
13499 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13500 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013501
Douglas Gregor3024f072012-04-16 07:05:22 +000013502 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013503 for (const auto &E : Proto->exceptions()) {
13504 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013505 return true;
13506 }
13507 break;
13508 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013509
13510 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013511}
13512
13513bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13514 FindCXXThisExpr Finder(*this);
13515
13516 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013517 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013518 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013519 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013520 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013521 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013522 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013523 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013524 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013525 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013526 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013527 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013528 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013529 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013530 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013531 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013532 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013533 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013534 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013535 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013536 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013537 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013538 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013539 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013540 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013541 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013542 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013543 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013544 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013545 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013546 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013547
13548 if (Arg && !Finder.TraverseStmt(Arg))
13549 return true;
13550
13551 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13552 if (!Finder.TraverseStmt(Args[I]))
13553 return true;
13554 }
13555 }
13556
13557 return false;
13558}
13559
Richard Smith2e321552014-11-12 02:00:47 +000013560void Sema::checkExceptionSpecification(
13561 bool IsTopLevel, ExceptionSpecificationType EST,
13562 ArrayRef<ParsedType> DynamicExceptions,
13563 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13564 SmallVectorImpl<QualType> &Exceptions,
13565 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013566 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013567 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013568 if (EST == EST_Dynamic) {
13569 Exceptions.reserve(DynamicExceptions.size());
13570 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13571 // FIXME: Preserve type source info.
13572 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13573
Richard Smith2e321552014-11-12 02:00:47 +000013574 if (IsTopLevel) {
13575 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13576 collectUnexpandedParameterPacks(ET, Unexpanded);
13577 if (!Unexpanded.empty()) {
13578 DiagnoseUnexpandedParameterPacks(
13579 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13580 Unexpanded);
13581 continue;
13582 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013583 }
13584
13585 // Check that the type is valid for an exception spec, and
13586 // drop it if not.
13587 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13588 Exceptions.push_back(ET);
13589 }
Richard Smith8acb4282014-07-31 21:57:55 +000013590 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013591 return;
13592 }
Richard Smith8acb4282014-07-31 21:57:55 +000013593
Douglas Gregor433e0532012-04-16 18:27:27 +000013594 if (EST == EST_ComputedNoexcept) {
13595 // If an error occurred, there's no expression here.
13596 if (NoexceptExpr) {
13597 assert((NoexceptExpr->isTypeDependent() ||
13598 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13599 Context.BoolTy) &&
13600 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013601 if (IsTopLevel && NoexceptExpr &&
13602 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013603 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013604 return;
13605 }
Richard Smith8acb4282014-07-31 21:57:55 +000013606
Douglas Gregor433e0532012-04-16 18:27:27 +000013607 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013608 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013609 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013610 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013611 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013612 }
13613 return;
13614 }
13615}
13616
Richard Smith0b3a4622014-11-13 20:01:57 +000013617void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13618 ExceptionSpecificationType EST,
13619 SourceRange SpecificationRange,
13620 ArrayRef<ParsedType> DynamicExceptions,
13621 ArrayRef<SourceRange> DynamicExceptionRanges,
13622 Expr *NoexceptExpr) {
13623 if (!MethodD)
13624 return;
13625
13626 // Dig out the method we're referring to.
13627 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13628 MethodD = FunTmpl->getTemplatedDecl();
13629
13630 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13631 if (!Method)
13632 return;
13633
13634 // Check the exception specification.
13635 llvm::SmallVector<QualType, 4> Exceptions;
13636 FunctionProtoType::ExceptionSpecInfo ESI;
13637 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13638 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13639 ESI);
13640
13641 // Update the exception specification on the function type.
13642 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13643
13644 if (Method->isStatic())
13645 checkThisInStaticMemberFunctionExceptionSpec(Method);
13646
13647 if (Method->isVirtual()) {
13648 // Check overrides, which we previously had to delay.
13649 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13650 OEnd = Method->end_overridden_methods();
13651 O != OEnd; ++O)
13652 CheckOverridingFunctionExceptionSpec(Method, *O);
13653 }
13654}
13655
John McCall5e77d762013-04-16 07:28:30 +000013656/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13657///
13658MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13659 SourceLocation DeclStart,
13660 Declarator &D, Expr *BitWidth,
13661 InClassInitStyle InitStyle,
13662 AccessSpecifier AS,
13663 AttributeList *MSPropertyAttr) {
13664 IdentifierInfo *II = D.getIdentifier();
13665 if (!II) {
13666 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013667 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013668 }
13669 SourceLocation Loc = D.getIdentifierLoc();
13670
13671 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13672 QualType T = TInfo->getType();
13673 if (getLangOpts().CPlusPlus) {
13674 CheckExtraCXXDefaultArguments(D);
13675
13676 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13677 UPPC_DataMemberType)) {
13678 D.setInvalidType();
13679 T = Context.IntTy;
13680 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13681 }
13682 }
13683
13684 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13685
13686 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13687 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13688 diag::err_invalid_thread)
13689 << DeclSpec::getSpecifierName(TSCS);
13690
13691 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013692 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013693 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13694 LookupName(Previous, S);
13695 switch (Previous.getResultKind()) {
13696 case LookupResult::Found:
13697 case LookupResult::FoundUnresolvedValue:
13698 PrevDecl = Previous.getAsSingle<NamedDecl>();
13699 break;
13700
13701 case LookupResult::FoundOverloaded:
13702 PrevDecl = Previous.getRepresentativeDecl();
13703 break;
13704
13705 case LookupResult::NotFound:
13706 case LookupResult::NotFoundInCurrentInstantiation:
13707 case LookupResult::Ambiguous:
13708 break;
13709 }
13710
13711 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13712 // Maybe we will complain about the shadowed template parameter.
13713 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13714 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013715 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013716 }
13717
13718 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013719 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013720
13721 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013722 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013723 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13724 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013725 ProcessDeclAttributes(TUScope, NewPD, D);
13726 NewPD->setAccess(AS);
13727
13728 if (NewPD->isInvalidDecl())
13729 Record->setInvalidDecl();
13730
13731 if (D.getDeclSpec().isModulePrivateSpecified())
13732 NewPD->setModulePrivate();
13733
13734 if (NewPD->isInvalidDecl() && PrevDecl) {
13735 // Don't introduce NewFD into scope; there's already something
13736 // with the same name in the same scope.
13737 } else if (II) {
13738 PushOnScopeChains(NewPD, S);
13739 } else
13740 Record->addDecl(NewPD);
13741
13742 return NewPD;
13743}