blob: ee81bbc2872af30b3db0c92310c1293c3adffa07 [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;
Benjamin Kramer642f1732015-07-02 21:03:14 +000076 for (Stmt *SubStmt : Node->children())
77 IsInvalid |= Visit(SubStmt);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000148}
Chris Lattner58258242008-04-10 02:22:51 +0000149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000165 // If we have a throw-all spec at this point, ignore the function.
166 if (ComputedEST == EST_None)
167 return;
168
Davide Italiano1a7f6482015-07-16 22:37:54 +0000169 switch(EST) {
170 // If this function can throw any exceptions, make a note of that.
171 case EST_MSAny:
172 case EST_None:
173 ClearExceptions();
174 ComputedEST = EST;
175 return;
176 // FIXME: If the call to this decl is using any of its default arguments, we
177 // need to search them for potentially-throwing calls.
178 // If this function has a basic noexcept, it doesn't affect the outcome.
179 case EST_BasicNoexcept:
180 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000183 case EST_DynamicNone:
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000187 // Check out noexcept specs.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000188 case EST_ComputedNoexcept:
189 {
Richard Smithf623c962012-04-17 00:58:00 +0000190 FunctionProtoType::NoexceptResult NR =
191 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000192 assert(NR != FunctionProtoType::NR_NoNoexcept &&
193 "Must have noexcept result for EST_ComputedNoexcept.");
194 assert(NR != FunctionProtoType::NR_Dependent &&
195 "Should not generate implicit declarations for dependent cases, "
196 "and don't know how to handle them anyway.");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000197 // noexcept(false) -> no spec on the new function
198 if (NR == FunctionProtoType::NR_Throw) {
199 ClearExceptions();
200 ComputedEST = EST_None;
201 }
202 // noexcept(true) won't change anything either.
203 return;
204 }
Davide Italiano1a7f6482015-07-16 22:37:54 +0000205 default:
206 break;
207 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000213 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000216}
217
Richard Smith938f40b2011-06-11 17:19:42 +0000218void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000219 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000220 return;
221
222 // FIXME:
223 //
224 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000225 // [An] implicit exception-specification specifies the type-id T if and
226 // only if T is allowed by the exception-specification of a function directly
227 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000228 // function it directly invokes allows all exceptions, and f shall allow no
229 // exceptions if every function it directly invokes allows no exceptions.
230 //
231 // Note in particular that if an implicit exception-specification is generated
232 // for a function containing a throw-expression, that specification can still
233 // be noexcept(true).
234 //
235 // Note also that 'directly invoked' is not defined in the standard, and there
236 // is no indication that we should only consider potentially-evaluated calls.
237 //
238 // Ultimately we should implement the intent of the standard: the exception
239 // specification should be the set of exceptions which can be thrown by the
240 // implicit definition. For now, we assume that any non-nothrow expression can
241 // throw any exception.
242
Richard Smithf623c962012-04-17 00:58:00 +0000243 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000244 ComputedEST = EST_None;
245}
246
Anders Carlssonc80a1272009-08-25 02:29:20 +0000247bool
John McCallb268a282010-08-23 23:25:46 +0000248Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000249 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000250 if (RequireCompleteType(Param->getLocation(), Param->getType(),
251 diag::err_typecheck_decl_incomplete_type)) {
252 Param->setInvalidDecl();
253 return true;
254 }
255
Anders Carlssonc80a1272009-08-25 02:29:20 +0000256 // C++ [dcl.fct.default]p5
257 // A default argument expression is implicitly converted (clause
258 // 4) to the parameter type. The default argument expression has
259 // the same semantic constraints as the initializer expression in
260 // a declaration of a variable of the parameter type, using the
261 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000266 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000268 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000269 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000270 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000271
Richard Smithc406cb72013-01-17 01:17:56 +0000272 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000273 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlssonc80a1272009-08-25 02:29:20 +0000275 // Okay: add the default argument to the parameter
276 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Douglas Gregor758cb672010-10-12 18:23:32 +0000278 // We have already instantiated this parameter; provide each of the
279 // instantiations with the uninstantiated default argument.
280 UnparsedDefaultArgInstantiationsMap::iterator InstPos
281 = UnparsedDefaultArgInstantiations.find(Param);
282 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285
286 // We're done tracking this parameter's instantiations.
287 UnparsedDefaultArgInstantiations.erase(InstPos);
288 }
289
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000290 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000291}
292
Chris Lattner58258242008-04-10 02:22:51 +0000293/// ActOnParamDefaultArgument - Check whether the default argument
294/// provided for a function parameter is well-formed. If so, attach it
295/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000296void
John McCall48871652010-08-21 09:40:31 +0000297Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000298 Expr *DefaultArg) {
299 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000300 return;
Mike Stump11289f42009-09-09 15:08:12 +0000301
John McCall48871652010-08-21 09:40:31 +0000302 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000303 UnparsedDefaultArgLocs.erase(Param);
304
Chris Lattner199abbc2008-04-08 05:04:30 +0000305 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000306 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000307 Diag(EqualLoc, diag::err_param_default_argument)
308 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000309 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000310 return;
311 }
312
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000313 // Check for unexpanded parameter packs.
314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315 Param->setInvalidDecl();
316 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000317 }
318
319 // C++11 [dcl.fct.default]p3
320 // A default argument expression [...] shall not be specified for a
321 // parameter pack.
322 if (Param->isParameterPack()) {
323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324 << DefaultArg->getSourceRange();
325 return;
326 }
327
Anders Carlssonf1c26952009-08-25 01:02:06 +0000328 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000331 Param->setInvalidDecl();
332 return;
333 }
Mike Stump11289f42009-09-09 15:08:12 +0000334
John McCallb268a282010-08-23 23:25:46 +0000335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000336}
337
Douglas Gregor58354032008-12-24 00:01:03 +0000338/// ActOnParamUnparsedDefaultArgument - We've seen a default
339/// argument for a function parameter, but we can't parse it yet
340/// because we're inside a class definition. Note that this default
341/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000342void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 SourceLocation EqualLoc,
344 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000345 if (!param)
346 return;
Mike Stump11289f42009-09-09 15:08:12 +0000347
John McCall48871652010-08-21 09:40:31 +0000348 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000349 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000350 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000351}
352
Douglas Gregor4d87df52008-12-16 21:30:33 +0000353/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000355void Sema::ActOnParamDefaultArgumentError(Decl *param,
356 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000357 if (!param)
358 return;
Mike Stump11289f42009-09-09 15:08:12 +0000359
John McCall48871652010-08-21 09:40:31 +0000360 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000361 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000362 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000363 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000364 OpaqueValueExpr(EqualLoc,
365 Param->getType().getNonReferenceType(),
366 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000367}
368
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000369/// CheckExtraCXXDefaultArguments - Check for any extra default
370/// arguments in the declarator, which is not a function declaration
371/// or definition and therefore is not permitted to have default
372/// arguments. This routine should be invoked for every declarator
373/// that is not a function declaration or definition.
374void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375 // C++ [dcl.fct.default]p3
376 // A default argument expression shall be specified only in the
377 // parameter-declaration-clause of a function declaration or in a
378 // template-parameter (14.1). It shall not be specified for a
379 // parameter pack. If it is specified in a
380 // parameter-declaration-clause, it shall not occur within a
381 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000382 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000384 DeclaratorChunk &chunk = D.getTypeObject(i);
385 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000386 if (MightBeFunction) {
387 // This is a function declaration. It can have default arguments, but
388 // keep looking in case its return type is a function type with default
389 // arguments.
390 MightBeFunction = false;
391 continue;
392 }
Alp Tokerc5350722014-02-26 22:27:52 +0000393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394 ++argIdx) {
395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000396 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000398 SourceRange SR;
399 if (Toks->size() > 1)
400 SR = SourceRange((*Toks)[1].getLocation(),
401 Toks->back().getLocation());
402 else
403 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000405 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000411 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000412 }
413 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000416 }
417 }
418}
419
David Majnemer502b0ed2013-06-25 23:09:30 +0000420static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
Craig Toppere4794282012-09-21 04:33:26 +0000431/// MergeCXXFunctionDecl - Merge two declarations of the same C++
432/// function, once we already know that they have the same
433/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000437 bool Invalid = false;
438
Richard Smithc7d48d12015-05-20 17:50:35 +0000439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
445
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
474 // We found our guy.
475 break;
476 }
477
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490 //
491 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
Richard Smithc7d48d12015-05-20 17:50:35 +0000503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
James Molloye9430032012-03-13 08:55:35 +0000506 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000524 Invalid = false;
525 }
526 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000527
Francois Pichet8cb243a2011-04-10 04:58:30 +0000528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000536 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000537 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000543 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 }
546
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000549 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000552 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000553 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
John McCalle61b02b2010-05-04 01:53:42 +0000560 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000561 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000612 }
613 }
614
Richard Smith58c3cc12012-11-28 03:45:24 +0000615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
David Majnemeree4f4022014-03-30 06:44:54 +0000631 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000633 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000648 }
649
David Majnemer502b0ed2013-06-25 23:09:30 +0000650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000651 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000652 // the only declaration of the function or function template in the
653 // translation unit.
654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655 functionDeclHasDefaultArgument(Old)) {
656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 Invalid = true;
659 }
660
Douglas Gregorf40863c2010-02-12 07:32:17 +0000661 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000662 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000663
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000664 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000665}
666
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000667/// \brief Merge the exception specifications of two variable declarations.
668///
669/// This is called when there's a redeclaration of a VarDecl. The function
670/// checks if the redeclaration might have an exception specification and
671/// validates compatibility and merges the specs if necessary.
672void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000674 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000675 return;
676
677 assert(Context.hasSameType(New->getType(), Old->getType()) &&
678 "Should only be called if types are otherwise the same.");
679
680 QualType NewType = New->getType();
681 QualType OldType = Old->getType();
682
683 // We're only interested in pointers and references to functions, as well
684 // as pointers to member functions.
685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686 NewType = R->getPointeeType();
687 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689 NewType = P->getPointeeType();
690 OldType = OldType->getAs<PointerType>()->getPointeeType();
691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692 NewType = M->getPointeeType();
693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694 }
695
696 if (!NewType->isFunctionProtoType())
697 return;
698
699 // There's lots of special cases for functions. For function pointers, system
700 // libraries are hopefully not as broken so that we don't need these
701 // workarounds.
702 if (CheckEquivalentExceptionSpec(
703 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705 New->setInvalidDecl();
706 }
707}
708
Chris Lattner199abbc2008-04-08 05:04:30 +0000709/// CheckCXXDefaultArguments - Verify that the default arguments for a
710/// function declaration are well-formed according to C++
711/// [dcl.fct.default].
712void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713 unsigned NumParams = FD->getNumParams();
714 unsigned p;
715
716 // Find first parameter with a default argument
717 for (p = 0; p < NumParams; ++p) {
718 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000719 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000720 break;
721 }
722
Benjamin Kramerfe257592015-03-27 13:58:41 +0000723 // C++11 [dcl.fct.default]p4:
724 // In a given function declaration, each parameter subsequent to a parameter
725 // with a default argument shall have a default argument supplied in this or
726 // a previous declaration or shall be a function parameter pack. A default
727 // argument shall not be redefined by a later declaration (not even to the
728 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +0000729 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000730 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000731 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +0000732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000733 if (Param->isInvalidDecl())
734 /* We already complained about this parameter. */;
735 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000736 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000737 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000738 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000739 else
Mike Stump11289f42009-09-09 15:08:12 +0000740 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000741 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattner199abbc2008-04-08 05:04:30 +0000743 LastMissingDefaultArg = p;
744 }
745 }
746
747 if (LastMissingDefaultArg > 0) {
748 // Some default arguments were missing. Clear out all of the
749 // default arguments up to (and including) the last missing
750 // default argument, so that we leave the function parameters
751 // in a semantically valid state.
752 for (p = 0; p <= LastMissingDefaultArg; ++p) {
753 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000754 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000756 }
757 }
758 }
759}
Douglas Gregor556877c2008-04-13 21:30:24 +0000760
Richard Smitheb3c10c2011-10-01 02:31:28 +0000761// CheckConstexprParameterTypes - Check whether a function's parameter types
762// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000763// diagnostic and return false.
764static bool CheckConstexprParameterTypes(Sema &SemaRef,
765 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000766 unsigned ArgIndex = 0;
767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769 e = FT->param_type_end();
770 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772 SourceLocation ParamLoc = PD->getLocation();
773 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000774 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000775 diag::err_constexpr_non_literal_param,
776 ArgIndex+1, PD->getSourceRange(),
777 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000780 return true;
781}
782
783/// \brief Get diagnostic %select index for tag kind for
784/// record diagnostic message.
785/// WARNING: Indexes apply to particular diagnostics only!
786///
787/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000788static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000789 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000790 case TTK_Struct: return 0;
791 case TTK_Interface: return 1;
792 case TTK_Class: return 2;
793 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000794 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000795}
796
797// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798// the requirements of a constexpr function definition or a constexpr
799// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000800// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801//
Richard Smith3607ffe2012-02-13 03:54:03 +0000802// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
803bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 // C++11 [dcl.constexpr]p4:
807 // The definition of a constexpr constructor shall satisfy the following
808 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000810 const CXXRecordDecl *RD = MD->getParent();
811 if (RD->getNumVBases()) {
812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813 << isa<CXXConstructorDecl>(NewFD)
814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000815 for (const auto &I : RD->vbases())
816 Diag(I.getLocStart(),
817 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000818 return false;
819 }
Richard Smith7971b692012-01-13 04:54:00 +0000820 }
821
822 if (!isa<CXXConstructorDecl>(NewFD)) {
823 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 // The definition of a constexpr function shall satisfy the following
825 // constraints:
826 // - it shall not be virtual;
827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +0000829 Method = Method->getCanonicalDecl();
830 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000831
Richard Smith3607ffe2012-02-13 03:54:03 +0000832 // If it's not obvious why this function is virtual, find an overridden
833 // function which uses the 'virtual' keyword.
834 const CXXMethodDecl *WrittenVirtual = Method;
835 while (!WrittenVirtual->isVirtualAsWritten())
836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837 if (WrittenVirtual != Method)
838 Diag(WrittenVirtual->getLocation(),
839 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000840 return false;
841 }
842
843 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000844 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000845 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000846 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000847 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000848 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000849 }
850
Richard Smith7971b692012-01-13 04:54:00 +0000851 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000852 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000853 return false;
854
Richard Smitheb3c10c2011-10-01 02:31:28 +0000855 return true;
856}
857
858/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000859/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000860///
Richard Smithd9f663b2013-04-22 15:31:51 +0000861/// \return true if the body is OK (maybe only as an extension), false if we
862/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000863static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
867 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000868 for (const auto *DclIt : DS->decls()) {
869 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000870 case Decl::StaticAssert:
871 case Decl::Using:
872 case Decl::UsingShadow:
873 case Decl::UsingDirective:
874 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000875 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000876 // - static_assert-declarations
877 // - using-declarations,
878 // - using-directives,
879 continue;
880
881 case Decl::Typedef:
882 case Decl::TypeAlias: {
883 // - typedef declarations and alias-declarations that do not define
884 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000885 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000886 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887 // Don't allow variably-modified types in constexpr functions.
888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890 << TL.getSourceRange() << TL.getType()
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894 continue;
895 }
896
897 case Decl::Enum:
898 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000899 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000902 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000903 ? diag::warn_cxx11_compat_constexpr_type_definition
904 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000905 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906 continue;
907
Richard Smithd9f663b2013-04-22 15:31:51 +0000908 case Decl::EnumConstant:
909 case Decl::IndirectField:
910 case Decl::ParmVar:
911 // These can only appear with other declarations which are banned in
912 // C++11 and permitted in C++1y, so ignore them.
913 continue;
914
915 case Decl::Var: {
916 // C++1y [dcl.constexpr]p3 allows anything except:
917 // a definition of a variable of non-literal type or of static or
918 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000919 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000920 if (VD->isThisDeclarationADefinition()) {
921 if (VD->isStaticLocal()) {
922 SemaRef.Diag(VD->getLocation(),
923 diag::err_constexpr_local_var_static)
924 << isa<CXXConstructorDecl>(Dcl)
925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926 return false;
927 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000928 if (!VD->getType()->isDependentType() &&
929 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000930 VD->getLocation(), VD->getType(),
931 diag::err_constexpr_local_var_non_literal_type,
932 isa<CXXConstructorDecl>(Dcl)))
933 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000934 if (!VD->getType()->isDependentType() &&
935 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000936 SemaRef.Diag(VD->getLocation(),
937 diag::err_constexpr_local_var_no_init)
938 << isa<CXXConstructorDecl>(Dcl);
939 return false;
940 }
941 }
942 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000943 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000944 ? diag::warn_cxx11_compat_constexpr_local_var
945 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000946 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000947 continue;
948 }
949
950 case Decl::NamespaceAlias:
951 case Decl::Function:
952 // These are disallowed in C++11 and permitted in C++1y. Allow them
953 // everywhere as an extension.
954 if (!Cxx1yLoc.isValid())
955 Cxx1yLoc = DS->getLocStart();
956 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000957
958 default:
959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960 << isa<CXXConstructorDecl>(Dcl);
961 return false;
962 }
963 }
964
965 return true;
966}
967
968/// Check that the given field is initialized within a constexpr constructor.
969///
970/// \param Dcl The constexpr constructor being checked.
971/// \param Field The field being checked. This may be a member of an anonymous
972/// struct or union nested within the class being checked.
973/// \param Inits All declarations, including anonymous struct/union members and
974/// indirect members, for which any initialization was provided.
975/// \param Diagnosed Set to true if an error is produced.
976static void CheckConstexprCtorInitializer(Sema &SemaRef,
977 const FunctionDecl *Dcl,
978 FieldDecl *Field,
979 llvm::SmallSet<Decl*, 16> &Inits,
980 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000981 if (Field->isInvalidDecl())
982 return;
983
Douglas Gregor556e5862011-10-10 17:22:13 +0000984 if (Field->isUnnamedBitfield())
985 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000986
Richard Smithab44d5b2013-12-10 08:25:00 +0000987 // Anonymous unions with no variant members and empty anonymous structs do not
988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000990 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000991 (Field->getType()->isUnionType()
992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000994 return;
995
Richard Smitheb3c10c2011-10-01 02:31:28 +0000996 if (!Inits.count(Field)) {
997 if (!Diagnosed) {
998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999 Diagnosed = true;
1000 }
1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002 } else if (Field->isAnonymousStructOrUnion()) {
1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001004 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001005 // If an anonymous union contains an anonymous struct of which any member
1006 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001007 if (!RD->isUnion() || Inits.count(I))
1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001009 }
1010}
1011
Richard Smithd9f663b2013-04-22 15:31:51 +00001012/// Check the provided statement is allowed in a constexpr function
1013/// definition.
1014static bool
1015CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001016 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001017 SourceLocation &Cxx1yLoc) {
1018 // - its function-body shall be [...] a compound-statement that contains only
1019 switch (S->getStmtClass()) {
1020 case Stmt::NullStmtClass:
1021 // - null statements,
1022 return true;
1023
1024 case Stmt::DeclStmtClass:
1025 // - static_assert-declarations
1026 // - using-declarations,
1027 // - using-directives,
1028 // - typedef declarations and alias-declarations that do not define
1029 // classes or enumerations,
1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031 return false;
1032 return true;
1033
1034 case Stmt::ReturnStmtClass:
1035 // - and exactly one return statement;
1036 if (isa<CXXConstructorDecl>(Dcl)) {
1037 // C++1y allows return statements in constexpr constructors.
1038 if (!Cxx1yLoc.isValid())
1039 Cxx1yLoc = S->getLocStart();
1040 return true;
1041 }
1042
1043 ReturnStmts.push_back(S->getLocStart());
1044 return true;
1045
1046 case Stmt::CompoundStmtClass: {
1047 // C++1y allows compound-statements.
1048 if (!Cxx1yLoc.isValid())
1049 Cxx1yLoc = S->getLocStart();
1050
1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001052 for (auto *BodyIt : CompStmt->body()) {
1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001054 Cxx1yLoc))
1055 return false;
1056 }
1057 return true;
1058 }
1059
1060 case Stmt::AttributedStmtClass:
1061 if (!Cxx1yLoc.isValid())
1062 Cxx1yLoc = S->getLocStart();
1063 return true;
1064
1065 case Stmt::IfStmtClass: {
1066 // C++1y allows if-statements.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1069
1070 IfStmt *If = cast<IfStmt>(S);
1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072 Cxx1yLoc))
1073 return false;
1074 if (If->getElse() &&
1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076 Cxx1yLoc))
1077 return false;
1078 return true;
1079 }
1080
1081 case Stmt::WhileStmtClass:
1082 case Stmt::DoStmtClass:
1083 case Stmt::ForStmtClass:
1084 case Stmt::CXXForRangeStmtClass:
1085 case Stmt::ContinueStmtClass:
1086 // C++1y allows all of these. We don't allow them as extensions in C++11,
1087 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001088 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001089 break;
1090 if (!Cxx1yLoc.isValid())
1091 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001092 for (Stmt *SubStmt : S->children())
1093 if (SubStmt &&
1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001095 Cxx1yLoc))
1096 return false;
1097 return true;
1098
1099 case Stmt::SwitchStmtClass:
1100 case Stmt::CaseStmtClass:
1101 case Stmt::DefaultStmtClass:
1102 case Stmt::BreakStmtClass:
1103 // C++1y allows switch-statements, and since they don't need variable
1104 // mutation, we can reasonably allow them in C++11 as an extension.
1105 if (!Cxx1yLoc.isValid())
1106 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001107 for (Stmt *SubStmt : S->children())
1108 if (SubStmt &&
1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001110 Cxx1yLoc))
1111 return false;
1112 return true;
1113
1114 default:
1115 if (!isa<Expr>(S))
1116 break;
1117
1118 // C++1y allows expression-statements.
1119 if (!Cxx1yLoc.isValid())
1120 Cxx1yLoc = S->getLocStart();
1121 return true;
1122 }
1123
1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125 << isa<CXXConstructorDecl>(Dcl);
1126 return false;
1127}
1128
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129/// Check the body for the given constexpr function declaration only contains
1130/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131///
1132/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001133bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001134 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001135 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001136 // The definition of a constexpr function shall satisfy the following
1137 // constraints: [...]
1138 // - its function-body shall be = delete, = default, or a
1139 // compound-statement
1140 //
Richard Smith74388b42012-02-04 00:33:54 +00001141 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001142 // In the definition of a constexpr constructor, [...]
1143 // - its function-body shall not be a function-try-block;
1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145 << isa<CXXConstructorDecl>(Dcl);
1146 return false;
1147 }
1148
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001149 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001150
1151 // - its function-body shall be [...] a compound-statement that contains only
1152 // [... list of cases ...]
1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001155 for (auto *BodyIt : CompBody->body()) {
1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001157 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001158 }
1159
Richard Smithd9f663b2013-04-22 15:31:51 +00001160 if (Cxx1yLoc.isValid())
1161 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001162 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164 : diag::ext_constexpr_body_invalid_stmt)
1165 << isa<CXXConstructorDecl>(Dcl);
1166
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 if (const CXXConstructorDecl *Constructor
1168 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001170 // DR1359:
1171 // - every non-variant non-static data member and base class sub-object
1172 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001173 // DR1460:
1174 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001175 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001176 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001177 if (Constructor->getNumCtorInitializers() == 0 &&
1178 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180 return false;
1181 }
Richard Smithf368fb42011-10-10 16:38:04 +00001182 } else if (!Constructor->isDependentContext() &&
1183 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185
1186 // Skip detailed checking if we have enough initializers, and we would
1187 // allow at most one initializer per member.
1188 bool AnyAnonStructUnionMembers = false;
1189 unsigned Fields = 0;
1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001192 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001193 AnyAnonStructUnionMembers = true;
1194 break;
1195 }
1196 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001197 // DR1460:
1198 // - if the class is a union-like class, but is not a union, for each of
1199 // its anonymous union members having variant members, exactly one of
1200 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001201 if (AnyAnonStructUnionMembers ||
1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203 // Check initialization of non-static data members. Base classes are
1204 // always initialized so do not need to be checked. Dependent bases
1205 // might not have initializers in the member initializer list.
1206 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001207 for (const auto *I: Constructor->inits()) {
1208 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001209 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001210 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001211 Inits.insert(ID->chain_begin(), ID->chain_end());
1212 }
1213
1214 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001215 for (auto *I : RD->fields())
1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001217 if (Diagnosed)
1218 return false;
1219 }
1220 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001221 } else {
1222 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001223 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001224 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001225 // otherwise if there's no return statement, the function cannot
1226 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001227 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001228 (Dcl->getReturnType()->isVoidType() ||
1229 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001230 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00001233 if (!OK)
1234 return false;
1235 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001236 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001237 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001242 }
1243 }
1244
Richard Smith74388b42012-02-04 00:33:54 +00001245 // C++11 [dcl.constexpr]p5:
1246 // if no function argument values exist such that the function invocation
1247 // substitution would produce a constant expression, the program is
1248 // ill-formed; no diagnostic required.
1249 // C++11 [dcl.constexpr]p3:
1250 // - every constructor call and implicit conversion used in initializing the
1251 // return value shall be one of those allowed in a constant expression.
1252 // C++11 [dcl.constexpr]p4:
1253 // - every constructor involved in initializing non-static data members and
1254 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001255 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001258 << isa<CXXConstructorDecl>(Dcl);
1259 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001261 // Don't return false here: we allow this for compatibility in
1262 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001263 }
1264
Richard Smitheb3c10c2011-10-01 02:31:28 +00001265 return true;
1266}
1267
Douglas Gregor61956c42008-10-31 09:07:45 +00001268/// isCurrentClassName - Determine whether the identifier II is the
1269/// name of the class type currently being defined. In the case of
1270/// nested classes, this will only return true if II is the name of
1271/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001272bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001274 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001275
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001276 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001277 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001278 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280 } else
1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001283 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001284 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001285 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001286}
1287
Richard Smithfb8b7b92013-10-15 00:00:26 +00001288/// \brief Determine whether the identifier II is a typo for the name of
1289/// the class type currently being defined. If so, update it to the identifier
1290/// that should have been used.
1291bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292 assert(getLangOpts().CPlusPlus && "No class names in C!");
1293
1294 if (!getLangOpts().SpellChecking)
1295 return false;
1296
1297 CXXRecordDecl *CurDecl;
1298 if (SS && SS->isSet() && !SS->isInvalid()) {
1299 DeclContext *DC = computeDeclContext(*SS, true);
1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301 } else
1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303
1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306 < II->getLength()) {
1307 II = CurDecl->getIdentifier();
1308 return true;
1309 }
1310
1311 return false;
1312}
1313
Douglas Gregordc974572012-11-10 07:24:09 +00001314/// \brief Determine whether the given class is a base class of the given
1315/// class, including looking at dependent bases.
1316static bool findCircularInheritance(const CXXRecordDecl *Class,
1317 const CXXRecordDecl *Current) {
1318 SmallVector<const CXXRecordDecl*, 8> Queue;
1319
1320 Class = Class->getCanonicalDecl();
1321 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001322 for (const auto &I : Current->bases()) {
1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001324 if (!Base)
1325 continue;
1326
1327 Base = Base->getDefinition();
1328 if (!Base)
1329 continue;
1330
1331 if (Base->getCanonicalDecl() == Class)
1332 return true;
1333
1334 Queue.push_back(Base);
1335 }
1336
1337 if (Queue.empty())
1338 return false;
1339
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001340 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001341 }
1342
1343 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001344}
1345
Mike Stump11289f42009-09-09 15:08:12 +00001346/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001347///
1348/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349/// and returns NULL otherwise.
1350CXXBaseSpecifier *
1351Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352 SourceRange SpecifierRange,
1353 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001354 TypeSourceInfo *TInfo,
1355 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001356 QualType BaseType = TInfo->getType();
1357
Douglas Gregor463421d2009-03-03 04:44:36 +00001358 // C++ [class.union]p1:
1359 // A union shall not have base classes.
1360 if (Class->isUnion()) {
1361 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001363 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001364 }
1365
Douglas Gregor752a5952011-01-03 22:36:02 +00001366 if (EllipsisLoc.isValid() &&
1367 !TInfo->getType()->containsUnexpandedParameterPack()) {
1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369 << TInfo->getTypeLoc().getSourceRange();
1370 EllipsisLoc = SourceLocation();
1371 }
Douglas Gregor62004702012-11-10 01:18:17 +00001372
1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374
1375 if (BaseType->isDependentType()) {
1376 // Make sure that we don't have circular inheritance among our dependent
1377 // bases. For non-dependent bases, the check for completeness below handles
1378 // this.
1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001382 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001383 Diag(BaseLoc, diag::err_circular_inheritance)
1384 << BaseType << Context.getTypeDeclType(Class);
1385
1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001389
1390 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001391 }
1392 }
1393
Mike Stump11289f42009-09-09 15:08:12 +00001394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001395 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001396 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001397 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001398
1399 // Base specifiers must be record types.
1400 if (!BaseType->isRecordType()) {
1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001402 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001403 }
1404
1405 // C++ [class.union]p1:
1406 // A union shall not be used as a base class.
1407 if (BaseType->isUnionType()) {
1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 }
1411
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001412 // For the MS ABI, propagate DLL attributes to base class templates.
1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414 if (Attr *ClassAttr = getDLLAttr(Class)) {
1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00001417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001419 }
1420 }
1421 }
1422
Douglas Gregor463421d2009-03-03 04:44:36 +00001423 // C++ [class.derived]p2:
1424 // The class-name in a base-specifier shall not be an incompletely
1425 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001426 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001427 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001428 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001429 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001430 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001431
Eli Friedmanc96d4962009-08-15 21:55:26 +00001432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001434 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001435 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001436 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001438 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001439
David Majnemer9b1754d2013-11-02 12:00:36 +00001440 // A class which contains a flexible array member is not suitable for use as a
1441 // base class:
1442 // - If the layout determines that a base comes before another base,
1443 // the flexible array member would index into the subsequent base.
1444 // - If the layout determines that base comes before the derived class,
1445 // the flexible array member would index into the derived class.
1446 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001449 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001450 }
1451
Anders Carlsson65c76d32011-03-25 14:55:14 +00001452 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001453 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001454 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001457 << CXXBaseDecl->getDeclName()
1458 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001461 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001462 }
1463
John McCall3696dcb2010-08-17 07:23:57 +00001464 if (BaseDecl->isInvalidDecl())
1465 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001466
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001467 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001469 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001470 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001471}
1472
Douglas Gregor556877c2008-04-13 21:30:24 +00001473/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001475/// example:
1476/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001477/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001478BaseResult
John McCall48871652010-08-21 09:40:31 +00001479Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001480 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001481 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001482 ParsedType basetype, SourceLocation BaseLoc,
1483 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001484 if (!classdecl)
1485 return true;
1486
Douglas Gregorc40290e2009-03-09 23:48:35 +00001487 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001489 if (!Class)
1490 return true;
1491
David Majnemer5ef4fe72014-06-13 06:43:46 +00001492 // We haven't yet attached the base specifiers.
1493 Class->setIsParsingBaseSpecifiers();
1494
Richard Smith4c96e992013-02-19 23:47:15 +00001495 // We do not support any C++11 attributes on base-specifiers yet.
1496 // Diagnose any attributes we see.
1497 if (!Attributes.empty()) {
1498 for (AttributeList *Attr = Attributes.getList(); Attr;
1499 Attr = Attr->getNext()) {
1500 if (Attr->isInvalid() ||
1501 Attr->getKind() == AttributeList::IgnoredAttribute)
1502 continue;
1503 Diag(Attr->getLoc(),
1504 Attr->getKind() == AttributeList::UnknownAttribute
1505 ? diag::warn_unknown_attribute_ignored
1506 : diag::err_base_specifier_attribute)
1507 << Attr->getName();
1508 }
1509 }
1510
Craig Topperc3ec1492014-05-26 06:22:03 +00001511 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001512 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001513
Douglas Gregor752a5952011-01-03 22:36:02 +00001514 if (EllipsisLoc.isInvalid() &&
1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001516 UPPC_BaseType))
1517 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001518
Douglas Gregor463421d2009-03-03 04:44:36 +00001519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001520 Virtual, Access, TInfo,
1521 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001522 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001523 else
1524 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001525
Douglas Gregor463421d2009-03-03 04:44:36 +00001526 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001527}
Douglas Gregor556877c2008-04-13 21:30:24 +00001528
Nathan Sidwell44b21742015-01-19 01:44:02 +00001529/// Use small set to collect indirect bases. As this is only used
1530/// locally, there's no need to abstract the small size parameter.
1531typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532
1533/// \brief Recursively add the bases of Type. Don't add Type itself.
1534static void
1535NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536 const QualType &Type)
1537{
1538 // Even though the incoming type is a base, it might not be
1539 // a class -- it could be a template parm, for instance.
1540 if (auto Rec = Type->getAs<RecordType>()) {
1541 auto Decl = Rec->getAsCXXRecordDecl();
1542
1543 // Iterate over its bases.
1544 for (const auto &BaseSpec : Decl->bases()) {
1545 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546 .getUnqualifiedType();
1547 if (Set.insert(Base).second)
1548 // If we've not already seen it, recurse.
1549 NoteIndirectBases(Context, Set, Base);
1550 }
1551 }
1552}
1553
Douglas Gregor463421d2009-03-03 04:44:36 +00001554/// \brief Performs the actual work of attaching the given base class
1555/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00001556bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
1557 MutableArrayRef<CXXBaseSpecifier *> Bases) {
1558 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00001559 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001560
1561 // Used to keep track of which base types we have already seen, so
1562 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001563 // that the key is always the unqualified canonical type of the base
1564 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566
Nathan Sidwell44b21742015-01-19 01:44:02 +00001567 // Used to track indirect bases so we can see if a direct base is
1568 // ambiguous.
1569 IndirectBaseSet IndirectBaseTypes;
1570
Douglas Gregor29a92472008-10-22 17:49:05 +00001571 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001572 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001573 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00001574 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001575 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001576 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001577 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001578
1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001581 // C++ [class.mi]p3:
1582 // A class shall not be specified as a direct base class of a
1583 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001584 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001585 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001586 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001587 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001588
1589 // Delete the duplicate base class specifier; we're going to
1590 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001591 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001592
1593 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001594 } else {
1595 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001596 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001597 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001598
1599 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00001600 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00001601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602
John McCalldb632ac2012-09-25 07:32:39 +00001603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605 if (Class->isInterface() &&
1606 (!RD->isInterface() ||
1607 KnownBase->getAccessSpecifier() != AS_public)) {
1608 // The Microsoft extension __interface does not permit bases that
1609 // are not themselves public interfaces.
1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612 << RD->getSourceRange();
1613 Invalid = true;
1614 }
1615 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001616 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001617 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001618 }
1619 }
1620
1621 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00001622 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001623
1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625 // Check whether this direct base is inaccessible due to ambiguity.
1626 QualType BaseType = Bases[idx]->getType();
1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001629
Nathan Sidwell44b21742015-01-19 01:44:02 +00001630 if (IndirectBaseTypes.count(CanonicalBase)) {
1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632 /*DetectVirtual=*/true);
1633 bool found
1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001636 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001637
1638 if (Paths.isAmbiguous(CanonicalBase))
1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640 << BaseType << getAmbiguousPathsDisplayString(Paths)
1641 << Bases[idx]->getSourceRange();
1642 else
1643 assert(Bases[idx]->isVirtual());
1644 }
1645
1646 // Delete the base class specifier, since its data has been copied
1647 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001648 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001649 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001650
1651 return Invalid;
1652}
1653
1654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655/// class, after checking whether there are any duplicate base
1656/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00001657void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
1658 MutableArrayRef<CXXBaseSpecifier *> Bases) {
1659 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00001660 return;
1661
1662 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00001663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001664}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001665
Douglas Gregor36d1b142009-10-06 17:59:45 +00001666/// \brief Determine whether the type \p Derived is a C++ class that is
1667/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00001668bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001669 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001670 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00001671
Douglas Gregor45bb4832013-03-26 23:36:30 +00001672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001673 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001674 return false;
1675
Douglas Gregor45bb4832013-03-26 23:36:30 +00001676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001677 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001678 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001679
1680 // If either the base or the derived type is invalid, don't try to
1681 // check whether one is derived from the other.
1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683 return false;
1684
Richard Smithdb0ac552015-12-18 22:40:25 +00001685 // FIXME: In a modules build, do we need the entire path to be visible for us
1686 // to be able to use the inheritance relationship?
1687 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1688 return false;
1689
Richard Smith0f59cb32015-12-18 21:45:41 +00001690 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001691}
1692
1693/// \brief Determine whether the type \p Derived is a C++ class that is
1694/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00001695bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
1696 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001697 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001698 return false;
1699
Douglas Gregor45bb4832013-03-26 23:36:30 +00001700 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001701 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001702 return false;
1703
Douglas Gregor45bb4832013-03-26 23:36:30 +00001704 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001705 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001706 return false;
1707
Richard Smithdb0ac552015-12-18 22:40:25 +00001708 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1709 return false;
1710
Douglas Gregor36d1b142009-10-06 17:59:45 +00001711 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1712}
1713
Anders Carlssona70cff62010-04-24 19:06:50 +00001714void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001715 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001716 assert(BasePathArray.empty() && "Base path array must be empty!");
1717 assert(Paths.isRecordingPaths() && "Must record paths!");
1718
1719 const CXXBasePath &Path = Paths.front();
1720
1721 // We first go backward and check if we have a virtual base.
1722 // FIXME: It would be better if CXXBasePath had the base specifier for
1723 // the nearest virtual base.
1724 unsigned Start = 0;
1725 for (unsigned I = Path.size(); I != 0; --I) {
1726 if (Path[I - 1].Base->isVirtual()) {
1727 Start = I - 1;
1728 break;
1729 }
1730 }
1731
1732 // Now add all bases.
1733 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001734 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001735}
1736
Douglas Gregor36d1b142009-10-06 17:59:45 +00001737/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1738/// conversion (where Derived and Base are class types) is
1739/// well-formed, meaning that the conversion is unambiguous (and
1740/// that all of the base classes are accessible). Returns true
1741/// and emits a diagnostic if the code is ill-formed, returns false
1742/// otherwise. Loc is the location where this routine should point to
1743/// if there is an error, and Range is the source range to highlight
1744/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00001745///
1746/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
1747/// diagnostic for the respective type of error will be suppressed, but the
1748/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00001749bool
1750Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001751 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001752 unsigned AmbigiousBaseConvID,
1753 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001754 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00001755 CXXCastPath *BasePath,
1756 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001757 // First, determine whether the path from Derived to Base is
1758 // ambiguous. This is slightly more expensive than checking whether
1759 // the Derived to Base conversion exists, because here we need to
1760 // explore multiple paths to determine if there is an ambiguity.
1761 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1762 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00001763 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001764 assert(DerivationOkay &&
1765 "Can only be used with a derived-to-base conversion");
1766 (void)DerivationOkay;
1767
1768 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00001769 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001770 // Check that the base class can be accessed.
1771 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1772 InaccessibleBaseID)) {
1773 case AR_inaccessible:
1774 return true;
1775 case AR_accessible:
1776 case AR_dependent:
1777 case AR_delayed:
1778 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001779 }
John McCall5b0829a2010-02-10 09:31:12 +00001780 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001781
1782 // Build a base path if necessary.
1783 if (BasePath)
1784 BuildBasePathArray(Paths, *BasePath);
1785 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001786 }
1787
David Majnemer626032f2013-06-22 06:43:58 +00001788 if (AmbigiousBaseConvID) {
1789 // We know that the derived-to-base conversion is ambiguous, and
1790 // we're going to produce a diagnostic. Perform the derived-to-base
1791 // search just one more time to compute all of the possible paths so
1792 // that we can print them out. This is more expensive than any of
1793 // the previous derived-to-base checks we've done, but at this point
1794 // performance isn't as much of an issue.
1795 Paths.clear();
1796 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001797 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00001798 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1799 (void)StillOkay;
1800
1801 // Build up a textual representation of the ambiguous paths, e.g.,
1802 // D -> B -> A, that will be used to illustrate the ambiguous
1803 // conversions in the diagnostic. We only print one of the paths
1804 // to each base class subobject.
1805 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1806
1807 Diag(Loc, AmbigiousBaseConvID)
1808 << Derived << Base << PathDisplayStr << Range << Name;
1809 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001810 return true;
1811}
1812
1813bool
1814Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001815 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001816 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001817 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00001818 return CheckDerivedToBaseConversion(
1819 Derived, Base, diag::err_upcast_to_inaccessible_base,
1820 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
1821 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001822}
1823
1824
1825/// @brief Builds a string representing ambiguous paths from a
1826/// specific derived class to different subobjects of the same base
1827/// class.
1828///
1829/// This function builds a string that can be used in error messages
1830/// to show the different paths that one can take through the
1831/// inheritance hierarchy to go from the derived class to different
1832/// subobjects of a base class. The result looks something like this:
1833/// @code
1834/// struct D -> struct B -> struct A
1835/// struct D -> struct C -> struct A
1836/// @endcode
1837std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1838 std::string PathDisplayStr;
1839 std::set<unsigned> DisplayedPaths;
1840 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1841 Path != Paths.end(); ++Path) {
1842 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1843 // We haven't displayed a path to this particular base
1844 // class subobject yet.
1845 PathDisplayStr += "\n ";
1846 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1847 for (CXXBasePath::const_iterator Element = Path->begin();
1848 Element != Path->end(); ++Element)
1849 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1850 }
1851 }
1852
1853 return PathDisplayStr;
1854}
1855
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001856//===----------------------------------------------------------------------===//
1857// C++ class member Handling
1858//===----------------------------------------------------------------------===//
1859
Abramo Bagnarad7340582010-06-05 05:09:32 +00001860/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001861bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1862 SourceLocation ASLoc,
1863 SourceLocation ColonLoc,
1864 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001865 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001866 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001867 ASLoc, ColonLoc);
1868 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001869 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001870}
1871
Richard Smith18f07db2012-08-06 03:25:17 +00001872/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001873void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001874 if (D->isInvalidDecl())
1875 return;
1876
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001877 // We only care about "override" and "final" declarations.
1878 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1879 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001880
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001881 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001882
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001883 // We can't check dependent instance methods.
1884 if (MD && MD->isInstance() &&
1885 (MD->getParent()->hasAnyDependentBases() ||
1886 MD->getType()->isDependentType()))
1887 return;
1888
1889 if (MD && !MD->isVirtual()) {
1890 // If we have a non-virtual method, check if if hides a virtual method.
1891 // (In that case, it's most likely the method has the wrong type.)
1892 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1893 FindHiddenVirtualMethods(MD, OverloadedMethods);
1894
1895 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001896 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1897 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001898 diag::override_keyword_hides_virtual_member_function)
1899 << "override" << (OverloadedMethods.size() > 1);
1900 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001901 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001902 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001903 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1904 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001905 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001906 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1907 MD->setInvalidDecl();
1908 return;
1909 }
1910 // Fall through into the general case diagnostic.
1911 // FIXME: We might want to attempt typo correction here.
1912 }
1913
1914 if (!MD || !MD->isVirtual()) {
1915 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1916 Diag(OA->getLocation(),
1917 diag::override_keyword_only_allowed_on_virtual_member_functions)
1918 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1919 D->dropAttr<OverrideAttr>();
1920 }
1921 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1922 Diag(FA->getLocation(),
1923 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001924 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1925 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001926 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001927 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001928 return;
1929 }
Richard Smith18f07db2012-08-06 03:25:17 +00001930
Richard Smith18f07db2012-08-06 03:25:17 +00001931 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001932 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001933 // does not override a member function of a base class, the program is
1934 // ill-formed.
1935 bool HasOverriddenMethods =
1936 MD->begin_overridden_methods() != MD->end_overridden_methods();
1937 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1938 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1939 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001940}
1941
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001942void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1943 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1944 return;
1945 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1946 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1947 isa<CXXDestructorDecl>(MD))
1948 return;
1949
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001950 SourceLocation Loc = MD->getLocation();
1951 SourceLocation SpellingLoc = Loc;
1952 if (getSourceManager().isMacroArgExpansion(Loc))
1953 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1954 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1955 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001956 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001957
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001958 if (MD->size_overridden_methods() > 0) {
1959 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1960 << MD->getDeclName();
1961 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1962 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1963 }
1964}
1965
Richard Smith18f07db2012-08-06 03:25:17 +00001966/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001967/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001968/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001969bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1970 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001971 FinalAttr *FA = Old->getAttr<FinalAttr>();
1972 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001973 return false;
1974
1975 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001976 << New->getDeclName()
1977 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001978 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1979 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001980}
1981
Daniel Jasper0baec5492012-06-06 08:32:04 +00001982static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001983 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1984 // FIXME: Destruction of ObjC lifetime types has side-effects.
1985 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1986 return !RD->isCompleteDefinition() ||
1987 !RD->hasTrivialDefaultConstructor() ||
1988 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001989 return false;
1990}
1991
John McCall5e77d762013-04-16 07:28:30 +00001992static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001994 if (it->isDeclspecPropertyAttribute())
1995 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001996 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001997}
1998
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001999/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2000/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002001/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002002/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2003/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002004NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002005Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002006 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002007 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002008 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002009 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002010 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2011 DeclarationName Name = NameInfo.getName();
2012 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002013
2014 // For anonymous bitfields, the location should point to the type.
2015 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002016 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002017
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002018 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002019
John McCallb1cd7da2010-06-04 08:34:12 +00002020 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002021 assert(!DS.isFriendSpecified());
2022
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002023 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002024
John McCalldb632ac2012-09-25 07:32:39 +00002025 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2026 // The Microsoft extension __interface only permits public member functions
2027 // and prohibits constructors, destructors, operators, non-public member
2028 // functions, static methods and data members.
2029 unsigned InvalidDecl;
2030 bool ShowDeclName = true;
2031 if (!isFunc)
2032 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2033 else if (AS != AS_public)
2034 InvalidDecl = 2;
2035 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2036 InvalidDecl = 3;
2037 else switch (Name.getNameKind()) {
2038 case DeclarationName::CXXConstructorName:
2039 InvalidDecl = 4;
2040 ShowDeclName = false;
2041 break;
2042
2043 case DeclarationName::CXXDestructorName:
2044 InvalidDecl = 5;
2045 ShowDeclName = false;
2046 break;
2047
2048 case DeclarationName::CXXOperatorName:
2049 case DeclarationName::CXXConversionFunctionName:
2050 InvalidDecl = 6;
2051 break;
2052
2053 default:
2054 InvalidDecl = 0;
2055 break;
2056 }
2057
2058 if (InvalidDecl) {
2059 if (ShowDeclName)
2060 Diag(Loc, diag::err_invalid_member_in_interface)
2061 << (InvalidDecl-1) << Name;
2062 else
2063 Diag(Loc, diag::err_invalid_member_in_interface)
2064 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002065 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002066 }
2067 }
2068
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002069 // C++ 9.2p6: A member shall not be declared to have automatic storage
2070 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002071 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2072 // data members and cannot be applied to names declared const or static,
2073 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002074 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002075 case DeclSpec::SCS_unspecified:
2076 case DeclSpec::SCS_typedef:
2077 case DeclSpec::SCS_static:
2078 break;
2079 case DeclSpec::SCS_mutable:
2080 if (isFunc) {
2081 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002082
Richard Smithb4a9e862013-04-12 22:46:28 +00002083 // FIXME: It would be nicer if the keyword was ignored only for this
2084 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002085 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002086 }
2087 break;
2088 default:
2089 Diag(DS.getStorageClassSpecLoc(),
2090 diag::err_storageclass_invalid_for_member);
2091 D.getMutableDeclSpec().ClearStorageClassSpecs();
2092 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002093 }
2094
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002095 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2096 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002097 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002098
David Blaikie35506f82013-01-30 01:22:18 +00002099 if (DS.isConstexprSpecified() && isInstField) {
2100 SemaDiagnosticBuilder B =
2101 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2102 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2103 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002104 B << 0 << 0;
2105 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2106 B << FixItHint::CreateRemoval(ConstexprLoc);
2107 else {
2108 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2109 D.getMutableDeclSpec().ClearConstexprSpec();
2110 const char *PrevSpec;
2111 unsigned DiagID;
2112 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2113 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2114 (void)Failed;
2115 assert(!Failed && "Making a constexpr member const shouldn't fail");
2116 }
David Blaikie35506f82013-01-30 01:22:18 +00002117 } else {
2118 B << 1;
2119 const char *PrevSpec;
2120 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002121 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002122 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2123 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002124 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002125 "This is the only DeclSpec that should fail to be applied");
2126 B << 1;
2127 } else {
2128 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2129 isInstField = false;
2130 }
2131 }
2132 }
2133
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002134 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002135 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002136 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002137
2138 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002139 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002140 Diag(Loc, diag::err_bad_variable_name)
2141 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002142 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002143 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002144
Benjamin Kramer365082d2012-05-19 16:34:46 +00002145 IdentifierInfo *II = Name.getAsIdentifierInfo();
2146
Douglas Gregor7c26c042011-09-21 14:40:46 +00002147 // Member field could not be with "template" keyword.
2148 // So TemplateParameterLists should be empty in this case.
2149 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002150 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002151 if (TemplateParams->size()) {
2152 // There is no such thing as a member field template.
2153 Diag(D.getIdentifierLoc(), diag::err_template_member)
2154 << II
2155 << SourceRange(TemplateParams->getTemplateLoc(),
2156 TemplateParams->getRAngleLoc());
2157 } else {
2158 // There is an extraneous 'template<>' for this member.
2159 Diag(TemplateParams->getTemplateLoc(),
2160 diag::err_template_member_noparams)
2161 << II
2162 << SourceRange(TemplateParams->getTemplateLoc(),
2163 TemplateParams->getRAngleLoc());
2164 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002165 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002166 }
2167
Douglas Gregora007d362010-10-13 22:19:53 +00002168 if (SS.isSet() && !SS.isInvalid()) {
2169 // The user provided a superfluous scope specifier inside a class
2170 // definition:
2171 //
2172 // class X {
2173 // int X::member;
2174 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002175 if (DeclContext *DC = computeDeclContext(SS, false))
2176 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002177 else
2178 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2179 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002180
Douglas Gregora007d362010-10-13 22:19:53 +00002181 SS.clear();
2182 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002183
John McCall5e77d762013-04-16 07:28:30 +00002184 AttributeList *MSPropertyAttr =
2185 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002186 if (MSPropertyAttr) {
2187 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2188 BitWidth, InitStyle, AS, MSPropertyAttr);
2189 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002190 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002191 isInstField = false;
2192 } else {
2193 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2194 BitWidth, InitStyle, AS);
2195 assert(Member && "HandleField never returns null");
2196 }
2197 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002198 Member = HandleDeclarator(S, D, TemplateParameterLists);
2199 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002200 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002201
2202 // Non-instance-fields can't have a bitfield.
2203 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002204 if (Member->isInvalidDecl()) {
2205 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002206 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002207 // C++ 9.6p3: A bit-field shall not be a static member.
2208 // "static member 'A' cannot be a bit-field"
2209 Diag(Loc, diag::err_static_not_bitfield)
2210 << Name << BitWidth->getSourceRange();
2211 } else if (isa<TypedefDecl>(Member)) {
2212 // "typedef member 'x' cannot be a bit-field"
2213 Diag(Loc, diag::err_typedef_not_bitfield)
2214 << Name << BitWidth->getSourceRange();
2215 } else {
2216 // A function typedef ("typedef int f(); f a;").
2217 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2218 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002219 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002220 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
Craig Topperc3ec1492014-05-26 06:22:03 +00002223 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002224 Member->setInvalidDecl();
2225 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002226
2227 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002228
Larisse Voufo39a1e502013-08-06 01:03:05 +00002229 // If we have declared a member function template or static data member
2230 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002231 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2232 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002233 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2234 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002235 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002236
Richard Smith18f07db2012-08-06 03:25:17 +00002237 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002238 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002239 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002240 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2241 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002242
Douglas Gregorf2f08062011-03-08 17:10:18 +00002243 if (VS.getLastLocation().isValid()) {
2244 // Update the end location of a method that has a virt-specifiers.
2245 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2246 MD->setRangeEnd(VS.getLastLocation());
2247 }
Richard Smith18f07db2012-08-06 03:25:17 +00002248
Anders Carlssonc87f8612011-01-20 06:29:02 +00002249 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002250
Douglas Gregor92751d42008-11-17 22:58:34 +00002251 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002252
Daniel Jasper0baec5492012-06-06 08:32:04 +00002253 if (isInstField) {
2254 FieldDecl *FD = cast<FieldDecl>(Member);
2255 FieldCollector->Add(FD);
2256
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002257 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002258 // Remember all explicit private FieldDecls that have a name, no side
2259 // effects and are not part of a dependent type declaration.
2260 if (!FD->isImplicit() && FD->getDeclName() &&
2261 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002262 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002263 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002264 !InitializationHasSideEffects(*FD))
2265 UnusedPrivateFields.insert(FD);
2266 }
2267 }
2268
John McCall48871652010-08-21 09:40:31 +00002269 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002270}
2271
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002272namespace {
2273 class UninitializedFieldVisitor
2274 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2275 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002276 // List of Decls to generate a warning on. Also remove Decls that become
2277 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002278 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002279 // List of base classes of the record. Classes are removed after their
2280 // initializers.
2281 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002282 // Vector of decls to be removed from the Decl set prior to visiting the
2283 // nodes. These Decls may have been initialized in the prior initializer.
2284 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002285 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002286 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002287 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002288 // InitList is true, special case initialization of FieldDecls matching
2289 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002290 bool InitList;
2291 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002292 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2293
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002294 public:
2295 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002296 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002297 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2298 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2299 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2300 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002301
Richard Trieufa1d0a72014-10-17 20:56:10 +00002302 // Returns true if the use of ME is not an uninitialized use.
2303 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2304 bool CheckReferenceOnly) {
2305 llvm::SmallVector<FieldDecl*, 4> Fields;
2306 bool ReferenceField = false;
2307 while (ME) {
2308 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2309 if (!FD)
2310 return false;
2311 Fields.push_back(FD);
2312 if (FD->getType()->isReferenceType())
2313 ReferenceField = true;
2314 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2315 }
2316
2317 // Binding a reference to an unintialized field is not an
2318 // uninitialized use.
2319 if (CheckReferenceOnly && !ReferenceField)
2320 return true;
2321
2322 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2323 // Discard the first field since it is the field decl that is being
2324 // initialized.
2325 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2326 UsedFieldIndex.push_back((*I)->getFieldIndex());
2327 }
2328
2329 for (auto UsedIter = UsedFieldIndex.begin(),
2330 UsedEnd = UsedFieldIndex.end(),
2331 OrigIter = InitFieldIndex.begin(),
2332 OrigEnd = InitFieldIndex.end();
2333 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2334 if (*UsedIter < *OrigIter)
2335 return true;
2336 if (*UsedIter > *OrigIter)
2337 break;
2338 }
2339
2340 return false;
2341 }
2342
Richard Trieu2d779b92014-10-01 03:44:58 +00002343 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2344 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002345 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2346 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002347
Richard Trieu1bc22c12013-09-13 03:20:53 +00002348 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2349 // or union.
2350 MemberExpr *FieldME = ME;
2351
Richard Trieu2d779b92014-10-01 03:44:58 +00002352 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2353
Richard Trieu1bc22c12013-09-13 03:20:53 +00002354 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002355 while (MemberExpr *SubME =
2356 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002357
Richard Trieufa1d0a72014-10-17 20:56:10 +00002358 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002359 return;
2360
Richard Trieufa1d0a72014-10-17 20:56:10 +00002361 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002362 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002363 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002364
Richard Trieu2d779b92014-10-01 03:44:58 +00002365 if (!FieldME->getType().isPODType(S.Context))
2366 AllPODFields = false;
2367
Richard Trieu3630c392014-11-21 03:10:30 +00002368 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002369 }
2370
Richard Trieu3630c392014-11-21 03:10:30 +00002371 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002372 return;
2373
Richard Trieu2d779b92014-10-01 03:44:58 +00002374 if (AddressOf && AllPODFields)
2375 return;
2376
Richard Trieu406e65c2013-09-20 03:03:06 +00002377 ValueDecl* FoundVD = FieldME->getMemberDecl();
2378
Richard Trieu3630c392014-11-21 03:10:30 +00002379 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2380 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2381 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2382 }
2383
2384 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2385 QualType T = BaseCast->getType();
2386 if (T->isPointerType() &&
2387 BaseClasses.count(T->getPointeeType())) {
2388 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2389 << T->getPointeeType() << FoundVD;
2390 }
2391 }
2392 }
2393
Richard Trieuef64e942013-10-25 00:56:00 +00002394 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002395 return;
2396
Richard Trieuef64e942013-10-25 00:56:00 +00002397 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002398
Richard Trieufa1d0a72014-10-17 20:56:10 +00002399 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2400 // Special checking for initializer lists.
2401 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2402 return;
2403 }
2404 } else {
2405 // Prevent double warnings on use of unbounded references.
2406 if (CheckReferenceOnly && !IsReference)
2407 return;
2408 }
Richard Trieuef64e942013-10-25 00:56:00 +00002409
2410 unsigned diag = IsReference
2411 ? diag::warn_reference_field_is_uninit
2412 : diag::warn_field_is_uninit;
2413 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2414 if (Constructor)
2415 S.Diag(Constructor->getLocation(),
2416 diag::note_uninit_in_this_constructor)
2417 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2418
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002419 }
2420
Richard Trieu2d779b92014-10-01 03:44:58 +00002421 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002422 E = E->IgnoreParens();
2423
2424 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002425 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2426 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002427 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002428 }
2429
2430 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002431 Visit(CO->getCond());
2432 HandleValue(CO->getTrueExpr(), AddressOf);
2433 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002434 return;
2435 }
2436
2437 if (BinaryConditionalOperator *BCO =
2438 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002439 Visit(BCO->getCond());
2440 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002441 return;
2442 }
2443
Richard Trieuabf6ec42014-08-27 22:15:10 +00002444 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002445 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002446 return;
2447 }
2448
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002449 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2450 switch (BO->getOpcode()) {
2451 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002452 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002453 case(BO_PtrMemD):
2454 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002455 HandleValue(BO->getLHS(), AddressOf);
2456 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002457 return;
2458 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002459 Visit(BO->getLHS());
2460 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002461 return;
2462 }
2463 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002464
2465 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002466 }
2467
Richard Trieufa1d0a72014-10-17 20:56:10 +00002468 void CheckInitListExpr(InitListExpr *ILE) {
2469 InitFieldIndex.push_back(0);
2470 for (auto Child : ILE->children()) {
2471 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2472 CheckInitListExpr(SubList);
2473 } else {
2474 Visit(Child);
2475 }
2476 ++InitFieldIndex.back();
2477 }
2478 InitFieldIndex.pop_back();
2479 }
2480
Richard Trieu8d08a272014-08-28 03:23:47 +00002481 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002482 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002483 // Remove Decls that may have been initialized in the previous
2484 // initializer.
2485 for (ValueDecl* VD : DeclsToRemove)
2486 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002487 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002488
Richard Trieu8d08a272014-08-28 03:23:47 +00002489 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002490 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2491
2492 if (ILE && Field) {
2493 InitList = true;
2494 InitListFieldDecl = Field;
2495 InitFieldIndex.clear();
2496 CheckInitListExpr(ILE);
2497 } else {
2498 InitList = false;
2499 Visit(E);
2500 }
2501
Richard Trieu8d08a272014-08-28 03:23:47 +00002502 if (Field)
2503 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002504 if (BaseClass)
2505 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002506 }
2507
Richard Trieu1bc22c12013-09-13 03:20:53 +00002508 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002509 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002510 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002511 }
2512
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002513 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002514 if (E->getCastKind() == CK_LValueToRValue) {
2515 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2516 return;
2517 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002518
2519 Inherited::VisitImplicitCastExpr(E);
2520 }
2521
Richard Trieu1bc22c12013-09-13 03:20:53 +00002522 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002523 if (E->getConstructor()->isCopyConstructor()) {
2524 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002525 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2526 if (ILE->getNumInits() == 1)
2527 ArgExpr = ILE->getInit(0);
2528 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2529 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002530 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002531 HandleValue(ArgExpr, false /*AddressOf*/);
2532 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002533 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002534 Inherited::VisitCXXConstructExpr(E);
2535 }
2536
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002537 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2538 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002539 if (isa<MemberExpr>(Callee)) {
2540 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002541 for (auto Arg : E->arguments())
2542 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002543 return;
2544 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002545
2546 Inherited::VisitCXXMemberCallExpr(E);
2547 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002548
Richard Trieu11fd0792014-08-26 04:30:55 +00002549 void VisitCallExpr(CallExpr *E) {
2550 // Treat std::move as a use.
2551 if (E->getNumArgs() == 1) {
2552 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002553 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2554 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002555 HandleValue(E->getArg(0), false /*AddressOf*/);
2556 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002557 }
2558 }
2559 }
2560
2561 Inherited::VisitCallExpr(E);
2562 }
2563
Richard Trieud4a01362014-10-31 21:10:22 +00002564 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2565 Expr *Callee = E->getCallee();
2566
2567 if (isa<UnresolvedLookupExpr>(Callee))
2568 return Inherited::VisitCXXOperatorCallExpr(E);
2569
2570 Visit(Callee);
2571 for (auto Arg : E->arguments())
2572 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2573 }
2574
Richard Trieu406e65c2013-09-20 03:03:06 +00002575 void VisitBinaryOperator(BinaryOperator *E) {
2576 // If a field assignment is detected, remove the field from the
2577 // uninitiailized field set.
2578 if (E->getOpcode() == BO_Assign)
2579 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2580 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002581 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002582 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002583
Richard Trieu52b8b602014-09-25 01:15:40 +00002584 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002585 HandleValue(E->getLHS(), false /*AddressOf*/);
2586 Visit(E->getRHS());
2587 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002588 }
2589
Richard Trieu406e65c2013-09-20 03:03:06 +00002590 Inherited::VisitBinaryOperator(E);
2591 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002592
2593 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002594 if (E->isIncrementDecrementOp()) {
2595 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2596 return;
2597 }
2598 if (E->getOpcode() == UO_AddrOf) {
2599 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2600 HandleValue(ME->getBase(), true /*AddressOf*/);
2601 return;
2602 }
2603 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002604
2605 Inherited::VisitUnaryOperator(E);
2606 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002607 };
Richard Trieuef64e942013-10-25 00:56:00 +00002608
2609 // Diagnose value-uses of fields to initialize themselves, e.g.
2610 // foo(foo)
2611 // where foo is not also a parameter to the constructor.
2612 // Also diagnose across field uninitialized use such as
2613 // x(y), y(x)
2614 // TODO: implement -Wuninitialized and fold this into that framework.
2615 static void DiagnoseUninitializedFields(
2616 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2617
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002618 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2619 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002620 return;
2621 }
2622
2623 if (Constructor->isInvalidDecl())
2624 return;
2625
2626 const CXXRecordDecl *RD = Constructor->getParent();
2627
Richard Trieu353a4b42014-10-22 05:21:59 +00002628 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002629 return;
2630
Richard Trieuef64e942013-10-25 00:56:00 +00002631 // Holds fields that are uninitialized.
2632 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2633
2634 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002635 for (auto *I : RD->decls()) {
2636 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002637 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002638 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002639 UninitializedFields.insert(IFD->getAnonField());
2640 }
2641 }
2642
Richard Trieu3630c392014-11-21 03:10:30 +00002643 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2644 for (auto I : RD->bases())
2645 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2646
2647 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002648 return;
2649
2650 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002651 UninitializedFields,
2652 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002653
Aaron Ballman0ad78302014-03-13 17:34:31 +00002654 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002655 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002656 break;
2657
Aaron Ballman0ad78302014-03-13 17:34:31 +00002658 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002659 if (!InitExpr)
2660 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002661
Richard Trieu8d08a272014-08-28 03:23:47 +00002662 if (CXXDefaultInitExpr *Default =
2663 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2664 InitExpr = Default->getExpr();
2665 if (!InitExpr)
2666 continue;
2667 // In class initializers will point to the constructor.
2668 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002669 FieldInit->getAnyMember(),
2670 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002671 } else {
2672 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002673 FieldInit->getAnyMember(),
2674 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002675 }
Richard Trieuef64e942013-10-25 00:56:00 +00002676 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002677 }
2678} // namespace
2679
Richard Smith74108172014-01-17 03:11:34 +00002680/// \brief Enter a new C++ default initializer scope. After calling this, the
2681/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2682/// parsing or instantiating the initializer failed.
2683void Sema::ActOnStartCXXInClassMemberInitializer() {
2684 // Create a synthetic function scope to represent the call to the constructor
2685 // that notionally surrounds a use of this initializer.
2686 PushFunctionScope();
2687}
2688
2689/// \brief This is invoked after parsing an in-class initializer for a
2690/// non-static C++ class member, and after instantiating an in-class initializer
2691/// in a class template. Such actions are deferred until the class is complete.
2692void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2693 SourceLocation InitLoc,
2694 Expr *InitExpr) {
2695 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002696 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002697
David Majnemer87ff66c2014-12-13 11:34:16 +00002698 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2699 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002700 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002701
2702 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002703 D->setInvalidDecl();
2704 if (FD)
2705 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002706 return;
2707 }
2708
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002709 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2710 FD->setInvalidDecl();
2711 FD->removeInClassInitializer();
2712 return;
2713 }
2714
Richard Smith938f40b2011-06-11 17:19:42 +00002715 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002716 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002717 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002718 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002719 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002720 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002721 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2722 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002723 if (Init.isInvalid()) {
2724 FD->setInvalidDecl();
2725 return;
2726 }
Richard Smith938f40b2011-06-11 17:19:42 +00002727 }
2728
Richard Smith945f8d32013-01-14 22:39:08 +00002729 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002730 // The initialization of each base and member constitutes a
2731 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002732 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002733 if (Init.isInvalid()) {
2734 FD->setInvalidDecl();
2735 return;
2736 }
2737
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002738 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002739
2740 FD->setInClassInitializer(InitExpr);
2741}
2742
Douglas Gregor15e77a22009-12-31 09:10:24 +00002743/// \brief Find the direct and/or virtual base specifiers that
2744/// correspond to the given base type, for use in base initialization
2745/// within a constructor.
2746static bool FindBaseInitializer(Sema &SemaRef,
2747 CXXRecordDecl *ClassDecl,
2748 QualType BaseType,
2749 const CXXBaseSpecifier *&DirectBaseSpec,
2750 const CXXBaseSpecifier *&VirtualBaseSpec) {
2751 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002752 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002753 for (const auto &Base : ClassDecl->bases()) {
2754 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002755 // We found a direct base of this type. That's what we're
2756 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002757 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002758 break;
2759 }
2760 }
2761
2762 // Check for a virtual base class.
2763 // FIXME: We might be able to short-circuit this if we know in advance that
2764 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002765 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002766 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2767 // We haven't found a base yet; search the class hierarchy for a
2768 // virtual base class.
2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002771 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2772 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00002773 BaseType, Paths)) {
2774 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2775 Path != Paths.end(); ++Path) {
2776 if (Path->back().Base->isVirtual()) {
2777 VirtualBaseSpec = Path->back().Base;
2778 break;
2779 }
2780 }
2781 }
2782 }
2783
2784 return DirectBaseSpec || VirtualBaseSpec;
2785}
2786
Sebastian Redla74948d2011-09-24 17:48:25 +00002787/// \brief Handle a C++ member initializer using braced-init-list syntax.
2788MemInitResult
2789Sema::ActOnMemInitializer(Decl *ConstructorD,
2790 Scope *S,
2791 CXXScopeSpec &SS,
2792 IdentifierInfo *MemberOrBase,
2793 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002794 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002795 SourceLocation IdLoc,
2796 Expr *InitList,
2797 SourceLocation EllipsisLoc) {
2798 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002799 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002800 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002801}
2802
2803/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002804MemInitResult
John McCall48871652010-08-21 09:40:31 +00002805Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002806 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002807 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002808 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002809 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002810 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002811 SourceLocation IdLoc,
2812 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002813 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002814 SourceLocation RParenLoc,
2815 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002816 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002817 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002818 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002819 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002820}
2821
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002822namespace {
2823
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002824// Callback to only accept typo corrections that can be a valid C++ member
2825// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002826class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002827public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002828 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2829 : ClassDecl(ClassDecl) {}
2830
Craig Toppera798a9d2014-03-02 09:32:10 +00002831 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002832 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2833 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2834 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002835 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002836 }
2837 return false;
2838 }
2839
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002840private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002841 CXXRecordDecl *ClassDecl;
2842};
2843
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002844}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002845
Sebastian Redla74948d2011-09-24 17:48:25 +00002846/// \brief Handle a C++ member initializer.
2847MemInitResult
2848Sema::BuildMemInitializer(Decl *ConstructorD,
2849 Scope *S,
2850 CXXScopeSpec &SS,
2851 IdentifierInfo *MemberOrBase,
2852 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002853 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002854 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002855 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002856 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002857 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2858 if (!Res.isUsable())
2859 return true;
2860 Init = Res.get();
2861
Douglas Gregor71a57182009-06-22 23:20:33 +00002862 if (!ConstructorD)
2863 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002864
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002865 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002866
2867 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002868 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002869 if (!Constructor) {
2870 // The user wrote a constructor initializer on a function that is
2871 // not a C++ constructor. Ignore the error for now, because we may
2872 // have more member initializers coming; we'll diagnose it just
2873 // once in ActOnMemInitializers.
2874 return true;
2875 }
2876
2877 CXXRecordDecl *ClassDecl = Constructor->getParent();
2878
2879 // C++ [class.base.init]p2:
2880 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002881 // constructor's class and, if not found in that scope, are looked
2882 // up in the scope containing the constructor's definition.
2883 // [Note: if the constructor's class contains a member with the
2884 // same name as a direct or virtual base class of the class, a
2885 // mem-initializer-id naming the member or base class and composed
2886 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002887 // mem-initializer-id for the hidden base class may be specified
2888 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002889 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002890 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002891 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002892 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002893 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002894 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2895 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002896 if (EllipsisLoc.isValid())
2897 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002898 << MemberOrBase
2899 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002900
Sebastian Redla9351792012-02-11 23:51:47 +00002901 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002902 }
Francois Pichetd583da02010-12-04 09:14:42 +00002903 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002904 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002905 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002906 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002907 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002908
2909 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002910 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002911 } else if (DS.getTypeSpecType() == TST_decltype) {
2912 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002913 } else {
2914 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2915 LookupParsedName(R, S, &SS);
2916
2917 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2918 if (!TyD) {
2919 if (R.isAmbiguous()) return true;
2920
John McCallda6841b2010-04-09 19:01:14 +00002921 // We don't want access-control diagnostics here.
2922 R.suppressDiagnostics();
2923
Douglas Gregora3b624a2010-01-19 06:46:48 +00002924 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2925 bool NotUnknownSpecialization = false;
2926 DeclContext *DC = computeDeclContext(SS, false);
2927 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2928 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2929
2930 if (!NotUnknownSpecialization) {
2931 // When the scope specifier can refer to a member of an unknown
2932 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002933 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2934 SS.getWithLocInContext(Context),
2935 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002936 if (BaseType.isNull())
2937 return true;
2938
Douglas Gregora3b624a2010-01-19 06:46:48 +00002939 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002940 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002941 }
2942 }
2943
Douglas Gregor15e77a22009-12-31 09:10:24 +00002944 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002945 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002946 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002947 (Corr = CorrectTypo(
2948 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2949 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2950 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002951 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002952 // We have found a non-static data member with a similar
2953 // name to what was typed; complain and initialize that
2954 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002955 diagnoseTypo(Corr,
2956 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2957 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002958 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002959 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002960 const CXXBaseSpecifier *DirectBaseSpec;
2961 const CXXBaseSpecifier *VirtualBaseSpec;
2962 if (FindBaseInitializer(*this, ClassDecl,
2963 Context.getTypeDeclType(Type),
2964 DirectBaseSpec, VirtualBaseSpec)) {
2965 // We have found a direct or virtual base class with a
2966 // similar name to what was typed; complain and initialize
2967 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002968 diagnoseTypo(Corr,
2969 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2970 << MemberOrBase << false,
2971 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002972
Richard Smithf9b15102013-08-17 00:46:16 +00002973 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2974 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002975 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002976 diag::note_base_class_specified_here)
2977 << BaseSpec->getType()
2978 << BaseSpec->getSourceRange();
2979
Douglas Gregor15e77a22009-12-31 09:10:24 +00002980 TyD = Type;
2981 }
2982 }
2983 }
2984
Douglas Gregora3b624a2010-01-19 06:46:48 +00002985 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002986 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002987 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002988 return true;
2989 }
John McCallb5a0d312009-12-21 10:41:20 +00002990 }
2991
Douglas Gregora3b624a2010-01-19 06:46:48 +00002992 if (BaseType.isNull()) {
2993 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00002994 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00002995 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00002996 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2997 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00002998 TInfo = Context.CreateTypeSourceInfo(BaseType);
2999 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3000 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3001 TL.setElaboratedKeywordLoc(SourceLocation());
3002 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3003 }
John McCallb5a0d312009-12-21 10:41:20 +00003004 }
3005 }
Mike Stump11289f42009-09-09 15:08:12 +00003006
John McCallbcd03502009-12-07 02:54:59 +00003007 if (!TInfo)
3008 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003009
Sebastian Redla9351792012-02-11 23:51:47 +00003010 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003011}
3012
Chandler Carruth599deef2011-09-03 01:14:15 +00003013/// Checks a member initializer expression for cases where reference (or
3014/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003015static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3016 Expr *Init,
3017 SourceLocation IdLoc) {
3018 QualType MemberTy = Member->getType();
3019
3020 // We only handle pointers and references currently.
3021 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3022 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3023 return;
3024
3025 const bool IsPointer = MemberTy->isPointerType();
3026 if (IsPointer) {
3027 if (const UnaryOperator *Op
3028 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3029 // The only case we're worried about with pointers requires taking the
3030 // address.
3031 if (Op->getOpcode() != UO_AddrOf)
3032 return;
3033
3034 Init = Op->getSubExpr();
3035 } else {
3036 // We only handle address-of expression initializers for pointers.
3037 return;
3038 }
3039 }
3040
Richard Smithe3b28bc2013-06-12 21:51:50 +00003041 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003042 // We only warn when referring to a non-reference parameter declaration.
3043 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3044 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003045 return;
3046
3047 S.Diag(Init->getExprLoc(),
3048 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3049 : diag::warn_bind_ref_member_to_parameter)
3050 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003051 } else {
3052 // Other initializers are fine.
3053 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003054 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003055
3056 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3057 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003058}
3059
John McCallfaf5fb42010-08-26 23:41:50 +00003060MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003061Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003062 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003063 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3064 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3065 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003066 "Member must be a FieldDecl or IndirectFieldDecl");
3067
Sebastian Redla9351792012-02-11 23:51:47 +00003068 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003069 return true;
3070
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003071 if (Member->isInvalidDecl())
3072 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003073
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003074 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003075 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003076 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003077 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003078 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003079 } else {
3080 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003081 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003082 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003083
Sebastian Redla9351792012-02-11 23:51:47 +00003084 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003085
Sebastian Redla9351792012-02-11 23:51:47 +00003086 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003087 // Can't check initialization for a member of dependent type or when
3088 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003089 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003090 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003091 bool InitList = false;
3092 if (isa<InitListExpr>(Init)) {
3093 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003094 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003095 }
3096
Chandler Carruthd44c3102010-12-06 09:23:57 +00003097 // Initialize the member.
3098 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003099 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3100 : InitializedEntity::InitializeMember(IndirectMember,
3101 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003102 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003103 InitList ? InitializationKind::CreateDirectList(IdLoc)
3104 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3105 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003106
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003107 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003108 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3109 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003110 if (MemberInit.isInvalid())
3111 return true;
3112
Richard Smith736a9472013-06-12 20:42:33 +00003113 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3114
Richard Smith945f8d32013-01-14 22:39:08 +00003115 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003116 // The initialization of each base and member constitutes a
3117 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003118 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003119 if (MemberInit.isInvalid())
3120 return true;
3121
Richard Smithd59b8322012-12-19 01:39:02 +00003122 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003123 }
3124
Chandler Carruthd44c3102010-12-06 09:23:57 +00003125 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003126 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3127 InitRange.getBegin(), Init,
3128 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003129 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003130 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3131 InitRange.getBegin(), Init,
3132 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003133 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003134}
3135
John McCallfaf5fb42010-08-26 23:41:50 +00003136MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003137Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003138 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003139 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003140 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003141 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003142 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003143 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003144
Sebastian Redl0501c632012-02-12 16:37:36 +00003145 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003146 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003147 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3148 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003149 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003150 }
3151
Sebastian Redla9351792012-02-11 23:51:47 +00003152 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003153 // Initialize the object.
3154 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3155 QualType(ClassDecl->getTypeForDecl(), 0));
3156 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003157 InitList ? InitializationKind::CreateDirectList(NameLoc)
3158 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3159 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003160 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003161 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003162 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003163 if (DelegationInit.isInvalid())
3164 return true;
3165
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003166 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3167 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003168
Richard Smith945f8d32013-01-14 22:39:08 +00003169 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003170 // The initialization of each base and member constitutes a
3171 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003172 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3173 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003174 if (DelegationInit.isInvalid())
3175 return true;
3176
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003177 // If we are in a dependent context, template instantiation will
3178 // perform this type-checking again. Just save the arguments that we
3179 // received in a ParenListExpr.
3180 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3181 // of the information that we have about the base
3182 // initializer. However, deconstructing the ASTs is a dicey process,
3183 // and this approach is far more likely to get the corner cases right.
3184 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003185 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003186
Sebastian Redla9351792012-02-11 23:51:47 +00003187 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003188 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003189 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003190}
3191
3192MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003193Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003194 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003195 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003196 SourceLocation BaseLoc
3197 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003198
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003199 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3200 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3201 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3202
3203 // C++ [class.base.init]p2:
3204 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003205 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003206 // of that class, the mem-initializer is ill-formed. A
3207 // mem-initializer-list can initialize a base class using any
3208 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003209 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003210
Sebastian Redla9351792012-02-11 23:51:47 +00003211 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003212 if (EllipsisLoc.isValid()) {
3213 // This is a pack expansion.
3214 if (!BaseType->containsUnexpandedParameterPack()) {
3215 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003216 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003217
Douglas Gregor44e7df62011-01-04 00:32:56 +00003218 EllipsisLoc = SourceLocation();
3219 }
3220 } else {
3221 // Check for any unexpanded parameter packs.
3222 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3223 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003224
Sebastian Redla9351792012-02-11 23:51:47 +00003225 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003226 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003227 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003228
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003229 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003230 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3231 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003232 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003233 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3234 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003235 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003236
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003237 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3238 VirtualBaseSpec);
3239
3240 // C++ [base.class.init]p2:
3241 // Unless the mem-initializer-id names a nonstatic data member of the
3242 // constructor's class or a direct or virtual base of that class, the
3243 // mem-initializer is ill-formed.
3244 if (!DirectBaseSpec && !VirtualBaseSpec) {
3245 // If the class has any dependent bases, then it's possible that
3246 // one of those types will resolve to the same type as
3247 // BaseType. Therefore, just treat this as a dependent base
3248 // class initialization. FIXME: Should we try to check the
3249 // initialization anyway? It seems odd.
3250 if (ClassDecl->hasAnyDependentBases())
3251 Dependent = true;
3252 else
3253 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3254 << BaseType << Context.getTypeDeclType(ClassDecl)
3255 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3256 }
3257 }
3258
3259 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003260 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003261
Sebastian Redla74948d2011-09-24 17:48:25 +00003262 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3263 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003264 InitRange.getBegin(), Init,
3265 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003266 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003267
3268 // C++ [base.class.init]p2:
3269 // If a mem-initializer-id is ambiguous because it designates both
3270 // a direct non-virtual base class and an inherited virtual base
3271 // class, the mem-initializer is ill-formed.
3272 if (DirectBaseSpec && VirtualBaseSpec)
3273 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003274 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003275
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003276 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003277 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003278 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003279
3280 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003281 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003282 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003283 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003284 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003285 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003286 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003287
3288 InitializedEntity BaseEntity =
3289 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3290 InitializationKind Kind =
3291 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3292 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3293 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003294 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003295 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003296 if (BaseInit.isInvalid())
3297 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003298
Richard Smith945f8d32013-01-14 22:39:08 +00003299 // C++11 [class.base.init]p7:
3300 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003301 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003302 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003303 if (BaseInit.isInvalid())
3304 return true;
3305
3306 // If we are in a dependent context, template instantiation will
3307 // perform this type-checking again. Just save the arguments that we
3308 // received in a ParenListExpr.
3309 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3310 // of the information that we have about the base
3311 // initializer. However, deconstructing the ASTs is a dicey process,
3312 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003313 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003314 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003315
Alexis Hunt1d792652011-01-08 20:30:50 +00003316 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003317 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003318 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003319 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003320 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003321}
3322
Sebastian Redl22653ba2011-08-30 19:58:05 +00003323// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003324static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3325 if (T.isNull()) T = E->getType();
3326 QualType TargetType = SemaRef.BuildReferenceType(
3327 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003328 SourceLocation ExprLoc = E->getLocStart();
3329 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3330 TargetType, ExprLoc);
3331
3332 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3333 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003334 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003335}
3336
Anders Carlsson1b00e242010-04-23 03:10:23 +00003337/// ImplicitInitializerKind - How an implicit base or member initializer should
3338/// initialize its base or member.
3339enum ImplicitInitializerKind {
3340 IIK_Default,
3341 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003342 IIK_Move,
3343 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003344};
3345
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003346static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003347BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003348 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003349 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003350 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003351 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003352 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003353 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3354 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003355
John McCalldadc5752010-08-24 06:29:42 +00003356 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003357
3358 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003359 case IIK_Inherit: {
3360 const CXXRecordDecl *Inherited =
3361 Constructor->getInheritedConstructor()->getParent();
3362 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3363 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3364 // C++11 [class.inhctor]p8:
3365 // Each expression in the expression-list is of the form
3366 // static_cast<T&&>(p), where p is the name of the corresponding
3367 // constructor parameter and T is the declared type of p.
3368 SmallVector<Expr*, 16> Args;
3369 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3370 ParmVarDecl *PD = Constructor->getParamDecl(I);
3371 ExprResult ArgExpr =
3372 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3373 VK_LValue, SourceLocation());
3374 if (ArgExpr.isInvalid())
3375 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003376 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003377 }
3378
3379 InitializationKind InitKind = InitializationKind::CreateDirect(
3380 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003381 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003382 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3383 break;
3384 }
3385 }
3386 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003387 case IIK_Default: {
3388 InitializationKind InitKind
3389 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003390 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3391 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003392 break;
3393 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003394
Sebastian Redl22653ba2011-08-30 19:58:05 +00003395 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003396 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003397 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003398 ParmVarDecl *Param = Constructor->getParamDecl(0);
3399 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003400
Anders Carlsson1b00e242010-04-23 03:10:23 +00003401 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003402 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003403 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003404 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003405 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003406
Eli Friedmanfa0df832012-02-02 03:46:19 +00003407 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3408
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003409 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003410 QualType ArgTy =
3411 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3412 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003413
Sebastian Redl22653ba2011-08-30 19:58:05 +00003414 if (Moving) {
3415 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3416 }
3417
John McCallcf142162010-08-07 06:22:56 +00003418 CXXCastPath BasePath;
3419 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003420 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3421 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003422 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003423 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003424
Anders Carlsson1b00e242010-04-23 03:10:23 +00003425 InitializationKind InitKind
3426 = InitializationKind::CreateDirect(Constructor->getLocation(),
3427 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003428 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3429 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003430 break;
3431 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003432 }
John McCallb268a282010-08-23 23:25:46 +00003433
Douglas Gregora40433a2010-12-07 00:41:46 +00003434 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003435 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003436 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003437
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003438 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003439 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003440 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3441 SourceLocation()),
3442 BaseSpec->isVirtual(),
3443 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003444 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003445 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003446 SourceLocation());
3447
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003448 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003449}
3450
Sebastian Redl22653ba2011-08-30 19:58:05 +00003451static bool RefersToRValueRef(Expr *MemRef) {
3452 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3453 return Referenced->getType()->isRValueReferenceType();
3454}
3455
Anders Carlsson3c1db572010-04-23 02:15:47 +00003456static bool
3457BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003458 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003459 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003460 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003461 if (Field->isInvalidDecl())
3462 return true;
3463
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003464 SourceLocation Loc = Constructor->getLocation();
3465
Sebastian Redl22653ba2011-08-30 19:58:05 +00003466 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3467 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003468 ParmVarDecl *Param = Constructor->getParamDecl(0);
3469 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003470
3471 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003472 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3473 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003474
Anders Carlsson423f5d82010-04-23 16:04:08 +00003475 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003476 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003477 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003478 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003479
Eli Friedmanfa0df832012-02-02 03:46:19 +00003480 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3481
Sebastian Redl22653ba2011-08-30 19:58:05 +00003482 if (Moving) {
3483 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3484 }
3485
Douglas Gregor94f9a482010-05-05 05:51:00 +00003486 // Build a reference to this field within the parameter.
3487 CXXScopeSpec SS;
3488 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3489 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003490 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3491 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003492 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003493 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003494 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003495 ParamType, Loc,
3496 /*IsArrow=*/false,
3497 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003498 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003499 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003500 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00003501 /*TemplateArgs=*/nullptr,
3502 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003503 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003504 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003505
3506 // C++11 [class.copy]p15:
3507 // - if a member m has rvalue reference type T&&, it is direct-initialized
3508 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003509 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003510 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003511 }
3512
Douglas Gregor94f9a482010-05-05 05:51:00 +00003513 // When the field we are copying is an array, create index variables for
3514 // each dimension of the array. We use these index variables to subscript
3515 // the source array, and other clients (e.g., CodeGen) will perform the
3516 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003517 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003518 QualType BaseType = Field->getType();
3519 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003520 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003521 while (const ConstantArrayType *Array
3522 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003523 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003524 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003525 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003526 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003527 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003528 llvm::raw_svector_ostream OS(Str);
3529 OS << "__i" << IndexVariables.size();
3530 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3531 }
3532 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003533 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003534 IterationVarName, SizeType,
3535 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003536 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003537 IndexVariables.push_back(IterationVar);
3538
3539 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003540 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003541 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003542 assert(!IterationVarRef.isInvalid() &&
3543 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003544 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003545 assert(!IterationVarRef.isInvalid() &&
3546 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003547
Douglas Gregor94f9a482010-05-05 05:51:00 +00003548 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003549 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3550 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003551 Loc);
3552 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003553 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003554
Douglas Gregor94f9a482010-05-05 05:51:00 +00003555 BaseType = Array->getElementType();
3556 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003557
3558 // The array subscript expression is an lvalue, which is wrong for moving.
3559 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003560 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003561
Douglas Gregor94f9a482010-05-05 05:51:00 +00003562 // Construct the entity that we will be initializing. For an array, this
3563 // will be first element in the array, which may require several levels
3564 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003565 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003566 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003567 if (Indirect)
3568 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3569 else
3570 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003571 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3572 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3573 0,
3574 Entities.back()));
3575
3576 // Direct-initialize to use the copy constructor.
3577 InitializationKind InitKind =
3578 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3579
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003580 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00003581 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3582 CtorArgE);
3583
John McCalldadc5752010-08-24 06:29:42 +00003584 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003585 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003586 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003587 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003588 if (MemberInit.isInvalid())
3589 return true;
3590
Douglas Gregor493627b2011-08-10 15:22:55 +00003591 if (Indirect) {
3592 assert(IndexVariables.size() == 0 &&
3593 "Indirect field improperly initialized");
3594 CXXMemberInit
3595 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3596 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003597 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003598 Loc);
3599 } else
3600 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003601 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003602 Loc,
3603 IndexVariables.data(),
3604 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003605 return false;
3606 }
3607
Richard Smithc2bc61b2013-03-18 21:12:30 +00003608 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3609 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003610
Anders Carlsson3c1db572010-04-23 02:15:47 +00003611 QualType FieldBaseElementType =
3612 SemaRef.Context.getBaseElementType(Field->getType());
3613
Anders Carlsson3c1db572010-04-23 02:15:47 +00003614 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003615 InitializedEntity InitEntity
3616 = Indirect? InitializedEntity::InitializeMember(Indirect)
3617 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003618 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003619 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003620
3621 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3622 ExprResult MemberInit =
3623 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003624
Douglas Gregora40433a2010-12-07 00:41:46 +00003625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003626 if (MemberInit.isInvalid())
3627 return true;
3628
Douglas Gregor493627b2011-08-10 15:22:55 +00003629 if (Indirect)
3630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3631 Indirect, Loc,
3632 Loc,
3633 MemberInit.get(),
3634 Loc);
3635 else
3636 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3637 Field, Loc, Loc,
3638 MemberInit.get(),
3639 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003640 return false;
3641 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003642
Alexis Hunt8b455182011-05-17 00:19:05 +00003643 if (!Field->getParent()->isUnion()) {
3644 if (FieldBaseElementType->isReferenceType()) {
3645 SemaRef.Diag(Constructor->getLocation(),
3646 diag::err_uninitialized_member_in_ctor)
3647 << (int)Constructor->isImplicit()
3648 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3649 << 0 << Field->getDeclName();
3650 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3651 return true;
3652 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003653
Alexis Hunt8b455182011-05-17 00:19:05 +00003654 if (FieldBaseElementType.isConstQualified()) {
3655 SemaRef.Diag(Constructor->getLocation(),
3656 diag::err_uninitialized_member_in_ctor)
3657 << (int)Constructor->isImplicit()
3658 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3659 << 1 << Field->getDeclName();
3660 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3661 return true;
3662 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003663 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003664
David Blaikiebbafb8a2012-03-11 07:00:24 +00003665 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003666 FieldBaseElementType->isObjCRetainableType() &&
3667 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3668 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003669 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003670 // Default-initialize Objective-C pointers to NULL.
3671 CXXMemberInit
3672 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3673 Loc, Loc,
3674 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3675 Loc);
3676 return false;
3677 }
3678
Anders Carlsson3c1db572010-04-23 02:15:47 +00003679 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003680 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003681 return false;
3682}
John McCallbc83b3f2010-05-20 23:23:51 +00003683
3684namespace {
3685struct BaseAndFieldInfo {
3686 Sema &S;
3687 CXXConstructorDecl *Ctor;
3688 bool AnyErrorsInInits;
3689 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003690 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003691 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003692 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003693
3694 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3695 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003696 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3697 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003698 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003699 else if (Generated && Ctor->isMoveConstructor())
3700 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003701 else if (Ctor->getInheritedConstructor())
3702 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003703 else
3704 IIK = IIK_Default;
3705 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003706
3707 bool isImplicitCopyOrMove() const {
3708 switch (IIK) {
3709 case IIK_Copy:
3710 case IIK_Move:
3711 return true;
3712
3713 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003714 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003715 return false;
3716 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003717
3718 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003719 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003720
3721 bool addFieldInitializer(CXXCtorInitializer *Init) {
3722 AllToInit.push_back(Init);
3723
3724 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003725 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003726 S.UnusedPrivateFields.remove(Init->getAnyMember());
3727
3728 return false;
3729 }
John McCallbc83b3f2010-05-20 23:23:51 +00003730
Richard Smithab44d5b2013-12-10 08:25:00 +00003731 bool isInactiveUnionMember(FieldDecl *Field) {
3732 RecordDecl *Record = Field->getParent();
3733 if (!Record->isUnion())
3734 return false;
3735
Richard Smith8d183852013-12-10 20:56:03 +00003736 if (FieldDecl *Active =
3737 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003738 return Active != Field->getCanonicalDecl();
3739
3740 // In an implicit copy or move constructor, ignore any in-class initializer.
3741 if (isImplicitCopyOrMove())
3742 return true;
3743
3744 // If there's no explicit initialization, the field is active only if it
3745 // has an in-class initializer...
3746 if (Field->hasInClassInitializer())
3747 return false;
3748 // ... or it's an anonymous struct or union whose class has an in-class
3749 // initializer.
3750 if (!Field->isAnonymousStructOrUnion())
3751 return true;
3752 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3753 return !FieldRD->hasInClassInitializer();
3754 }
3755
3756 /// \brief Determine whether the given field is, or is within, a union member
3757 /// that is inactive (because there was an initializer given for a different
3758 /// member of the union, or because the union was not initialized at all).
3759 bool isWithinInactiveUnionMember(FieldDecl *Field,
3760 IndirectFieldDecl *Indirect) {
3761 if (!Indirect)
3762 return isInactiveUnionMember(Field);
3763
Aaron Ballman29c94602014-03-07 18:36:15 +00003764 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003765 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003766 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003767 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003768 }
3769 return false;
3770 }
3771};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003772}
Richard Smithc94ec842011-09-19 13:34:43 +00003773
Douglas Gregor10f939c2011-11-02 23:04:16 +00003774/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3775/// array type.
3776static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3777 if (T->isIncompleteArrayType())
3778 return true;
3779
3780 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3781 if (!ArrayT->getSize())
3782 return true;
3783
3784 T = ArrayT->getElementType();
3785 }
3786
3787 return false;
3788}
3789
Richard Smith938f40b2011-06-11 17:19:42 +00003790static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003791 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003792 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003793 if (Field->isInvalidDecl())
3794 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003795
Chandler Carruth139e9622010-06-30 02:59:29 +00003796 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003797 if (CXXCtorInitializer *Init =
3798 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003799 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003800
Richard Smithab44d5b2013-12-10 08:25:00 +00003801 // C++11 [class.base.init]p8:
3802 // if the entity is a non-static data member that has a
3803 // brace-or-equal-initializer and either
3804 // -- the constructor's class is a union and no other variant member of that
3805 // union is designated by a mem-initializer-id or
3806 // -- the constructor's class is not a union, and, if the entity is a member
3807 // of an anonymous union, no other member of that union is designated by
3808 // a mem-initializer-id,
3809 // the entity is initialized as specified in [dcl.init].
3810 //
3811 // We also apply the same rules to handle anonymous structs within anonymous
3812 // unions.
3813 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3814 return false;
3815
Douglas Gregor7db3e952011-11-28 20:03:15 +00003816 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003817 ExprResult DIE =
3818 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3819 if (DIE.isInvalid())
3820 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003821 CXXCtorInitializer *Init;
3822 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003823 Init = new (SemaRef.Context)
3824 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3825 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003826 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003827 Init = new (SemaRef.Context)
3828 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3829 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003830 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003831 }
3832
Douglas Gregor10f939c2011-11-02 23:04:16 +00003833 // Don't initialize incomplete or zero-length arrays.
3834 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3835 return false;
3836
John McCallbc83b3f2010-05-20 23:23:51 +00003837 // Don't try to build an implicit initializer if there were semantic
3838 // errors in any of the initializers (and therefore we might be
3839 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003840 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003841 return false;
3842
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003844 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3845 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003846 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003847
Richard Smith0a8cfc72012-08-07 21:30:42 +00003848 if (!Init)
3849 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003850
Richard Smith0a8cfc72012-08-07 21:30:42 +00003851 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003852}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003853
3854bool
3855Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3856 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003857 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003858 Constructor->setNumCtorInitializers(1);
3859 CXXCtorInitializer **initializer =
3860 new (Context) CXXCtorInitializer*[1];
3861 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3862 Constructor->setCtorInitializers(initializer);
3863
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003864 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003865 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003866 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3867 }
3868
Alexis Hunte2622992011-05-05 00:05:47 +00003869 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003870
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003871 DiagnoseUninitializedFields(*this, Constructor);
3872
Alexis Hunt61bc1732011-05-01 07:04:31 +00003873 return false;
3874}
Douglas Gregor493627b2011-08-10 15:22:55 +00003875
David Blaikie3fc2f912013-01-17 05:26:25 +00003876bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3877 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003878 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003879 // Just store the initializers as written, they will be checked during
3880 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003881 if (!Initializers.empty()) {
3882 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003883 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003884 new (Context) CXXCtorInitializer*[Initializers.size()];
3885 memcpy(baseOrMemberInitializers, Initializers.data(),
3886 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003887 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003888 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003889
3890 // Let template instantiation know whether we had errors.
3891 if (AnyErrors)
3892 Constructor->setInvalidDecl();
3893
Anders Carlssondb0a9652010-04-02 06:26:44 +00003894 return false;
3895 }
3896
John McCallbc83b3f2010-05-20 23:23:51 +00003897 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003898
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003899 // We need to build the initializer AST according to order of construction
3900 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003901 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003902 if (!ClassDecl)
3903 return true;
3904
Eli Friedman9cf6b592009-11-09 19:20:36 +00003905 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003906
David Blaikie3fc2f912013-01-17 05:26:25 +00003907 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003908 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003909
Anders Carlssondb0a9652010-04-02 06:26:44 +00003910 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003911 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003912 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003913 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003914
3915 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003916 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003917 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003918 if (FD && FD->getParent()->isUnion())
3919 Info.ActiveUnionMember.insert(std::make_pair(
3920 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3921 }
3922 } else if (FieldDecl *FD = Member->getMember()) {
3923 if (FD->getParent()->isUnion())
3924 Info.ActiveUnionMember.insert(std::make_pair(
3925 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3926 }
3927 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003928 }
3929
Anders Carlsson43c64af2010-04-21 19:52:01 +00003930 // Keep track of the direct virtual bases.
3931 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003932 for (auto &I : ClassDecl->bases()) {
3933 if (I.isVirtual())
3934 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003935 }
3936
Anders Carlssondb0a9652010-04-02 06:26:44 +00003937 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003938 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003939 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003940 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003941 // [class.base.init]p7, per DR257:
3942 // A mem-initializer where the mem-initializer-id names a virtual base
3943 // class is ignored during execution of a constructor of any class that
3944 // is not the most derived class.
3945 if (ClassDecl->isAbstract()) {
3946 // FIXME: Provide a fixit to remove the base specifier. This requires
3947 // tracking the location of the associated comma for a base specifier.
3948 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003949 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003950 DiagnoseAbstractType(ClassDecl);
3951 }
3952
John McCallbc83b3f2010-05-20 23:23:51 +00003953 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003954 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3955 // [class.base.init]p8, per DR257:
3956 // If a given [...] base class is not named by a mem-initializer-id
3957 // [...] and the entity is not a virtual base class of an abstract
3958 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003959 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003960 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003961 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003962 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003963 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003964 HadError = true;
3965 continue;
3966 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003967
John McCallbc83b3f2010-05-20 23:23:51 +00003968 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003969 }
3970 }
Mike Stump11289f42009-09-09 15:08:12 +00003971
John McCallbc83b3f2010-05-20 23:23:51 +00003972 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003973 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003974 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003975 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003976 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Alexis Hunt1d792652011-01-08 20:30:50 +00003978 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003979 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003980 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003981 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003982 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003983 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003984 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003985 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003986 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003987 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003988 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003989
John McCallbc83b3f2010-05-20 23:23:51 +00003990 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003991 }
3992 }
Mike Stump11289f42009-09-09 15:08:12 +00003993
John McCallbc83b3f2010-05-20 23:23:51 +00003994 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003995 for (auto *Mem : ClassDecl->decls()) {
3996 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003997 // C++ [class.bit]p2:
3998 // A declaration for a bit-field that omits the identifier declares an
3999 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4000 // initialized.
4001 if (F->isUnnamedBitfield())
4002 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004003
Sebastian Redl22653ba2011-08-30 19:58:05 +00004004 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004005 // handle anonymous struct/union fields based on their individual
4006 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004007 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004008 continue;
4009
4010 if (CollectFieldInitializer(*this, Info, F))
4011 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004012 continue;
4013 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004014
4015 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004016 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004017 continue;
4018
Aaron Ballman629afae2014-03-07 19:56:05 +00004019 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004020 if (F->getType()->isIncompleteArrayType()) {
4021 assert(ClassDecl->hasFlexibleArrayMember() &&
4022 "Incomplete array type is not valid");
4023 continue;
4024 }
4025
Douglas Gregor493627b2011-08-10 15:22:55 +00004026 // Initialize each field of an anonymous struct individually.
4027 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4028 HadError = true;
4029
4030 continue;
4031 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004032 }
Mike Stump11289f42009-09-09 15:08:12 +00004033
David Blaikie3fc2f912013-01-17 05:26:25 +00004034 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004035 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004036 Constructor->setNumCtorInitializers(NumInitializers);
4037 CXXCtorInitializer **baseOrMemberInitializers =
4038 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004039 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004040 NumInitializers * sizeof(CXXCtorInitializer*));
4041 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004042
John McCalla6309952010-03-16 21:39:52 +00004043 // Constructors implicitly reference the base and member
4044 // destructors.
4045 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4046 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004047 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004048
4049 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004050}
4051
David Blaikieb61b8152013-01-17 08:49:22 +00004052static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004053 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004054 const RecordDecl *RD = RT->getDecl();
4055 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004056 for (auto *Field : RD->fields())
4057 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004058 return;
4059 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004060 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004061 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004062}
4063
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004064static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4065 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004066}
4067
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004068static const void *GetKeyForMember(ASTContext &Context,
4069 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004070 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004071 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004072
Richard Smithcd45dbc2014-04-19 03:48:30 +00004073 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004074}
4075
David Blaikie3fc2f912013-01-17 05:26:25 +00004076static void DiagnoseBaseOrMemInitializerOrder(
4077 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4078 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004079 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004080 return;
Mike Stump11289f42009-09-09 15:08:12 +00004081
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004082 // Don't check initializers order unless the warning is enabled at the
4083 // location of at least one initializer.
4084 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004085 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004086 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004087 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4088 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004089 ShouldCheckOrder = true;
4090 break;
4091 }
4092 }
4093 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004094 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004095
John McCallbb7b6582010-04-10 07:37:23 +00004096 // Build the list of bases and members in the order that they'll
4097 // actually be initialized. The explicit initializers should be in
4098 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004099 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004100
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004101 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4102
John McCallbb7b6582010-04-10 07:37:23 +00004103 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004104 for (const auto &VBase : ClassDecl->vbases())
4105 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004106
John McCallbb7b6582010-04-10 07:37:23 +00004107 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004108 for (const auto &Base : ClassDecl->bases()) {
4109 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004110 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004111 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004112 }
Mike Stump11289f42009-09-09 15:08:12 +00004113
John McCallbb7b6582010-04-10 07:37:23 +00004114 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004115 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004116 if (Field->isUnnamedBitfield())
4117 continue;
4118
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004119 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004120 }
4121
John McCallbb7b6582010-04-10 07:37:23 +00004122 unsigned NumIdealInits = IdealInitKeys.size();
4123 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004124
Craig Topperc3ec1492014-05-26 06:22:03 +00004125 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004126 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004127 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004128 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004129
4130 // Scan forward to try to find this initializer in the idealized
4131 // initializers list.
4132 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4133 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004134 break;
John McCallbb7b6582010-04-10 07:37:23 +00004135
4136 // If we didn't find this initializer, it must be because we
4137 // scanned past it on a previous iteration. That can only
4138 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004139 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004140 Sema::SemaDiagnosticBuilder D =
4141 SemaRef.Diag(PrevInit->getSourceLocation(),
4142 diag::warn_initializer_out_of_order);
4143
Francois Pichetd583da02010-12-04 09:14:42 +00004144 if (PrevInit->isAnyMemberInitializer())
4145 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004146 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004147 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004148
Francois Pichetd583da02010-12-04 09:14:42 +00004149 if (Init->isAnyMemberInitializer())
4150 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004151 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004152 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004153
4154 // Move back to the initializer's location in the ideal list.
4155 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4156 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004157 break;
John McCallbb7b6582010-04-10 07:37:23 +00004158
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004159 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004160 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004161 }
John McCallbb7b6582010-04-10 07:37:23 +00004162
4163 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004164 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004165}
4166
John McCall23eebd92010-04-10 09:28:51 +00004167namespace {
4168bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004169 CXXCtorInitializer *Init,
4170 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004171 if (!PrevInit) {
4172 PrevInit = Init;
4173 return false;
4174 }
4175
Douglas Gregorea306a12013-03-25 23:28:23 +00004176 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004177 S.Diag(Init->getSourceLocation(),
4178 diag::err_multiple_mem_initialization)
4179 << Field->getDeclName()
4180 << Init->getSourceRange();
4181 else {
John McCall424cec92011-01-19 06:33:43 +00004182 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004183 assert(BaseClass && "neither field nor base");
4184 S.Diag(Init->getSourceLocation(),
4185 diag::err_multiple_base_initialization)
4186 << QualType(BaseClass, 0)
4187 << Init->getSourceRange();
4188 }
4189 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4190 << 0 << PrevInit->getSourceRange();
4191
4192 return true;
4193}
4194
Alexis Hunt1d792652011-01-08 20:30:50 +00004195typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004196typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4197
4198bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004199 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004200 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004201 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004202 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004203 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004204
4205 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004206 if (Parent->isUnion()) {
4207 UnionEntry &En = Unions[Parent];
4208 if (En.first && En.first != Child) {
4209 S.Diag(Init->getSourceLocation(),
4210 diag::err_multiple_mem_union_initialization)
4211 << Field->getDeclName()
4212 << Init->getSourceRange();
4213 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4214 << 0 << En.second->getSourceRange();
4215 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004216 }
4217 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004218 En.first = Child;
4219 En.second = Init;
4220 }
David Blaikie0f65d592011-11-17 06:01:57 +00004221 if (!Parent->isAnonymousStructOrUnion())
4222 return false;
John McCall23eebd92010-04-10 09:28:51 +00004223 }
4224
4225 Child = Parent;
4226 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004227 }
John McCall23eebd92010-04-10 09:28:51 +00004228
4229 return false;
4230}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004231}
John McCall23eebd92010-04-10 09:28:51 +00004232
Anders Carlssone857b292010-04-02 03:37:03 +00004233/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004234void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004235 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004236 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004237 bool AnyErrors) {
4238 if (!ConstructorDecl)
4239 return;
4240
4241 AdjustDeclIfTemplate(ConstructorDecl);
4242
4243 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004244 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004245
4246 if (!Constructor) {
4247 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4248 return;
4249 }
4250
John McCall23eebd92010-04-10 09:28:51 +00004251 // Mapping for the duplicate initializers check.
4252 // For member initializers, this is keyed with a FieldDecl*.
4253 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004254 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004255
4256 // Mapping for the inconsistent anonymous-union initializers check.
4257 RedundantUnionMap MemberUnions;
4258
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004259 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004260 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004261 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004262
Abramo Bagnara341d7832010-05-26 18:09:23 +00004263 // Set the source order index.
4264 Init->setSourceOrder(i);
4265
Francois Pichetd583da02010-12-04 09:14:42 +00004266 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004267 const void *Key = GetKeyForMember(Context, Init);
4268 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004269 CheckRedundantUnionInit(*this, Init, MemberUnions))
4270 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004271 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004272 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004273 if (CheckRedundantInit(*this, Init, Members[Key]))
4274 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004275 } else {
4276 assert(Init->isDelegatingInitializer());
4277 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004278 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004279 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004280 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004281 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004282 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004283 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004284 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004285 // Return immediately as the initializer is set.
4286 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004287 }
Anders Carlssone857b292010-04-02 03:37:03 +00004288 }
4289
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004290 if (HadError)
4291 return;
4292
David Blaikie3fc2f912013-01-17 05:26:25 +00004293 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004294
David Blaikie3fc2f912013-01-17 05:26:25 +00004295 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004296
Richard Trieuef64e942013-10-25 00:56:00 +00004297 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004298}
4299
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004300void
John McCalla6309952010-03-16 21:39:52 +00004301Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4302 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004303 // Ignore dependent contexts. Also ignore unions, since their members never
4304 // have destructors implicitly called.
4305 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004306 return;
John McCall1064d7e2010-03-16 05:22:47 +00004307
4308 // FIXME: all the access-control diagnostics are positioned on the
4309 // field/base declaration. That's probably good; that said, the
4310 // user might reasonably want to know why the destructor is being
4311 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004312
Anders Carlssondee9a302009-11-17 04:44:12 +00004313 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004314 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004315 if (Field->isInvalidDecl())
4316 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004317
4318 // Don't destroy incomplete or zero-length arrays.
4319 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4320 continue;
4321
Anders Carlssondee9a302009-11-17 04:44:12 +00004322 QualType FieldType = Context.getBaseElementType(Field->getType());
4323
4324 const RecordType* RT = FieldType->getAs<RecordType>();
4325 if (!RT)
4326 continue;
4327
4328 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004329 if (FieldClassDecl->isInvalidDecl())
4330 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004331 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004332 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004333 // The destructor for an implicit anonymous union member is never invoked.
4334 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4335 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004336
Douglas Gregore71edda2010-07-01 22:47:18 +00004337 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004338 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004339 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004340 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004341 << Field->getDeclName()
4342 << FieldType);
4343
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004344 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004345 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004346 }
4347
John McCall1064d7e2010-03-16 05:22:47 +00004348 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4349
Anders Carlssondee9a302009-11-17 04:44:12 +00004350 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004351 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004352 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004353 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004354
4355 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004356 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004357 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004358
John McCall1064d7e2010-03-16 05:22:47 +00004359 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004360 // If our base class is invalid, we probably can't get its dtor anyway.
4361 if (BaseClassDecl->isInvalidDecl())
4362 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004363 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004364 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004365
Douglas Gregore71edda2010-07-01 22:47:18 +00004366 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004367 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004368
4369 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004370 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004371 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004372 << Base.getType()
4373 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004374 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004375
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004376 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004377 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004378 }
4379
4380 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004381 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004382 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004383 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004384
4385 // Ignore direct virtual bases.
4386 if (DirectVirtualBases.count(RT))
4387 continue;
4388
John McCall1064d7e2010-03-16 05:22:47 +00004389 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004390 // If our base class is invalid, we probably can't get its dtor anyway.
4391 if (BaseClassDecl->isInvalidDecl())
4392 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004393 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004394 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004395
Douglas Gregore71edda2010-07-01 22:47:18 +00004396 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004397 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004398 if (CheckDestructorAccess(
4399 ClassDecl->getLocation(), Dtor,
4400 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004401 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004402 Context.getTypeDeclType(ClassDecl)) ==
4403 AR_accessible) {
4404 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004405 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004406 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004407 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004408 }
John McCall1064d7e2010-03-16 05:22:47 +00004409
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004410 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004411 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004412 }
4413}
4414
John McCall48871652010-08-21 09:40:31 +00004415void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004416 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004417 return;
Mike Stump11289f42009-09-09 15:08:12 +00004418
Mike Stump11289f42009-09-09 15:08:12 +00004419 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004420 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004421 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004422 DiagnoseUninitializedFields(*this, Constructor);
4423 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004424}
4425
Richard Smithdb0ac552015-12-18 22:40:25 +00004426bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004427 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004428 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004429
Richard Smithdb0ac552015-12-18 22:40:25 +00004430 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4431 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004432 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004433
Richard Smithdb0ac552015-12-18 22:40:25 +00004434 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4435 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004436
John McCall02db245d2010-08-18 09:41:07 +00004437 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00004438 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00004439 // over all the declarations when we have a full definition.
4440 const CXXRecordDecl *Def = RD->getDefinition();
4441 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004442 return false;
4443
Richard Smithdb0ac552015-12-18 22:40:25 +00004444 return RD->isAbstract();
4445}
4446
4447bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4448 TypeDiagnoser &Diagnoser) {
4449 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004450 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004451
Richard Smithdb0ac552015-12-18 22:40:25 +00004452 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00004453 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00004454 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00004455 return true;
4456}
4457
4458void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4459 // Check if we've already emitted the list of pure virtual functions
4460 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004461 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004462 return;
Mike Stump11289f42009-09-09 15:08:12 +00004463
Richard Smithbc46e432013-07-22 02:56:56 +00004464 // If the diagnostic is suppressed, don't emit the notes. We're only
4465 // going to emit them once, so try to attach them to a diagnostic we're
4466 // actually going to show.
4467 if (Diags.isLastDiagnosticIgnored())
4468 return;
4469
Douglas Gregor4165bd62010-03-23 23:47:56 +00004470 CXXFinalOverriderMap FinalOverriders;
4471 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004472
Anders Carlssona2f74f32010-06-03 01:00:02 +00004473 // Keep a set of seen pure methods so we won't diagnose the same method
4474 // more than once.
4475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4476
Douglas Gregor4165bd62010-03-23 23:47:56 +00004477 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4478 MEnd = FinalOverriders.end();
4479 M != MEnd;
4480 ++M) {
4481 for (OverridingMethods::iterator SO = M->second.begin(),
4482 SOEnd = M->second.end();
4483 SO != SOEnd; ++SO) {
4484 // C++ [class.abstract]p4:
4485 // A class is abstract if it contains or inherits at least one
4486 // pure virtual function for which the final overrider is pure
4487 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004488
Douglas Gregor4165bd62010-03-23 23:47:56 +00004489 //
4490 if (SO->second.size() != 1)
4491 continue;
4492
4493 if (!SO->second.front().Method->isPure())
4494 continue;
4495
David Blaikie82e95a32014-11-19 07:49:47 +00004496 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004497 continue;
4498
Douglas Gregor4165bd62010-03-23 23:47:56 +00004499 Diag(SO->second.front().Method->getLocation(),
4500 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004501 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004502 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004503 }
4504
4505 if (!PureVirtualClassDiagSet)
4506 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4507 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004508}
4509
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004510namespace {
John McCall02db245d2010-08-18 09:41:07 +00004511struct AbstractUsageInfo {
4512 Sema &S;
4513 CXXRecordDecl *Record;
4514 CanQualType AbstractType;
4515 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004516
John McCall02db245d2010-08-18 09:41:07 +00004517 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4518 : S(S), Record(Record),
4519 AbstractType(S.Context.getCanonicalType(
4520 S.Context.getTypeDeclType(Record))),
4521 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004522
John McCall02db245d2010-08-18 09:41:07 +00004523 void DiagnoseAbstractType() {
4524 if (Invalid) return;
4525 S.DiagnoseAbstractType(Record);
4526 Invalid = true;
4527 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004528
John McCall02db245d2010-08-18 09:41:07 +00004529 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4530};
4531
4532struct CheckAbstractUsage {
4533 AbstractUsageInfo &Info;
4534 const NamedDecl *Ctx;
4535
4536 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4537 : Info(Info), Ctx(Ctx) {}
4538
4539 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4540 switch (TL.getTypeLocClass()) {
4541#define ABSTRACT_TYPELOC(CLASS, PARENT)
4542#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004543 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004544#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004545 }
John McCall02db245d2010-08-18 09:41:07 +00004546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547
John McCall02db245d2010-08-18 09:41:07 +00004548 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004549 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004550 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4551 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004552 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004553
4554 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004555 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004556 }
John McCall02db245d2010-08-18 09:41:07 +00004557 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004558
John McCall02db245d2010-08-18 09:41:07 +00004559 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4560 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4561 }
Mike Stump11289f42009-09-09 15:08:12 +00004562
John McCall02db245d2010-08-18 09:41:07 +00004563 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4564 // Visit the type parameters from a permissive context.
4565 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4566 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4567 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4568 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4569 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4570 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004571 }
John McCall02db245d2010-08-18 09:41:07 +00004572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
John McCall02db245d2010-08-18 09:41:07 +00004574 // Visit pointee types from a permissive context.
4575#define CheckPolymorphic(Type) \
4576 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4577 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4578 }
4579 CheckPolymorphic(PointerTypeLoc)
4580 CheckPolymorphic(ReferenceTypeLoc)
4581 CheckPolymorphic(MemberPointerTypeLoc)
4582 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004583 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004584
John McCall02db245d2010-08-18 09:41:07 +00004585 /// Handle all the types we haven't given a more specific
4586 /// implementation for above.
4587 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4588 // Every other kind of type that we haven't called out already
4589 // that has an inner type is either (1) sugar or (2) contains that
4590 // inner type in some way as a subobject.
4591 if (TypeLoc Next = TL.getNextTypeLoc())
4592 return Visit(Next, Sel);
4593
4594 // If there's no inner type and we're in a permissive context,
4595 // don't diagnose.
4596 if (Sel == Sema::AbstractNone) return;
4597
4598 // Check whether the type matches the abstract type.
4599 QualType T = TL.getType();
4600 if (T->isArrayType()) {
4601 Sel = Sema::AbstractArrayType;
4602 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004603 }
John McCall02db245d2010-08-18 09:41:07 +00004604 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4605 if (CT != Info.AbstractType) return;
4606
4607 // It matched; do some magic.
4608 if (Sel == Sema::AbstractArrayType) {
4609 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4610 << T << TL.getSourceRange();
4611 } else {
4612 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4613 << Sel << T << TL.getSourceRange();
4614 }
4615 Info.DiagnoseAbstractType();
4616 }
4617};
4618
4619void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4620 Sema::AbstractDiagSelID Sel) {
4621 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4622}
4623
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004624}
John McCall02db245d2010-08-18 09:41:07 +00004625
4626/// Check for invalid uses of an abstract type in a method declaration.
4627static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4628 CXXMethodDecl *MD) {
4629 // No need to do the check on definitions, which require that
4630 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004631 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004632 return;
4633
4634 // For safety's sake, just ignore it if we don't have type source
4635 // information. This should never happen for non-implicit methods,
4636 // but...
4637 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4638 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4639}
4640
4641/// Check for invalid uses of an abstract type within a class definition.
4642static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4643 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004644 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004645 if (D->isImplicit()) continue;
4646
4647 // Methods and method templates.
4648 if (isa<CXXMethodDecl>(D)) {
4649 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4650 } else if (isa<FunctionTemplateDecl>(D)) {
4651 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4652 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4653
4654 // Fields and static variables.
4655 } else if (isa<FieldDecl>(D)) {
4656 FieldDecl *FD = cast<FieldDecl>(D);
4657 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4658 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4659 } else if (isa<VarDecl>(D)) {
4660 VarDecl *VD = cast<VarDecl>(D);
4661 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4662 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4663
4664 // Nested classes and class templates.
4665 } else if (isa<CXXRecordDecl>(D)) {
4666 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4667 } else if (isa<ClassTemplateDecl>(D)) {
4668 CheckAbstractClassUsage(Info,
4669 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4670 }
4671 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004672}
4673
Hans Wennborg99000c22015-08-15 01:18:16 +00004674static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4675 Attr *ClassAttr = getDLLAttr(Class);
4676 if (!ClassAttr)
4677 return;
4678
4679 assert(ClassAttr->getKind() == attr::DLLExport);
4680
4681 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4682
4683 if (TSK == TSK_ExplicitInstantiationDeclaration)
4684 // Don't go any further if this is just an explicit instantiation
4685 // declaration.
4686 return;
4687
4688 for (Decl *Member : Class->decls()) {
4689 auto *MD = dyn_cast<CXXMethodDecl>(Member);
4690 if (!MD)
4691 continue;
4692
4693 if (Member->getAttr<DLLExportAttr>()) {
4694 if (MD->isUserProvided()) {
4695 // Instantiate non-default class member functions ...
4696
4697 // .. except for certain kinds of template specializations.
4698 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4699 continue;
4700
4701 S.MarkFunctionReferenced(Class->getLocation(), MD);
4702
4703 // The function will be passed to the consumer when its definition is
4704 // encountered.
4705 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4706 MD->isCopyAssignmentOperator() ||
4707 MD->isMoveAssignmentOperator()) {
4708 // Synthesize and instantiate non-trivial implicit methods, explicitly
4709 // defaulted methods, and the copy and move assignment operators. The
4710 // latter are exported even if they are trivial, because the address of
4711 // an operator can be taken and should compare equal accross libraries.
4712 DiagnosticErrorTrap Trap(S.Diags);
4713 S.MarkFunctionReferenced(Class->getLocation(), MD);
4714 if (Trap.hasErrorOccurred()) {
4715 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4716 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4717 break;
4718 }
4719
4720 // There is no later point when we will see the definition of this
4721 // function, so pass it to the consumer now.
4722 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4723 }
4724 }
4725 }
4726}
4727
Hans Wennborg853ae942014-05-30 16:59:42 +00004728/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004729void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004730 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004731
4732 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004733 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00004734 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4735 if (Attr *TemplateAttr =
4736 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004737 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00004738 A->setInherited(true);
4739 ClassAttr = A;
4740 }
4741 }
4742 }
4743
Hans Wennborg853ae942014-05-30 16:59:42 +00004744 if (!ClassAttr)
4745 return;
4746
Hans Wennborg8313c762014-11-03 16:09:16 +00004747 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004748 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00004749 << Class << ClassAttr;
4750 return;
4751 }
4752
Hans Wennborg17f9b442015-05-27 00:06:45 +00004753 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004754 !ClassAttr->isInherited()) {
4755 // Diagnose dll attributes on members of class with dll attribute.
4756 for (Decl *Member : Class->decls()) {
4757 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4758 continue;
4759 InheritableAttr *MemberAttr = getDLLAttr(Member);
4760 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4761 continue;
4762
Hans Wennborg17f9b442015-05-27 00:06:45 +00004763 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004764 diag::err_attribute_dll_member_of_dll_class)
4765 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00004766 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004767 Member->setInvalidDecl();
4768 }
4769 }
4770
4771 if (Class->getDescribedClassTemplate())
4772 // Don't inherit dll attribute until the template is instantiated.
4773 return;
4774
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004775 // The class is either imported or exported.
4776 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00004777
Hans Wennborgfd76d912015-01-15 21:18:30 +00004778 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4779
Hans Wennborgbb1983c2015-06-09 00:39:03 +00004780 // Ignore explicit dllexport on explicit class template instantiation declarations.
4781 if (ClassExported && !ClassAttr->isInherited() &&
4782 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00004783 Class->dropAttr<DLLExportAttr>();
4784 return;
4785 }
4786
Hans Wennborg853ae942014-05-30 16:59:42 +00004787 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004788 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00004789
4790 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4791 // seem to be true in practice?
4792
Hans Wennborg853ae942014-05-30 16:59:42 +00004793 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004794 VarDecl *VD = dyn_cast<VarDecl>(Member);
4795 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4796
4797 // Only methods and static fields inherit the attributes.
4798 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004799 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004800
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004801 if (MD) {
4802 // Don't process deleted methods.
4803 if (MD->isDeleted())
4804 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004805
David Majnemer30f058a2015-05-11 03:00:22 +00004806 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00004807 // MinGW does not import or export inline methods.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004808 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemer30f058a2015-05-11 03:00:22 +00004809 continue;
4810
Dmitry Polukhin41581522016-05-13 09:03:56 +00004811 // MSVC versions before 2015 don't export the move assignment operators
4812 // and move constructor, so don't attempt to import/export them if
4813 // we have a definition.
4814 auto *CXXC = dyn_cast<CXXConstructorDecl>(MD);
4815 if ((MD->isMoveAssignmentOperator() ||
4816 (CXXC && CXXC->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00004817 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00004818 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004819 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004820 }
4821
Hans Wennborg287231c2015-04-22 04:05:17 +00004822 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4823 continue;
4824
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004825 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004826 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00004827 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00004828 NewAttr->setInherited(true);
4829 Member->addAttr(NewAttr);
4830 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004831 }
Hans Wennborg99000c22015-08-15 01:18:16 +00004832
4833 if (ClassExported)
4834 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00004835}
4836
Hans Wennborgfce87ca2015-06-09 00:39:09 +00004837/// \brief Perform propagation of DLL attributes from a derived class to a
4838/// templated base class for MS compatibility.
4839void Sema::propagateDLLAttrToBaseClassTemplate(
4840 CXXRecordDecl *Class, Attr *ClassAttr,
4841 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4842 if (getDLLAttr(
4843 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4844 // If the base class template has a DLL attribute, don't try to change it.
4845 return;
4846 }
4847
4848 auto TSK = BaseTemplateSpec->getSpecializationKind();
4849 if (!getDLLAttr(BaseTemplateSpec) &&
4850 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4851 TSK == TSK_ImplicitInstantiation)) {
4852 // The template hasn't been instantiated yet (or it has, but only as an
4853 // explicit instantiation declaration or implicit instantiation, which means
4854 // we haven't codegenned any members yet), so propagate the attribute.
4855 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4856 NewAttr->setInherited(true);
4857 BaseTemplateSpec->addAttr(NewAttr);
4858
4859 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4860 // needs to be run again to work see the new attribute. Otherwise this will
4861 // get run whenever the template is instantiated.
4862 if (TSK != TSK_Undeclared)
4863 checkClassLevelDLLAttribute(BaseTemplateSpec);
4864
4865 return;
4866 }
4867
4868 if (getDLLAttr(BaseTemplateSpec)) {
4869 // The template has already been specialized or instantiated with an
4870 // attribute, explicitly or through propagation. We should not try to change
4871 // it.
4872 return;
4873 }
4874
4875 // The template was previously instantiated or explicitly specialized without
4876 // a dll attribute, It's too late for us to add an attribute, so warn that
4877 // this is unsupported.
4878 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4879 << BaseTemplateSpec->isExplicitSpecialization();
4880 Diag(ClassAttr->getLocation(), diag::note_attribute);
4881 if (BaseTemplateSpec->isExplicitSpecialization()) {
4882 Diag(BaseTemplateSpec->getLocation(),
4883 diag::note_template_class_explicit_specialization_was_here)
4884 << BaseTemplateSpec;
4885 } else {
4886 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4887 diag::note_template_class_instantiation_was_here)
4888 << BaseTemplateSpec;
4889 }
4890}
4891
Douglas Gregorc99f1552009-12-03 18:33:45 +00004892/// \brief Perform semantic checks on a class definition that has been
4893/// completing, introducing implicitly-declared members, checking for
4894/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004895void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004896 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004897 return;
4898
John McCall02db245d2010-08-18 09:41:07 +00004899 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4900 AbstractUsageInfo Info(*this, Record);
4901 CheckAbstractClassUsage(Info, Record);
4902 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004903
4904 // If this is not an aggregate type and has no user-declared constructor,
4905 // complain about any non-static data members of reference or const scalar
4906 // type, since they will never get initializers.
4907 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004908 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4909 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004910 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004911 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004912 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004913 continue;
4914
Douglas Gregor454a5b62010-04-15 00:00:53 +00004915 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004916 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004917 if (!Complained) {
4918 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4919 << Record->getTagKind() << Record;
4920 Complained = true;
4921 }
4922
4923 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4924 << F->getType()->isReferenceType()
4925 << F->getDeclName();
4926 }
4927 }
4928 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004929
Douglas Gregor36c22a22010-10-15 13:21:21 +00004930 if (Record->getIdentifier()) {
4931 // C++ [class.mem]p13:
4932 // If T is the name of a class, then each of the following shall have a
4933 // name different from T:
4934 // - every member of every anonymous union that is a member of class T.
4935 //
4936 // C++ [class.mem]p14:
4937 // In addition, if class T has a user-declared constructor (12.1), every
4938 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004939 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4940 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4941 ++I) {
4942 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004943 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4944 isa<IndirectFieldDecl>(D)) {
4945 Diag(D->getLocation(), diag::err_member_name_of_class)
4946 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004947 break;
4948 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004949 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004950 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004951
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004952 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004953 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004954 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004955 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4956 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004957 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4958 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4959 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004960
David Majnemera5433082013-10-18 00:33:31 +00004961 if (Record->isAbstract()) {
4962 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4963 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4964 << FA->isSpelledAsSealed();
4965 DiagnoseAbstractType(Record);
4966 }
David Blaikie348df502012-09-21 03:21:07 +00004967 }
4968
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004969 bool HasMethodWithOverrideControl = false,
4970 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004971 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004972 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004973 // See if a method overloads virtual methods in a base
4974 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004975 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004976 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004977 if (M->hasAttr<OverrideAttr>())
4978 HasMethodWithOverrideControl = true;
4979 else if (M->size_overridden_methods() > 0)
4980 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004981 // Check whether the explicitly-defaulted special members are valid.
4982 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004983 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004984
4985 // For an explicitly defaulted or deleted special member, we defer
4986 // determining triviality until the class is complete. That time is now!
4987 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004988 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004989 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004990 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004991
4992 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004993 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004994 }
4995 }
4996 }
4997 }
4998
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004999 if (HasMethodWithOverrideControl &&
5000 HasOverridingMethodWithoutOverrideControl) {
5001 // At least one method has the 'override' control declared.
5002 // Diagnose all other overridden methods which do not have 'override' specified on them.
5003 for (auto *M : Record->methods())
5004 DiagnoseAbsenceOfOverrideControl(M);
5005 }
Sebastian Redl08905022011-02-05 19:23:19 +00005006
John McCall95833f32014-02-27 20:30:49 +00005007 // ms_struct is a request to use the same ABI rules as MSVC. Check
5008 // whether this class uses any C++ features that are implemented
5009 // completely differently in MSVC, and if so, emit a diagnostic.
5010 // That diagnostic defaults to an error, but we allow projects to
5011 // map it down to a warning (or ignore it). It's a fairly common
5012 // practice among users of the ms_struct pragma to mass-annotate
5013 // headers, sweeping up a bunch of types that the project doesn't
5014 // really rely on MSVC-compatible layout for. We must therefore
5015 // support "ms_struct except for C++ stuff" as a secondary ABI.
5016 if (Record->isMsStruct(Context) &&
5017 (Record->isPolymorphic() || Record->getNumBases())) {
5018 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005019 }
5020
Richard Smithc2bc61b2013-03-18 21:12:30 +00005021 // Declare inheriting constructors. We do this eagerly here because:
5022 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00005023 // constructors from different classes.
5024 // - The lazy declaration of the other implicit constructors is so as to not
5025 // waste space and performance on classes that are not meant to be
5026 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00005027 // have inheriting constructors.
5028 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00005029
Hans Wennborg17f9b442015-05-27 00:06:45 +00005030 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005031}
5032
Richard Smith41c35d62013-11-27 03:39:20 +00005033/// Look up the special member function that would be called by a special
5034/// member function for a subobject of class type.
5035///
5036/// \param Class The class type of the subobject.
5037/// \param CSM The kind of special member function.
5038/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5039/// \param ConstRHS True if this is a copy operation with a const object
5040/// on its RHS, that is, if the argument to the outer special member
5041/// function is 'const' and this is not a field marked 'mutable'.
5042static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5043 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5044 unsigned FieldQuals, bool ConstRHS) {
5045 unsigned LHSQuals = 0;
5046 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5047 LHSQuals = FieldQuals;
5048
5049 unsigned RHSQuals = FieldQuals;
5050 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5051 RHSQuals = 0;
5052 else if (ConstRHS)
5053 RHSQuals |= Qualifiers::Const;
5054
5055 return S.LookupSpecialMember(Class, CSM,
5056 RHSQuals & Qualifiers::Const,
5057 RHSQuals & Qualifiers::Volatile,
5058 false,
5059 LHSQuals & Qualifiers::Const,
5060 LHSQuals & Qualifiers::Volatile);
5061}
5062
Richard Smithb5800092012-06-10 05:43:50 +00005063/// Is the special member function which would be selected to perform the
5064/// specified operation on the specified class type a constexpr constructor?
5065static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5066 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005067 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005068 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005069 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005070 if (!SMOR || !SMOR->getMethod())
5071 // A constructor we wouldn't select can't be "involved in initializing"
5072 // anything.
5073 return true;
5074 return SMOR->getMethod()->isConstexpr();
5075}
5076
5077/// Determine whether the specified special member function would be constexpr
5078/// if it were implicitly defined.
5079static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5080 Sema::CXXSpecialMember CSM,
5081 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005082 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005083 return false;
5084
5085 // C++11 [dcl.constexpr]p4:
5086 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005087 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005088 switch (CSM) {
5089 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005090 // Since default constructor lookup is essentially trivial (and cannot
5091 // involve, for instance, template instantiation), we compute whether a
5092 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5093 //
5094 // This is important for performance; we need to know whether the default
5095 // constructor is constexpr to determine whether the type is a literal type.
5096 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5097
Richard Smithb5800092012-06-10 05:43:50 +00005098 case Sema::CXXCopyConstructor:
5099 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005100 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005101 break;
5102
5103 case Sema::CXXCopyAssignment:
5104 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005105 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005106 return false;
5107 // In C++1y, we need to perform overload resolution.
5108 Ctor = false;
5109 break;
5110
Richard Smithb5800092012-06-10 05:43:50 +00005111 case Sema::CXXDestructor:
5112 case Sema::CXXInvalid:
5113 return false;
5114 }
5115
5116 // -- if the class is a non-empty union, or for each non-empty anonymous
5117 // union member of a non-union class, exactly one non-static data member
5118 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005119 //
5120 // If we squint, this is guaranteed, since exactly one non-static data member
5121 // will be initialized (if the constructor isn't deleted), we just don't know
5122 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005123 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005124 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005125
5126 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005127 if (Ctor && ClassDecl->getNumVBases())
5128 return false;
5129
5130 // C++1y [class.copy]p26:
5131 // -- [the class] is a literal type, and
5132 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005133 return false;
5134
5135 // -- every constructor involved in initializing [...] base class
5136 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005137 // -- the assignment operator selected to copy/move each direct base
5138 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005139 for (const auto &B : ClassDecl->bases()) {
5140 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005141 if (!BaseType) continue;
5142
5143 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005144 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005145 return false;
5146 }
5147
5148 // -- every constructor involved in initializing non-static data members
5149 // [...] shall be a constexpr constructor;
5150 // -- every non-static data member and base class sub-object shall be
5151 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005152 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005153 // thereof), the assignment operator selected to copy/move that member is
5154 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005155 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005156 if (F->isInvalidDecl())
5157 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005158 QualType BaseType = S.Context.getBaseElementType(F->getType());
5159 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005160 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005161 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5162 BaseType.getCVRQualifiers(),
5163 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005164 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005165 }
5166 }
5167
5168 // All OK, it's constexpr!
5169 return true;
5170}
5171
Richard Smithd3b5c9082012-07-27 04:22:15 +00005172static Sema::ImplicitExceptionSpecification
5173computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5174 switch (S.getSpecialMember(MD)) {
5175 case Sema::CXXDefaultConstructor:
5176 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5177 case Sema::CXXCopyConstructor:
5178 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5179 case Sema::CXXCopyAssignment:
5180 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5181 case Sema::CXXMoveConstructor:
5182 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5183 case Sema::CXXMoveAssignment:
5184 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5185 case Sema::CXXDestructor:
5186 return S.ComputeDefaultedDtorExceptionSpec(MD);
5187 case Sema::CXXInvalid:
5188 break;
5189 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005190 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5191 "only special members have implicit exception specs");
5192 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005193}
5194
Reid Kleckner78af0702013-08-27 23:08:25 +00005195static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5196 CXXMethodDecl *MD) {
5197 FunctionProtoType::ExtProtoInfo EPI;
5198
5199 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005200 EPI.ExceptionSpec.Type = EST_Unevaluated;
5201 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005202
5203 // Set the calling convention to the default for C++ instance methods.
5204 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5205 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5206 /*IsCXXMethod=*/true));
5207 return EPI;
5208}
5209
Richard Smithd3b5c9082012-07-27 04:22:15 +00005210void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5211 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5212 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5213 return;
5214
Richard Smith7f782272012-07-30 23:48:14 +00005215 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005216 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005217
Richard Smith7f782272012-07-30 23:48:14 +00005218 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005219 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005220
5221 // A user-provided destructor can be defined outside the class. When that
5222 // happens, be sure to update the exception specification on both
5223 // declarations.
5224 const FunctionProtoType *CanonicalFPT =
5225 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5226 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005227 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005228}
5229
Richard Smithb9e90b12012-05-15 04:39:51 +00005230void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5231 CXXRecordDecl *RD = MD->getParent();
5232 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005233
Richard Smithb9e90b12012-05-15 04:39:51 +00005234 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5235 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005236
5237 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005238 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005239 bool First = MD == MD->getCanonicalDecl();
5240
5241 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005242
5243 // C++11 [dcl.fct.def.default]p1:
5244 // A function that is explicitly defaulted shall
5245 // -- be a special member function (checked elsewhere),
5246 // -- have the same type (except for ref-qualifiers, and except that a
5247 // copy operation can take a non-const reference) as an implicit
5248 // declaration, and
5249 // -- not have default arguments.
5250 unsigned ExpectedParams = 1;
5251 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5252 ExpectedParams = 0;
5253 if (MD->getNumParams() != ExpectedParams) {
5254 // This also checks for default arguments: a copy or move constructor with a
5255 // default argument is classified as a default constructor, and assignment
5256 // operations and destructors can't have default arguments.
5257 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5258 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005259 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005260 } else if (MD->isVariadic()) {
5261 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5262 << CSM << MD->getSourceRange();
5263 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005264 }
5265
Richard Smithb9e90b12012-05-15 04:39:51 +00005266 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005267
Richard Smithb5800092012-06-10 05:43:50 +00005268 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005269 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005270 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005271 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005272 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005273
Richard Smithb9e90b12012-05-15 04:39:51 +00005274 QualType ReturnType = Context.VoidTy;
5275 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5276 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005277 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005278 QualType ExpectedReturnType =
5279 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5280 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5281 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5282 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5283 HadError = true;
5284 }
5285
5286 // A defaulted special member cannot have cv-qualifiers.
5287 if (Type->getTypeQuals()) {
5288 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005289 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005290 HadError = true;
5291 }
5292 }
5293
5294 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005295 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005296 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005297 if (ExpectedParams && ArgType->isReferenceType()) {
5298 // Argument must be reference to possibly-const T.
5299 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005300 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005301
5302 if (ReferentType.isVolatileQualified()) {
5303 Diag(MD->getLocation(),
5304 diag::err_defaulted_special_member_volatile_param) << CSM;
5305 HadError = true;
5306 }
5307
Richard Smithb5800092012-06-10 05:43:50 +00005308 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005309 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5310 Diag(MD->getLocation(),
5311 diag::err_defaulted_special_member_copy_const_param)
5312 << (CSM == CXXCopyAssignment);
5313 // FIXME: Explain why this special member can't be const.
5314 } else {
5315 Diag(MD->getLocation(),
5316 diag::err_defaulted_special_member_move_const_param)
5317 << (CSM == CXXMoveAssignment);
5318 }
5319 HadError = true;
5320 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005321 } else if (ExpectedParams) {
5322 // A copy assignment operator can take its argument by value, but a
5323 // defaulted one cannot.
5324 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005325 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005326 HadError = true;
5327 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005328
Richard Smithcc36f692011-12-22 02:22:31 +00005329 // C++11 [dcl.fct.def.default]p2:
5330 // An explicitly-defaulted function may be declared constexpr only if it
5331 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005332 // Do not apply this rule to members of class templates, since core issue 1358
5333 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005334 // functions which cannot be constexpr (for non-constructors in C++11 and for
5335 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005336 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5337 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005338 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005339 : isa<CXXConstructorDecl>(MD)) &&
5340 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005341 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5342 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005343 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005344 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005345 }
Richard Smithbd305122012-12-11 01:14:52 +00005346
Richard Smithcc36f692011-12-22 02:22:31 +00005347 // and may have an explicit exception-specification only if it is compatible
5348 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005349 if (Type->hasExceptionSpec()) {
5350 // Delay the check if this is the first declaration of the special member,
5351 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005352 if (First) {
5353 // If the exception specification needs to be instantiated, do so now,
5354 // before we clobber it with an EST_Unevaluated specification below.
5355 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5356 InstantiateExceptionSpec(MD->getLocStart(), MD);
5357 Type = MD->getType()->getAs<FunctionProtoType>();
5358 }
Richard Smithbd305122012-12-11 01:14:52 +00005359 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005360 } else
Richard Smithbd305122012-12-11 01:14:52 +00005361 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5362 }
Richard Smithcc36f692011-12-22 02:22:31 +00005363
5364 // If a function is explicitly defaulted on its first declaration,
5365 if (First) {
5366 // -- it is implicitly considered to be constexpr if the implicit
5367 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005368 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005369
Richard Smithb9e90b12012-05-15 04:39:51 +00005370 // -- it is implicitly considered to have the same exception-specification
5371 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005372 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005373 EPI.ExceptionSpec.Type = EST_Unevaluated;
5374 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005375 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005376 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005377 ExpectedParams),
5378 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005379 }
5380
Richard Smithb9e90b12012-05-15 04:39:51 +00005381 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005382 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005383 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005384 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005385 // C++11 [dcl.fct.def.default]p4:
5386 // [For a] user-provided explicitly-defaulted function [...] if such a
5387 // function is implicitly defined as deleted, the program is ill-formed.
5388 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005389 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005390 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005391 }
5392 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005393
Richard Smithb9e90b12012-05-15 04:39:51 +00005394 if (HadError)
5395 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005396}
5397
Richard Smithbd305122012-12-11 01:14:52 +00005398/// Check whether the exception specification provided for an
5399/// explicitly-defaulted special member matches the exception specification
5400/// that would have been generated for an implicit special member, per
5401/// C++11 [dcl.fct.def.default]p2.
5402void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5403 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005404 // If the exception specification was explicitly specified but hadn't been
5405 // parsed when the method was defaulted, grab it now.
5406 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5407 SpecifiedType =
5408 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5409
Richard Smithbd305122012-12-11 01:14:52 +00005410 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005411 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5412 /*IsCXXMethod=*/true);
5413 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005414 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5415 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005416 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005417 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005418
5419 // Ensure that it matches.
5420 CheckEquivalentExceptionSpec(
5421 PDiag(diag::err_incorrect_defaulted_exception_spec)
5422 << getSpecialMember(MD), PDiag(),
5423 ImplicitType, SourceLocation(),
5424 SpecifiedType, MD->getLocation());
5425}
5426
Alp Tokerae3a9442013-10-18 05:54:19 +00005427void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005428 decltype(DelayedExceptionSpecChecks) Checks;
5429 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005430
Richard Smith88f45492014-11-22 03:09:05 +00005431 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005432 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5433
5434 // Perform any deferred checking of exception specifications for virtual
5435 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005436 for (auto &Check : Checks)
5437 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005438
5439 // Check that any explicitly-defaulted methods have exception specifications
5440 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005441 for (auto &Spec : Specs)
5442 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005443}
5444
Richard Smithd951a1d2012-02-18 02:02:13 +00005445namespace {
5446struct SpecialMemberDeletionInfo {
5447 Sema &S;
5448 CXXMethodDecl *MD;
5449 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005450 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005451
5452 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005453 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005454 SourceLocation Loc;
5455
5456 bool AllFieldsAreConst;
5457
5458 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005459 Sema::CXXSpecialMember CSM, bool Diagnose)
5460 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005461 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005462 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005463 AllFieldsAreConst(true) {
5464 switch (CSM) {
5465 case Sema::CXXDefaultConstructor:
5466 case Sema::CXXCopyConstructor:
5467 IsConstructor = true;
5468 break;
5469 case Sema::CXXMoveConstructor:
5470 IsConstructor = true;
5471 IsMove = true;
5472 break;
5473 case Sema::CXXCopyAssignment:
5474 IsAssignment = true;
5475 break;
5476 case Sema::CXXMoveAssignment:
5477 IsAssignment = true;
5478 IsMove = true;
5479 break;
5480 case Sema::CXXDestructor:
5481 break;
5482 case Sema::CXXInvalid:
5483 llvm_unreachable("invalid special member kind");
5484 }
5485
5486 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005487 if (const ReferenceType *RT =
5488 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5489 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005490 }
5491 }
5492
5493 bool inUnion() const { return MD->getParent()->isUnion(); }
5494
5495 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005496 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005497 unsigned Quals, bool IsMutable) {
5498 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5499 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005500 }
5501
Richard Smith852265f2012-03-30 20:53:28 +00005502 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005503
Richard Smith852265f2012-03-30 20:53:28 +00005504 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005505 bool shouldDeleteForField(FieldDecl *FD);
5506 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005507
Richard Smithaf136f82012-07-18 03:51:16 +00005508 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5509 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005510 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5511 Sema::SpecialMemberOverloadResult *SMOR,
5512 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005513
5514 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005515};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005516}
Richard Smithd951a1d2012-02-18 02:02:13 +00005517
John McCalld4274212012-04-09 20:53:23 +00005518/// Is the given special member inaccessible when used on the given
5519/// sub-object.
5520bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5521 CXXMethodDecl *target) {
5522 /// If we're operating on a base class, the object type is the
5523 /// type of this special member.
5524 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005525 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005526 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5527 objectTy = S.Context.getTypeDeclType(MD->getParent());
5528 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5529
5530 // If we're operating on a field, the object type is the type of the field.
5531 } else {
5532 objectTy = S.Context.getTypeDeclType(target->getParent());
5533 }
5534
5535 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5536}
5537
Richard Smith852265f2012-03-30 20:53:28 +00005538/// Check whether we should delete a special member due to the implicit
5539/// definition containing a call to a special member of a subobject.
5540bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5541 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5542 bool IsDtorCallInCtor) {
5543 CXXMethodDecl *Decl = SMOR->getMethod();
5544 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5545
5546 int DiagKind = -1;
5547
5548 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5549 DiagKind = !Decl ? 0 : 1;
5550 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5551 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005552 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005553 DiagKind = 3;
5554 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5555 !Decl->isTrivial()) {
5556 // A member of a union must have a trivial corresponding special member.
5557 // As a weird special case, a destructor call from a union's constructor
5558 // must be accessible and non-deleted, but need not be trivial. Such a
5559 // destructor is never actually called, but is semantically checked as
5560 // if it were.
5561 DiagKind = 4;
5562 }
5563
5564 if (DiagKind == -1)
5565 return false;
5566
5567 if (Diagnose) {
5568 if (Field) {
5569 S.Diag(Field->getLocation(),
5570 diag::note_deleted_special_member_class_subobject)
5571 << CSM << MD->getParent() << /*IsField*/true
5572 << Field << DiagKind << IsDtorCallInCtor;
5573 } else {
5574 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5575 S.Diag(Base->getLocStart(),
5576 diag::note_deleted_special_member_class_subobject)
5577 << CSM << MD->getParent() << /*IsField*/false
5578 << Base->getType() << DiagKind << IsDtorCallInCtor;
5579 }
5580
5581 if (DiagKind == 1)
5582 S.NoteDeletedFunction(Decl);
5583 // FIXME: Explain inaccessibility if DiagKind == 3.
5584 }
5585
5586 return true;
5587}
5588
Richard Smith921bd202012-02-26 09:11:52 +00005589/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005590/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005591bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005592 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005593 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005594 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005595
5596 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005597 // -- any direct or virtual base class, or non-static data member with no
5598 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005599 // either M has no default constructor or overload resolution as applied
5600 // to M's default constructor results in an ambiguity or in a function
5601 // that is deleted or inaccessible
5602 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5603 // -- a direct or virtual base class B that cannot be copied/moved because
5604 // overload resolution, as applied to B's corresponding special member,
5605 // results in an ambiguity or a function that is deleted or inaccessible
5606 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005607 // C++11 [class.dtor]p5:
5608 // -- any direct or virtual base class [...] has a type with a destructor
5609 // that is deleted or inaccessible
5610 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005611 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005612 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5613 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005614 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005615
Richard Smith852265f2012-03-30 20:53:28 +00005616 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5617 // -- any direct or virtual base class or non-static data member has a
5618 // type with a destructor that is deleted or inaccessible
5619 if (IsConstructor) {
5620 Sema::SpecialMemberOverloadResult *SMOR =
5621 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5622 false, false, false, false, false);
5623 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5624 return true;
5625 }
5626
Richard Smith921bd202012-02-26 09:11:52 +00005627 return false;
5628}
5629
5630/// Check whether we should delete a special member function due to the class
5631/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005632bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005633 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00005634 // If program is correct, BaseClass cannot be null, but if it is, the error
5635 // must be reported elsewhere.
5636 return BaseClass && shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005637}
5638
5639/// Check whether we should delete a special member function due to the class
5640/// having a particular non-static data member.
5641bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5642 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5643 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5644
5645 if (CSM == Sema::CXXDefaultConstructor) {
5646 // For a default constructor, all references must be initialized in-class
5647 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005648 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5649 if (Diagnose)
5650 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5651 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005652 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005653 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005654 // C++11 [class.ctor]p5: any non-variant non-static data member of
5655 // const-qualified type (or array thereof) with no
5656 // brace-or-equal-initializer does not have a user-provided default
5657 // constructor.
5658 if (!inUnion() && FieldType.isConstQualified() &&
5659 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005660 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5661 if (Diagnose)
5662 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005663 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005664 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005665 }
5666
5667 if (inUnion() && !FieldType.isConstQualified())
5668 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005669 } else if (CSM == Sema::CXXCopyConstructor) {
5670 // For a copy constructor, data members must not be of rvalue reference
5671 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005672 if (FieldType->isRValueReferenceType()) {
5673 if (Diagnose)
5674 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5675 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005676 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005677 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005678 } else if (IsAssignment) {
5679 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005680 if (FieldType->isReferenceType()) {
5681 if (Diagnose)
5682 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5683 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005684 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005685 }
5686 if (!FieldRecord && FieldType.isConstQualified()) {
5687 // C++11 [class.copy]p23:
5688 // -- a non-static data member of const non-class type (or array thereof)
5689 if (Diagnose)
5690 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005691 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005692 return true;
5693 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005694 }
5695
5696 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005697 // Some additional restrictions exist on the variant members.
5698 if (!inUnion() && FieldRecord->isUnion() &&
5699 FieldRecord->isAnonymousStructOrUnion()) {
5700 bool AllVariantFieldsAreConst = true;
5701
Richard Smith5704fe82012-03-29 19:00:10 +00005702 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005703 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005704 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005705
5706 if (!UnionFieldType.isConstQualified())
5707 AllVariantFieldsAreConst = false;
5708
Richard Smith921bd202012-02-26 09:11:52 +00005709 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5710 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005711 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005712 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005713 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005714 }
5715
5716 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005717 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005718 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005719 if (Diagnose)
5720 S.Diag(FieldRecord->getLocation(),
5721 diag::note_deleted_default_ctor_all_const)
5722 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005723 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005724 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005725
Richard Smith5704fe82012-03-29 19:00:10 +00005726 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005727 // This is technically non-conformant, but sanity demands it.
5728 return false;
5729 }
5730
Richard Smithaf136f82012-07-18 03:51:16 +00005731 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5732 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005733 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005734 }
5735
5736 return false;
5737}
5738
5739/// C++11 [class.ctor] p5:
5740/// A defaulted default constructor for a class X is defined as deleted if
5741/// X is a union and all of its variant members are of const-qualified type.
5742bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005743 // This is a silly definition, because it gives an empty union a deleted
5744 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005745 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005746 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005747 if (Diagnose)
5748 S.Diag(MD->getParent()->getLocation(),
5749 diag::note_deleted_default_ctor_all_const)
5750 << MD->getParent() << /*not anonymous union*/0;
5751 return true;
5752 }
5753 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005754}
5755
5756/// Determine whether a defaulted special member function should be defined as
5757/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5758/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005759bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5760 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005761 if (MD->isInvalidDecl())
5762 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005763 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005764 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005765 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005766 return false;
5767
Richard Smithd951a1d2012-02-18 02:02:13 +00005768 // C++11 [expr.lambda.prim]p19:
5769 // The closure type associated with a lambda-expression has a
5770 // deleted (8.4.3) default constructor and a deleted copy
5771 // assignment operator.
5772 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005773 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5774 if (Diagnose)
5775 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005776 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005777 }
5778
Richard Smith6f1e2c62012-04-02 20:59:25 +00005779 // For an anonymous struct or union, the copy and assignment special members
5780 // will never be used, so skip the check. For an anonymous union declared at
5781 // namespace scope, the constructor and destructor are used.
5782 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5783 RD->isAnonymousStructOrUnion())
5784 return false;
5785
Richard Smith852265f2012-03-30 20:53:28 +00005786 // C++11 [class.copy]p7, p18:
5787 // If the class definition declares a move constructor or move assignment
5788 // operator, an implicitly declared copy constructor or copy assignment
5789 // operator is defined as deleted.
5790 if (MD->isImplicit() &&
5791 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005792 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005793
5794 // In Microsoft mode, a user-declared move only causes the deletion of the
5795 // corresponding copy operation, not both copy operations.
5796 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005797 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005798 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005799
5800 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005801 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005802 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005803 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005804 break;
5805 }
5806 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005807 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005808 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005809 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005810 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005811
5812 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005813 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005814 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005815 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005816 break;
5817 }
5818 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005819 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005820 }
5821
5822 if (UserDeclaredMove) {
5823 Diag(UserDeclaredMove->getLocation(),
5824 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005825 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005826 << UserDeclaredMove->isMoveAssignmentOperator();
5827 return true;
5828 }
5829 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005830
Richard Smith6f1e2c62012-04-02 20:59:25 +00005831 // Do access control from the special member function
5832 ContextRAII MethodContext(*this, MD);
5833
Richard Smith921bd202012-02-26 09:11:52 +00005834 // C++11 [class.dtor]p5:
5835 // -- for a virtual destructor, lookup of the non-array deallocation function
5836 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005837 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005838 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005839 DeclarationName Name =
5840 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5841 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005842 OperatorDelete, false)) {
5843 if (Diagnose)
5844 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005845 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005846 }
Richard Smith921bd202012-02-26 09:11:52 +00005847 }
5848
Richard Smith852265f2012-03-30 20:53:28 +00005849 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005850
Aaron Ballman574705e2014-03-13 15:41:46 +00005851 for (auto &BI : RD->bases())
5852 if (!BI.isVirtual() &&
5853 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005854 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005855
Richard Smithd1627032013-07-22 18:06:23 +00005856 // Per DR1611, do not consider virtual bases of constructors of abstract
5857 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005858 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005859 for (auto &BI : RD->vbases())
5860 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005861 return true;
5862 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005863
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005864 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005865 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005866 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005867 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005868
Richard Smithd951a1d2012-02-18 02:02:13 +00005869 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005870 return true;
5871
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005872 if (getLangOpts().CUDA) {
5873 // We should delete the special member in CUDA mode if target inference
5874 // failed.
5875 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5876 Diagnose);
5877 }
5878
Alexis Huntea6f0322011-05-11 22:34:38 +00005879 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005880}
5881
Richard Smith92f241f2012-12-08 02:53:02 +00005882/// Perform lookup for a special member of the specified kind, and determine
5883/// whether it is trivial. If the triviality can be determined without the
5884/// lookup, skip it. This is intended for use when determining whether a
5885/// special member of a containing object is trivial, and thus does not ever
5886/// perform overload resolution for default constructors.
5887///
5888/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5889/// member that was most likely to be intended to be trivial, if any.
5890static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5891 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005892 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005893 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005894 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005895
5896 switch (CSM) {
5897 case Sema::CXXInvalid:
5898 llvm_unreachable("not a special member");
5899
5900 case Sema::CXXDefaultConstructor:
5901 // C++11 [class.ctor]p5:
5902 // A default constructor is trivial if:
5903 // - all the [direct subobjects] have trivial default constructors
5904 //
5905 // Note, no overload resolution is performed in this case.
5906 if (RD->hasTrivialDefaultConstructor())
5907 return true;
5908
5909 if (Selected) {
5910 // If there's a default constructor which could have been trivial, dig it
5911 // out. Otherwise, if there's any user-provided default constructor, point
5912 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005913 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005914 if (RD->needsImplicitDefaultConstructor())
5915 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005916 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005917 if (!CI->isDefaultConstructor())
5918 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005919 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005920 if (!DefCtor->isUserProvided())
5921 break;
5922 }
5923
5924 *Selected = DefCtor;
5925 }
5926
5927 return false;
5928
5929 case Sema::CXXDestructor:
5930 // C++11 [class.dtor]p5:
5931 // A destructor is trivial if:
5932 // - all the direct [subobjects] have trivial destructors
5933 if (RD->hasTrivialDestructor())
5934 return true;
5935
5936 if (Selected) {
5937 if (RD->needsImplicitDestructor())
5938 S.DeclareImplicitDestructor(RD);
5939 *Selected = RD->getDestructor();
5940 }
5941
5942 return false;
5943
5944 case Sema::CXXCopyConstructor:
5945 // C++11 [class.copy]p12:
5946 // A copy constructor is trivial if:
5947 // - the constructor selected to copy each direct [subobject] is trivial
5948 if (RD->hasTrivialCopyConstructor()) {
5949 if (Quals == Qualifiers::Const)
5950 // We must either select the trivial copy constructor or reach an
5951 // ambiguity; no need to actually perform overload resolution.
5952 return true;
5953 } else if (!Selected) {
5954 return false;
5955 }
5956 // In C++98, we are not supposed to perform overload resolution here, but we
5957 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5958 // cases like B as having a non-trivial copy constructor:
5959 // struct A { template<typename T> A(T&); };
5960 // struct B { mutable A a; };
5961 goto NeedOverloadResolution;
5962
5963 case Sema::CXXCopyAssignment:
5964 // C++11 [class.copy]p25:
5965 // A copy assignment operator is trivial if:
5966 // - the assignment operator selected to copy each direct [subobject] is
5967 // trivial
5968 if (RD->hasTrivialCopyAssignment()) {
5969 if (Quals == Qualifiers::Const)
5970 return true;
5971 } else if (!Selected) {
5972 return false;
5973 }
5974 // In C++98, we are not supposed to perform overload resolution here, but we
5975 // treat that as a language defect.
5976 goto NeedOverloadResolution;
5977
5978 case Sema::CXXMoveConstructor:
5979 case Sema::CXXMoveAssignment:
5980 NeedOverloadResolution:
5981 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005982 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005983
5984 // The standard doesn't describe how to behave if the lookup is ambiguous.
5985 // We treat it as not making the member non-trivial, just like the standard
5986 // mandates for the default constructor. This should rarely matter, because
5987 // the member will also be deleted.
5988 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5989 return true;
5990
5991 if (!SMOR->getMethod()) {
5992 assert(SMOR->getKind() ==
5993 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5994 return false;
5995 }
5996
5997 // We deliberately don't check if we found a deleted special member. We're
5998 // not supposed to!
5999 if (Selected)
6000 *Selected = SMOR->getMethod();
6001 return SMOR->getMethod()->isTrivial();
6002 }
6003
6004 llvm_unreachable("unknown special method kind");
6005}
6006
Benjamin Kramer3e350262013-02-15 12:30:38 +00006007static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006008 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006009 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006010 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006011
6012 // Look for constructor templates.
6013 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6014 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6015 if (CXXConstructorDecl *CD =
6016 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6017 return CD;
6018 }
6019
Craig Topperc3ec1492014-05-26 06:22:03 +00006020 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006021}
6022
6023/// The kind of subobject we are checking for triviality. The values of this
6024/// enumeration are used in diagnostics.
6025enum TrivialSubobjectKind {
6026 /// The subobject is a base class.
6027 TSK_BaseClass,
6028 /// The subobject is a non-static data member.
6029 TSK_Field,
6030 /// The object is actually the complete object.
6031 TSK_CompleteObject
6032};
6033
6034/// Check whether the special member selected for a given type would be trivial.
6035static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006036 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006037 Sema::CXXSpecialMember CSM,
6038 TrivialSubobjectKind Kind,
6039 bool Diagnose) {
6040 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6041 if (!SubRD)
6042 return true;
6043
6044 CXXMethodDecl *Selected;
6045 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006046 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006047 return true;
6048
6049 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006050 if (ConstRHS)
6051 SubType.addConst();
6052
Richard Smith92f241f2012-12-08 02:53:02 +00006053 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6054 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6055 << Kind << SubType.getUnqualifiedType();
6056 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6057 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6058 } else if (!Selected)
6059 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6060 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6061 else if (Selected->isUserProvided()) {
6062 if (Kind == TSK_CompleteObject)
6063 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6064 << Kind << SubType.getUnqualifiedType() << CSM;
6065 else {
6066 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6067 << Kind << SubType.getUnqualifiedType() << CSM;
6068 S.Diag(Selected->getLocation(), diag::note_declared_at);
6069 }
6070 } else {
6071 if (Kind != TSK_CompleteObject)
6072 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6073 << Kind << SubType.getUnqualifiedType() << CSM;
6074
6075 // Explain why the defaulted or deleted special member isn't trivial.
6076 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6077 }
6078 }
6079
6080 return false;
6081}
6082
6083/// Check whether the members of a class type allow a special member to be
6084/// trivial.
6085static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6086 Sema::CXXSpecialMember CSM,
6087 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006088 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006089 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6090 continue;
6091
6092 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6093
6094 // Pretend anonymous struct or union members are members of this class.
6095 if (FI->isAnonymousStructOrUnion()) {
6096 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6097 CSM, ConstArg, Diagnose))
6098 return false;
6099 continue;
6100 }
6101
6102 // C++11 [class.ctor]p5:
6103 // A default constructor is trivial if [...]
6104 // -- no non-static data member of its class has a
6105 // brace-or-equal-initializer
6106 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6107 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006108 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006109 return false;
6110 }
6111
6112 // Objective C ARC 4.3.5:
6113 // [...] nontrivally ownership-qualified types are [...] not trivially
6114 // default constructible, copy constructible, move constructible, copy
6115 // assignable, move assignable, or destructible [...]
6116 if (S.getLangOpts().ObjCAutoRefCount &&
6117 FieldType.hasNonTrivialObjCLifetime()) {
6118 if (Diagnose)
6119 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6120 << RD << FieldType.getObjCLifetime();
6121 return false;
6122 }
6123
Richard Smith41c35d62013-11-27 03:39:20 +00006124 bool ConstRHS = ConstArg && !FI->isMutable();
6125 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6126 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006127 return false;
6128 }
6129
6130 return true;
6131}
6132
6133/// Diagnose why the specified class does not have a trivial special member of
6134/// the given kind.
6135void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6136 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006137
Richard Smith41c35d62013-11-27 03:39:20 +00006138 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6139 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006140 TSK_CompleteObject, /*Diagnose*/true);
6141}
6142
6143/// Determine whether a defaulted or deleted special member function is trivial,
6144/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6145/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6146bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6147 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006148 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6149
6150 CXXRecordDecl *RD = MD->getParent();
6151
6152 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006153
Richard Smith2002bfe2013-11-04 02:02:27 +00006154 // C++11 [class.copy]p12, p25: [DR1593]
6155 // A [special member] is trivial if [...] its parameter-type-list is
6156 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006157 switch (CSM) {
6158 case CXXDefaultConstructor:
6159 case CXXDestructor:
6160 // Trivial default constructors and destructors cannot have parameters.
6161 break;
6162
6163 case CXXCopyConstructor:
6164 case CXXCopyAssignment: {
6165 // Trivial copy operations always have const, non-volatile parameter types.
6166 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006167 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006168 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6169 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6170 if (Diagnose)
6171 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6172 << Param0->getSourceRange() << Param0->getType()
6173 << Context.getLValueReferenceType(
6174 Context.getRecordType(RD).withConst());
6175 return false;
6176 }
6177 break;
6178 }
6179
6180 case CXXMoveConstructor:
6181 case CXXMoveAssignment: {
6182 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006183 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006184 const RValueReferenceType *RT =
6185 Param0->getType()->getAs<RValueReferenceType>();
6186 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6187 if (Diagnose)
6188 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6189 << Param0->getSourceRange() << Param0->getType()
6190 << Context.getRValueReferenceType(Context.getRecordType(RD));
6191 return false;
6192 }
6193 break;
6194 }
6195
6196 case CXXInvalid:
6197 llvm_unreachable("not a special member");
6198 }
6199
Richard Smith92f241f2012-12-08 02:53:02 +00006200 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6201 if (Diagnose)
6202 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6203 diag::note_nontrivial_default_arg)
6204 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6205 return false;
6206 }
6207 if (MD->isVariadic()) {
6208 if (Diagnose)
6209 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6210 return false;
6211 }
6212
6213 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6214 // A copy/move [constructor or assignment operator] is trivial if
6215 // -- the [member] selected to copy/move each direct base class subobject
6216 // is trivial
6217 //
6218 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6219 // A [default constructor or destructor] is trivial if
6220 // -- all the direct base classes have trivial [default constructors or
6221 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006222 for (const auto &BI : RD->bases())
6223 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006224 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006225 return false;
6226
6227 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6228 // A copy/move [constructor or assignment operator] for a class X is
6229 // trivial if
6230 // -- for each non-static data member of X that is of class type (or array
6231 // thereof), the constructor selected to copy/move that member is
6232 // trivial
6233 //
6234 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6235 // A [default constructor or destructor] is trivial if
6236 // -- for all of the non-static data members of its class that are of class
6237 // type (or array thereof), each such class has a trivial [default
6238 // constructor or destructor]
6239 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6240 return false;
6241
6242 // C++11 [class.dtor]p5:
6243 // A destructor is trivial if [...]
6244 // -- the destructor is not virtual
6245 if (CSM == CXXDestructor && MD->isVirtual()) {
6246 if (Diagnose)
6247 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6248 return false;
6249 }
6250
6251 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6252 // A [special member] for class X is trivial if [...]
6253 // -- class X has no virtual functions and no virtual base classes
6254 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6255 if (!Diagnose)
6256 return false;
6257
6258 if (RD->getNumVBases()) {
6259 // Check for virtual bases. We already know that the corresponding
6260 // member in all bases is trivial, so vbases must all be direct.
6261 CXXBaseSpecifier &BS = *RD->vbases_begin();
6262 assert(BS.isVirtual());
6263 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6264 return false;
6265 }
6266
6267 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006268 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006269 if (MI->isVirtual()) {
6270 SourceLocation MLoc = MI->getLocStart();
6271 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6272 return false;
6273 }
6274 }
6275
6276 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6277 }
6278
6279 // Looks like it's trivial!
6280 return true;
6281}
6282
Benjamin Kramer024e6192011-03-04 13:12:48 +00006283namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006284struct FindHiddenVirtualMethod {
6285 Sema *S;
6286 CXXMethodDecl *Method;
6287 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6288 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006289
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006290private:
6291 /// Check whether any most overriden method from MD in Methods
6292 static bool CheckMostOverridenMethods(
6293 const CXXMethodDecl *MD,
6294 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6295 if (MD->size_overridden_methods() == 0)
6296 return Methods.count(MD->getCanonicalDecl());
6297 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6298 E = MD->end_overridden_methods();
6299 I != E; ++I)
6300 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006301 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006302 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006303 }
6304
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006305public:
6306 /// Member lookup function that determines whether a given C++
6307 /// method overloads virtual methods in a base class without overriding any,
6308 /// to be used with CXXRecordDecl::lookupInBases().
6309 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6310 RecordDecl *BaseRecord =
6311 Specifier->getType()->getAs<RecordType>()->getDecl();
6312
6313 DeclarationName Name = Method->getDeclName();
6314 assert(Name.getNameKind() == DeclarationName::Identifier);
6315
6316 bool foundSameNameMethod = false;
6317 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6318 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6319 Path.Decls = Path.Decls.slice(1)) {
6320 NamedDecl *D = Path.Decls.front();
6321 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6322 MD = MD->getCanonicalDecl();
6323 foundSameNameMethod = true;
6324 // Interested only in hidden virtual methods.
6325 if (!MD->isVirtual())
6326 continue;
6327 // If the method we are checking overrides a method from its base
6328 // don't warn about the other overloaded methods. Clang deviates from
6329 // GCC by only diagnosing overloads of inherited virtual functions that
6330 // do not override any other virtual functions in the base. GCC's
6331 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6332 // function from a base class. These cases may be better served by a
6333 // warning (not specific to virtual functions) on call sites when the
6334 // call would select a different function from the base class, were it
6335 // visible.
6336 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6337 if (!S->IsOverload(Method, MD, false))
6338 return true;
6339 // Collect the overload only if its hidden.
6340 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6341 overloadedMethods.push_back(MD);
6342 }
6343 }
6344
6345 if (foundSameNameMethod)
6346 OverloadedMethods.append(overloadedMethods.begin(),
6347 overloadedMethods.end());
6348 return foundSameNameMethod;
6349 }
6350};
6351} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006352
David Blaikie282c92a2012-10-19 00:53:08 +00006353/// \brief Add the most overriden methods from MD to Methods
6354static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006355 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006356 if (MD->size_overridden_methods() == 0)
6357 Methods.insert(MD->getCanonicalDecl());
6358 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6359 E = MD->end_overridden_methods();
6360 I != E; ++I)
6361 AddMostOverridenMethods(*I, Methods);
6362}
6363
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006364/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006365/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006366void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6367 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006368 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006369 return;
6370
6371 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6372 /*bool RecordPaths=*/false,
6373 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006374 FindHiddenVirtualMethod FHVM;
6375 FHVM.Method = MD;
6376 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006377
6378 // Keep the base methods that were overriden or introduced in the subclass
6379 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006380 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006381 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6382 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6383 NamedDecl *ND = *I;
6384 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006385 ND = shad->getTargetDecl();
6386 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006387 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006388 }
6389
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006390 if (DC->lookupInBases(FHVM, Paths))
6391 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006392}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006393
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006394void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6395 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6396 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6397 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6398 PartialDiagnostic PD = PDiag(
6399 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6400 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6401 Diag(overloadedMD->getLocation(), PD);
6402 }
6403}
6404
6405/// \brief Diagnose methods which overload virtual methods in a base class
6406/// without overriding any.
6407void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6408 if (MD->isInvalidDecl())
6409 return;
6410
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006411 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006412 return;
6413
6414 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6415 FindHiddenVirtualMethods(MD, OverloadedMethods);
6416 if (!OverloadedMethods.empty()) {
6417 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6418 << MD << (OverloadedMethods.size() > 1);
6419
6420 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006421 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006422}
6423
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006424void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006425 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006426 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006427 SourceLocation RBrac,
6428 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006429 if (!TagDecl)
6430 return;
Mike Stump11289f42009-09-09 15:08:12 +00006431
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006432 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006433
Rafael Espindola06e1b132012-07-12 04:32:30 +00006434 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6435 if (l->getKind() != AttributeList::AT_Visibility)
6436 continue;
6437 l->setInvalid();
6438 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6439 l->getName();
6440 }
6441
David Blaikie751c5582011-09-22 02:58:26 +00006442 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006443 // strict aliasing violation!
6444 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006445 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006446
Douglas Gregor0be31a22010-07-02 17:43:08 +00006447 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006448 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006449}
6450
Douglas Gregor05379422008-11-03 17:51:48 +00006451/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6452/// special functions, such as the default constructor, copy
6453/// constructor, or destructor, to the given C++ class (C++
6454/// [special]p1). This routine can only be executed just before the
6455/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006456void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006457 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006458 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006459
Richard Smith12e79312016-05-13 06:47:56 +00006460 // If this class inherited any constructors, declare the default constructor
6461 // now in case it displaces one from a base class.
6462 if (ClassDecl->needsImplicitDefaultConstructor() &&
6463 ClassDecl->hasInheritedConstructor())
6464 DeclareImplicitDefaultConstructor(ClassDecl);
6465
Richard Smitha87b7662016-05-13 18:48:05 +00006466 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006467 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006468
Richard Smith6b02d462012-12-08 08:32:28 +00006469 // If the properties or semantics of the copy constructor couldn't be
6470 // determined while the class was being declared, force a declaration
6471 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00006472 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
6473 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00006474 DeclareImplicitCopyConstructor(ClassDecl);
6475 }
6476
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006477 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006478 ++ASTContext::NumImplicitMoveConstructors;
6479
Richard Smith12e79312016-05-13 06:47:56 +00006480 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
6481 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00006482 DeclareImplicitMoveConstructor(ClassDecl);
6483 }
6484
Richard Smitha87b7662016-05-13 18:48:05 +00006485 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006486 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006487
6488 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006489 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006490 // it shows up in the right place in the vtable and that we diagnose
6491 // problems with the implicit exception specification.
6492 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00006493 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
6494 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006495 DeclareImplicitCopyAssignment(ClassDecl);
6496 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006497
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006498 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006499 ++ASTContext::NumImplicitMoveAssignmentOperators;
6500
6501 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006502 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00006503 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
6504 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006505 DeclareImplicitMoveAssignment(ClassDecl);
6506 }
6507
Richard Smitha87b7662016-05-13 18:48:05 +00006508 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00006509 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006510
6511 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006512 // have to declare the destructor immediately. This ensures that, e.g., it
6513 // shows up in the right place in the vtable and that we diagnose problems
6514 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006515 if (ClassDecl->isDynamicClass() ||
6516 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006517 DeclareImplicitDestructor(ClassDecl);
6518 }
Douglas Gregor05379422008-11-03 17:51:48 +00006519}
6520
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006521unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006522 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006523 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006524
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006525 // The order of template parameters is not important here. All names
6526 // get added to the same scope.
6527 SmallVector<TemplateParameterList *, 4> ParameterLists;
6528
6529 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6530 D = TD->getTemplatedDecl();
6531
6532 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6533 ParameterLists.push_back(PSD->getTemplateParameters());
6534
6535 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6536 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6537 ParameterLists.push_back(DD->getTemplateParameterList(i));
6538
6539 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6540 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6541 ParameterLists.push_back(FTD->getTemplateParameters());
6542 }
6543 }
6544
6545 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6546 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6547 ParameterLists.push_back(TD->getTemplateParameterList(i));
6548
6549 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6550 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6551 ParameterLists.push_back(CTD->getTemplateParameters());
6552 }
6553 }
6554
6555 unsigned Count = 0;
6556 for (TemplateParameterList *Params : ParameterLists) {
6557 if (Params->size() > 0)
6558 // Ignore explicit specializations; they don't contribute to the template
6559 // depth.
6560 ++Count;
6561 for (NamedDecl *Param : *Params) {
6562 if (Param->getDeclName()) {
6563 S->AddDecl(Param);
6564 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006565 }
6566 }
6567 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006568
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006569 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006570}
6571
John McCall48871652010-08-21 09:40:31 +00006572void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006573 if (!RecordD) return;
6574 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006575 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006576 PushDeclContext(S, Record);
6577}
6578
John McCall48871652010-08-21 09:40:31 +00006579void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006580 if (!RecordD) return;
6581 PopDeclContext();
6582}
6583
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006584/// This is used to implement the constant expression evaluation part of the
6585/// attribute enable_if extension. There is nothing in standard C++ which would
6586/// require reentering parameters.
6587void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6588 if (!Param)
6589 return;
6590
6591 S->AddDecl(Param);
6592 if (Param->getDeclName())
6593 IdResolver.AddDecl(Param);
6594}
6595
Douglas Gregor4d87df52008-12-16 21:30:33 +00006596/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6597/// parsing a top-level (non-nested) C++ class, and we are now
6598/// parsing those parts of the given Method declaration that could
6599/// not be parsed earlier (C++ [class.mem]p2), such as default
6600/// arguments. This action should enter the scope of the given
6601/// Method declaration as if we had just parsed the qualified method
6602/// name. However, it should not bring the parameters into scope;
6603/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006604void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006605}
6606
6607/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6608/// C++ method declaration. We're (re-)introducing the given
6609/// function parameter into scope for use in parsing later parts of
6610/// the method declaration. For example, we could see an
6611/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006612void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006613 if (!ParamD)
6614 return;
Mike Stump11289f42009-09-09 15:08:12 +00006615
John McCall48871652010-08-21 09:40:31 +00006616 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006617
6618 // If this parameter has an unparsed default argument, clear it out
6619 // to make way for the parsed default argument.
6620 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006621 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006622
John McCall48871652010-08-21 09:40:31 +00006623 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006624 if (Param->getDeclName())
6625 IdResolver.AddDecl(Param);
6626}
6627
6628/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6629/// processing the delayed method declaration for Method. The method
6630/// declaration is now considered finished. There may be a separate
6631/// ActOnStartOfFunctionDef action later (not necessarily
6632/// immediately!) for this method, if it was also defined inside the
6633/// class body.
John McCall48871652010-08-21 09:40:31 +00006634void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006635 if (!MethodD)
6636 return;
Mike Stump11289f42009-09-09 15:08:12 +00006637
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006638 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006639
John McCall48871652010-08-21 09:40:31 +00006640 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006641
6642 // Now that we have our default arguments, check the constructor
6643 // again. It could produce additional diagnostics or affect whether
6644 // the class has implicitly-declared destructors, among other
6645 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006646 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6647 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006648
6649 // Check the default arguments, which we may have added.
6650 if (!Method->isInvalidDecl())
6651 CheckCXXDefaultArguments(Method);
6652}
6653
Douglas Gregor831c93f2008-11-05 20:51:48 +00006654/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006655/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006656/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006657/// emit diagnostics and set the invalid bit to true. In any case, the type
6658/// will be updated to reflect a well-formed type for the constructor and
6659/// returned.
6660QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006661 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006662 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006663
6664 // C++ [class.ctor]p3:
6665 // A constructor shall not be virtual (10.3) or static (9.4). A
6666 // constructor can be invoked for a const, volatile or const
6667 // volatile object. A constructor shall not be declared const,
6668 // volatile, or const volatile (9.3.2).
6669 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006670 if (!D.isInvalidType())
6671 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6672 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6673 << SourceRange(D.getIdentifierLoc());
6674 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006675 }
John McCall8e7d6562010-08-26 03:08:43 +00006676 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006677 if (!D.isInvalidType())
6678 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6679 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6680 << SourceRange(D.getIdentifierLoc());
6681 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006682 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006683 }
Mike Stump11289f42009-09-09 15:08:12 +00006684
David Majnemer03f705f2014-07-08 18:18:04 +00006685 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6686 diagnoseIgnoredQualifiers(
6687 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6688 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6689 D.getDeclSpec().getRestrictSpecLoc(),
6690 D.getDeclSpec().getAtomicSpecLoc());
6691 D.setInvalidType();
6692 }
6693
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006694 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006695 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006696 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006697 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6698 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006699 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006700 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6701 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006702 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006703 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6704 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006705 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006706 }
Mike Stump11289f42009-09-09 15:08:12 +00006707
Douglas Gregordb9d6642011-01-26 05:01:58 +00006708 // C++0x [class.ctor]p4:
6709 // A constructor shall not be declared with a ref-qualifier.
6710 if (FTI.hasRefQualifier()) {
6711 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6712 << FTI.RefQualifierIsLValueRef
6713 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6714 D.setInvalidType();
6715 }
6716
Douglas Gregor831c93f2008-11-05 20:51:48 +00006717 // Rebuild the function type "R" without any type qualifiers (in
6718 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006719 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006720 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006721 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006722 return R;
6723
6724 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6725 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006726 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006727
6728 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006729}
6730
Douglas Gregor4d87df52008-12-16 21:30:33 +00006731/// CheckConstructor - Checks a fully-formed constructor for
6732/// well-formedness, issuing any diagnostics required. Returns true if
6733/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006734void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006735 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006736 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6737 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006738 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006739
6740 // C++ [class.copy]p3:
6741 // A declaration of a constructor for a class X is ill-formed if
6742 // its first parameter is of type (optionally cv-qualified) X and
6743 // either there are no other parameters or else all other
6744 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006745 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006746 ((Constructor->getNumParams() == 1) ||
6747 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006748 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6749 Constructor->getTemplateSpecializationKind()
6750 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006751 QualType ParamType = Constructor->getParamDecl(0)->getType();
6752 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6753 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006754 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006755 const char *ConstRef
6756 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6757 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006758 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006759 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006760
6761 // FIXME: Rather that making the constructor invalid, we should endeavor
6762 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006763 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006764 }
6765 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006766}
6767
John McCalldeb646e2010-08-04 01:04:25 +00006768/// CheckDestructor - Checks a fully-formed destructor definition for
6769/// well-formedness, issuing any diagnostics required. Returns true
6770/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006771bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006772 CXXRecordDecl *RD = Destructor->getParent();
6773
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006774 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006775 SourceLocation Loc;
6776
6777 if (!Destructor->isImplicit())
6778 Loc = Destructor->getLocation();
6779 else
6780 Loc = RD->getLocation();
6781
6782 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006783 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006784 DeclarationName Name =
6785 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006786 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006787 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006788 // If there's no class-specific operator delete, look up the global
6789 // non-array delete.
6790 if (!OperatorDelete)
6791 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006792
Eli Friedmanfa0df832012-02-02 03:46:19 +00006793 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006794
6795 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006796 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006797
6798 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006799}
6800
Douglas Gregor831c93f2008-11-05 20:51:48 +00006801/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6802/// the well-formednes of the destructor declarator @p D with type @p
6803/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006804/// emit diagnostics and set the declarator to invalid. Even if this happens,
6805/// will be updated to reflect a well-formed type for the destructor and
6806/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006807QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006808 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006809 // C++ [class.dtor]p1:
6810 // [...] A typedef-name that names a class is a class-name
6811 // (7.1.3); however, a typedef-name that names a class shall not
6812 // be used as the identifier in the declarator for a destructor
6813 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006814 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006815 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006816 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006817 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006818 else if (const TemplateSpecializationType *TST =
6819 DeclaratorType->getAs<TemplateSpecializationType>())
6820 if (TST->isTypeAlias())
6821 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6822 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006823
6824 // C++ [class.dtor]p2:
6825 // A destructor is used to destroy objects of its class type. A
6826 // destructor takes no parameters, and no return type can be
6827 // specified for it (not even void). The address of a destructor
6828 // shall not be taken. A destructor shall not be static. A
6829 // destructor can be invoked for a const, volatile or const
6830 // volatile object. A destructor shall not be declared const,
6831 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006832 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006833 if (!D.isInvalidType())
6834 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6835 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006836 << SourceRange(D.getIdentifierLoc())
6837 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6838
John McCall8e7d6562010-08-26 03:08:43 +00006839 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006840 }
David Majnemer03f705f2014-07-08 18:18:04 +00006841 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006842 // Destructors don't have return types, but the parser will
6843 // happily parse something like:
6844 //
6845 // class X {
6846 // float ~X();
6847 // };
6848 //
6849 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006850 if (D.getDeclSpec().hasTypeSpecifier())
6851 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6852 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6853 << SourceRange(D.getIdentifierLoc());
6854 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6855 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6856 SourceLocation(),
6857 D.getDeclSpec().getConstSpecLoc(),
6858 D.getDeclSpec().getVolatileSpecLoc(),
6859 D.getDeclSpec().getRestrictSpecLoc(),
6860 D.getDeclSpec().getAtomicSpecLoc());
6861 D.setInvalidType();
6862 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006863 }
Mike Stump11289f42009-09-09 15:08:12 +00006864
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006865 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006866 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006867 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006868 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6869 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006870 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006871 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6872 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006873 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006874 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6875 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006876 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006877 }
6878
Douglas Gregordb9d6642011-01-26 05:01:58 +00006879 // C++0x [class.dtor]p2:
6880 // A destructor shall not be declared with a ref-qualifier.
6881 if (FTI.hasRefQualifier()) {
6882 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6883 << FTI.RefQualifierIsLValueRef
6884 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6885 D.setInvalidType();
6886 }
6887
Douglas Gregor831c93f2008-11-05 20:51:48 +00006888 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006889 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006890 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6891
6892 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006893 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006894 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006895 }
6896
Mike Stump11289f42009-09-09 15:08:12 +00006897 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006898 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006899 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006900 D.setInvalidType();
6901 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006902
6903 // Rebuild the function type "R" without any type qualifiers or
6904 // parameters (in case any of the errors above fired) and with
6905 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006906 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006907 if (!D.isInvalidType())
6908 return R;
6909
Douglas Gregor95755162010-07-01 05:10:53 +00006910 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006911 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6912 EPI.Variadic = false;
6913 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006914 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006915 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006916}
6917
Craig Toppere335f252015-10-04 04:53:55 +00006918static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00006919 if (Before.isInvalid())
6920 return;
6921 R.setBegin(Before.getBegin());
6922 if (R.getEnd().isInvalid())
6923 R.setEnd(Before.getEnd());
6924}
6925
Craig Toppere335f252015-10-04 04:53:55 +00006926static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00006927 if (After.isInvalid())
6928 return;
6929 if (R.getBegin().isInvalid())
6930 R.setBegin(After.getBegin());
6931 R.setEnd(After.getEnd());
6932}
6933
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006934/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6935/// well-formednes of the conversion function declarator @p D with
6936/// type @p R. If there are any errors in the declarator, this routine
6937/// will emit diagnostics and return true. Otherwise, it will return
6938/// false. Either way, the type @p R will be updated to reflect a
6939/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006940void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006941 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006942 // C++ [class.conv.fct]p1:
6943 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006944 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006945 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006946 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006947 if (!D.isInvalidType())
6948 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006949 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6950 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006951 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006952 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006953 }
John McCall212fa2e2010-04-13 00:04:31 +00006954
Richard Smitha865a162014-12-19 02:07:47 +00006955 TypeSourceInfo *ConvTSI = nullptr;
6956 QualType ConvType =
6957 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006958
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006959 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006960 // Conversion functions don't have return types, but the parser will
6961 // happily parse something like:
6962 //
6963 // class X {
6964 // float operator bool();
6965 // };
6966 //
6967 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006968 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6969 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6970 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006971 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006972 }
6973
John McCall212fa2e2010-04-13 00:04:31 +00006974 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6975
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006976 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006977 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006978 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6979
6980 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006981 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006982 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006983 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006984 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006985 D.setInvalidType();
6986 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006987
John McCall212fa2e2010-04-13 00:04:31 +00006988 // Diagnose "&operator bool()" and other such nonsense. This
6989 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006990 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006991 bool NeedsTypedef = false;
6992 SourceRange Before, After;
6993
6994 // Walk the chunks and extract information on them for our diagnostic.
6995 bool PastFunctionChunk = false;
6996 for (auto &Chunk : D.type_objects()) {
6997 switch (Chunk.Kind) {
6998 case DeclaratorChunk::Function:
6999 if (!PastFunctionChunk) {
7000 if (Chunk.Fun.HasTrailingReturnType) {
7001 TypeSourceInfo *TRT = nullptr;
7002 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7003 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7004 }
7005 PastFunctionChunk = true;
7006 break;
7007 }
7008 // Fall through.
7009 case DeclaratorChunk::Array:
7010 NeedsTypedef = true;
7011 extendRight(After, Chunk.getSourceRange());
7012 break;
7013
7014 case DeclaratorChunk::Pointer:
7015 case DeclaratorChunk::BlockPointer:
7016 case DeclaratorChunk::Reference:
7017 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00007018 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00007019 extendLeft(Before, Chunk.getSourceRange());
7020 break;
7021
7022 case DeclaratorChunk::Paren:
7023 extendLeft(Before, Chunk.Loc);
7024 extendRight(After, Chunk.EndLoc);
7025 break;
7026 }
7027 }
7028
7029 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7030 After.isValid() ? After.getBegin() :
7031 D.getIdentifierLoc();
7032 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7033 DB << Before << After;
7034
7035 if (!NeedsTypedef) {
7036 DB << /*don't need a typedef*/0;
7037
7038 // If we can provide a correct fix-it hint, do so.
7039 if (After.isInvalid() && ConvTSI) {
7040 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00007041 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00007042 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7043 << FixItHint::CreateInsertionFromRange(
7044 InsertLoc, CharSourceRange::getTokenRange(Before))
7045 << FixItHint::CreateRemoval(Before);
7046 }
7047 } else if (!Proto->getReturnType()->isDependentType()) {
7048 DB << /*typedef*/1 << Proto->getReturnType();
7049 } else if (getLangOpts().CPlusPlus11) {
7050 DB << /*alias template*/2 << Proto->getReturnType();
7051 } else {
7052 DB << /*might not be fixable*/3;
7053 }
7054
7055 // Recover by incorporating the other type chunks into the result type.
7056 // Note, this does *not* change the name of the function. This is compatible
7057 // with the GCC extension:
7058 // struct S { &operator int(); } s;
7059 // int &r = s.operator int(); // ok in GCC
7060 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007061 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007062 }
7063
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007064 // C++ [class.conv.fct]p4:
7065 // The conversion-type-id shall not represent a function type nor
7066 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007067 if (ConvType->isArrayType()) {
7068 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7069 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007070 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007071 } else if (ConvType->isFunctionType()) {
7072 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7073 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007074 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007075 }
7076
7077 // Rebuild the function type "R" without any parameters (in case any
7078 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007079 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007080 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007081 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007082
Douglas Gregor5fb53972009-01-14 15:45:31 +00007083 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007084 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007085 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007086 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007087 diag::warn_cxx98_compat_explicit_conversion_functions :
7088 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007089 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007090}
7091
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007092/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7093/// the declaration of the given C++ conversion function. This routine
7094/// is responsible for recording the conversion function in the C++
7095/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007096Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007097 assert(Conversion && "Expected to receive a conversion function declaration");
7098
Douglas Gregor4287b372008-12-12 08:25:50 +00007099 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007100
7101 // Make sure we aren't redeclaring the conversion function.
7102 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007103
7104 // C++ [class.conv.fct]p1:
7105 // [...] A conversion function is never used to convert a
7106 // (possibly cv-qualified) object to the (possibly cv-qualified)
7107 // same object type (or a reference to it), to a (possibly
7108 // cv-qualified) base class of that type (or a reference to it),
7109 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007110 // FIXME: Suppress this warning if the conversion function ends up being a
7111 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007112 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007113 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007114 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007115 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007116 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7117 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007118 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007119 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007120 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7121 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007122 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007123 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00007124 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007125 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007126 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007127 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007128 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007129 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007130 }
7131
Douglas Gregor457104e2010-09-29 04:25:11 +00007132 if (FunctionTemplateDecl *ConversionTemplate
7133 = Conversion->getDescribedFunctionTemplate())
7134 return ConversionTemplate;
7135
John McCall48871652010-08-21 09:40:31 +00007136 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007137}
7138
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007139//===----------------------------------------------------------------------===//
7140// Namespace Handling
7141//===----------------------------------------------------------------------===//
7142
Richard Smith45bb8852012-10-04 22:13:39 +00007143/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7144/// reopened.
7145static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7146 SourceLocation Loc,
7147 IdentifierInfo *II, bool *IsInline,
7148 NamespaceDecl *PrevNS) {
7149 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007150
Richard Smithf501cc32012-10-05 01:46:25 +00007151 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7152 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7153 // inline namespaces, with the intention of bringing names into namespace std.
7154 //
7155 // We support this just well enough to get that case working; this is not
7156 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007157 if (*IsInline && II && II->getName().startswith("__atomic") &&
7158 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007159 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007160 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7161 NS = NS->getPreviousDecl())
7162 NS->setInline(*IsInline);
7163 // Patch up the lookup table for the containing namespace. This isn't really
7164 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007165 for (auto *I : PrevNS->decls())
7166 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007167 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7168 return;
7169 }
7170
7171 if (PrevNS->isInline())
7172 // The user probably just forgot the 'inline', so suggest that it
7173 // be added back.
7174 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7175 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7176 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007177 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007178
7179 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7180 *IsInline = PrevNS->isInline();
7181}
John McCallb1be5232010-08-26 09:15:37 +00007182
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007183/// ActOnStartNamespaceDef - This is called at the start of a namespace
7184/// definition.
John McCall48871652010-08-21 09:40:31 +00007185Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007186 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007187 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007188 SourceLocation IdentLoc,
7189 IdentifierInfo *II,
7190 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00007191 AttributeList *AttrList,
7192 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007193 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7194 // For anonymous namespace, take the location of the left brace.
7195 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007196 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007197 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007198 bool IsStd = false;
7199 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007200 Scope *DeclRegionScope = NamespcScope->getParent();
7201
Craig Topperc3ec1492014-05-26 06:22:03 +00007202 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007203 if (II) {
7204 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007205 // The identifier in an original-namespace-definition shall not
7206 // have been previously defined in the declarative region in
7207 // which the original-namespace-definition appears. The
7208 // identifier in an original-namespace-definition is the name of
7209 // the namespace. Subsequently in that declarative region, it is
7210 // treated as an original-namespace-name.
7211 //
7212 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00007213 // look through using directives, just look for any ordinary names
7214 // as if by qualified name lookup.
7215 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7216 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00007217 NamedDecl *PrevDecl =
7218 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00007219 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00007220
Douglas Gregore57e7522012-01-07 09:11:48 +00007221 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007222 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007223 if (IsInline != PrevNS->isInline())
7224 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7225 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007226 } else if (PrevDecl) {
7227 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007228 Diag(Loc, diag::err_redefinition_different_kind)
7229 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007230 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007231 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007232 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007233 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007234 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007235 // This is the first "real" definition of the namespace "std", so update
7236 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007237 PrevNS = getStdNamespace();
7238 IsStd = true;
7239 AddToKnown = !IsInline;
7240 } else {
7241 // We've seen this namespace for the first time.
7242 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007243 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007244 } else {
John McCall4fa53422009-10-01 00:25:31 +00007245 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007246
7247 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007248 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007249 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007250 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007251 } else {
7252 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007253 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007254 }
7255
Richard Smith45bb8852012-10-04 22:13:39 +00007256 if (PrevNS && IsInline != PrevNS->isInline())
7257 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7258 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007259 }
7260
7261 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7262 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007263 if (IsInvalid)
7264 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007265
7266 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007267
Douglas Gregore57e7522012-01-07 09:11:48 +00007268 // FIXME: Should we be merging attributes?
7269 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007270 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007271
7272 if (IsStd)
7273 StdNamespace = Namespc;
7274 if (AddToKnown)
7275 KnownNamespaces[Namespc] = false;
7276
7277 if (II) {
7278 PushOnScopeChains(Namespc, DeclRegionScope);
7279 } else {
7280 // Link the anonymous namespace into its parent.
7281 DeclContext *Parent = CurContext->getRedeclContext();
7282 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7283 TU->setAnonymousNamespace(Namespc);
7284 } else {
7285 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007286 }
John McCall4fa53422009-10-01 00:25:31 +00007287
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007288 CurContext->addDecl(Namespc);
7289
John McCall4fa53422009-10-01 00:25:31 +00007290 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7291 // behaves as if it were replaced by
7292 // namespace unique { /* empty body */ }
7293 // using namespace unique;
7294 // namespace unique { namespace-body }
7295 // where all occurrences of 'unique' in a translation unit are
7296 // replaced by the same identifier and this identifier differs
7297 // from all other identifiers in the entire program.
7298
7299 // We just create the namespace with an empty name and then add an
7300 // implicit using declaration, just like the standard suggests.
7301 //
7302 // CodeGen enforces the "universally unique" aspect by giving all
7303 // declarations semantically contained within an anonymous
7304 // namespace internal linkage.
7305
Douglas Gregore57e7522012-01-07 09:11:48 +00007306 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00007307 UD = UsingDirectiveDecl::Create(Context, Parent,
7308 /* 'using' */ LBrace,
7309 /* 'namespace' */ SourceLocation(),
7310 /* qualifier */ NestedNameSpecifierLoc(),
7311 /* identifier */ SourceLocation(),
7312 Namespc,
7313 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007314 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007315 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007316 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007317 }
7318
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007319 ActOnDocumentableDecl(Namespc);
7320
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007321 // Although we could have an invalid decl (i.e. the namespace name is a
7322 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007323 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7324 // for the namespace has the declarations that showed up in that particular
7325 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007326 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007327 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007328}
7329
Sebastian Redla6602e92009-11-23 15:34:23 +00007330/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7331/// is a namespace alias, returns the namespace it points to.
7332static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7333 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7334 return AD->getNamespace();
7335 return dyn_cast_or_null<NamespaceDecl>(D);
7336}
7337
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007338/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7339/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007340void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007341 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7342 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007343 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007344 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007345 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007346 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007347}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007348
John McCall28a0cf72010-08-25 07:42:41 +00007349CXXRecordDecl *Sema::getStdBadAlloc() const {
7350 return cast_or_null<CXXRecordDecl>(
7351 StdBadAlloc.get(Context.getExternalSource()));
7352}
7353
7354NamespaceDecl *Sema::getStdNamespace() const {
7355 return cast_or_null<NamespaceDecl>(
7356 StdNamespace.get(Context.getExternalSource()));
7357}
7358
Douglas Gregorcdf87022010-06-29 17:53:46 +00007359/// \brief Retrieve the special "std" namespace, which may require us to
7360/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007361NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007362 if (!StdNamespace) {
7363 // The "std" namespace has not yet been defined, so build one implicitly.
7364 StdNamespace = NamespaceDecl::Create(Context,
7365 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007366 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007367 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007368 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007369 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007370 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007371 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007372
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007373 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007374}
7375
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007376bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007377 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007378 "Looking for std::initializer_list outside of C++.");
7379
7380 // We're looking for implicit instantiations of
7381 // template <typename E> class std::initializer_list.
7382
7383 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7384 return false;
7385
Craig Topperc3ec1492014-05-26 06:22:03 +00007386 ClassTemplateDecl *Template = nullptr;
7387 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007388
Sebastian Redl43144e72012-01-17 22:49:58 +00007389 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007390
Sebastian Redl43144e72012-01-17 22:49:58 +00007391 ClassTemplateSpecializationDecl *Specialization =
7392 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7393 if (!Specialization)
7394 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007395
Sebastian Redl43144e72012-01-17 22:49:58 +00007396 Template = Specialization->getSpecializedTemplate();
7397 Arguments = Specialization->getTemplateArgs().data();
7398 } else if (const TemplateSpecializationType *TST =
7399 Ty->getAs<TemplateSpecializationType>()) {
7400 Template = dyn_cast_or_null<ClassTemplateDecl>(
7401 TST->getTemplateName().getAsTemplateDecl());
7402 Arguments = TST->getArgs();
7403 }
7404 if (!Template)
7405 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007406
7407 if (!StdInitializerList) {
7408 // Haven't recognized std::initializer_list yet, maybe this is it.
7409 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7410 if (TemplateClass->getIdentifier() !=
7411 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007412 !getStdNamespace()->InEnclosingNamespaceSetOf(
7413 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007414 return false;
7415 // This is a template called std::initializer_list, but is it the right
7416 // template?
7417 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007418 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007419 return false;
7420 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7421 return false;
7422
7423 // It's the right template.
7424 StdInitializerList = Template;
7425 }
7426
Richard Smith7d7dee72015-02-24 03:30:14 +00007427 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007428 return false;
7429
7430 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007431 if (Element)
7432 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007433 return true;
7434}
7435
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007436static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7437 NamespaceDecl *Std = S.getStdNamespace();
7438 if (!Std) {
7439 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007440 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007441 }
7442
7443 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7444 Loc, Sema::LookupOrdinaryName);
7445 if (!S.LookupQualifiedName(Result, Std)) {
7446 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007447 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007448 }
7449 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7450 if (!Template) {
7451 Result.suppressDiagnostics();
7452 // We found something weird. Complain about the first thing we found.
7453 NamedDecl *Found = *Result.begin();
7454 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007455 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007456 }
7457
7458 // We found some template called std::initializer_list. Now verify that it's
7459 // correct.
7460 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007461 if (Params->getMinRequiredArguments() != 1 ||
7462 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007463 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007464 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007465 }
7466
7467 return Template;
7468}
7469
7470QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7471 if (!StdInitializerList) {
7472 StdInitializerList = LookupStdInitializerList(*this, Loc);
7473 if (!StdInitializerList)
7474 return QualType();
7475 }
7476
7477 TemplateArgumentListInfo Args(Loc, Loc);
7478 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7479 Context.getTrivialTypeSourceInfo(Element,
7480 Loc)));
7481 return Context.getCanonicalType(
7482 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7483}
7484
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007485bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7486 // C++ [dcl.init.list]p2:
7487 // A constructor is an initializer-list constructor if its first parameter
7488 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7489 // std::initializer_list<E> for some type E, and either there are no other
7490 // parameters or else all other parameters have default arguments.
7491 if (Ctor->getNumParams() < 1 ||
7492 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7493 return false;
7494
7495 QualType ArgType = Ctor->getParamDecl(0)->getType();
7496 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7497 ArgType = RT->getPointeeType().getUnqualifiedType();
7498
Craig Topperc3ec1492014-05-26 06:22:03 +00007499 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007500}
7501
Douglas Gregora172e082011-03-26 22:25:30 +00007502/// \brief Determine whether a using statement is in a context where it will be
7503/// apply in all contexts.
7504static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7505 switch (CurContext->getDeclKind()) {
7506 case Decl::TranslationUnit:
7507 return true;
7508 case Decl::LinkageSpec:
7509 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7510 default:
7511 return false;
7512 }
7513}
7514
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007515namespace {
7516
7517// Callback to only accept typo corrections that are namespaces.
7518class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007519public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007520 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007521 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007522 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007523 return false;
7524 }
7525};
7526
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007527}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007528
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007529static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7530 CXXScopeSpec &SS,
7531 SourceLocation IdentLoc,
7532 IdentifierInfo *Ident) {
7533 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007534 if (TypoCorrection Corrected =
7535 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7536 llvm::make_unique<NamespaceValidatorCCC>(),
7537 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007538 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007539 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7540 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007541 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007542 S.diagnoseTypo(Corrected,
7543 S.PDiag(diag::err_using_directive_member_suggest)
7544 << Ident << DC << DroppedSpecifier << SS.getRange(),
7545 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007546 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007547 S.diagnoseTypo(Corrected,
7548 S.PDiag(diag::err_using_directive_suggest) << Ident,
7549 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007550 }
Richard Smithde6d6c42015-12-29 19:43:10 +00007551 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007552 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007553 }
7554 return false;
7555}
7556
John McCall48871652010-08-21 09:40:31 +00007557Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007558 SourceLocation UsingLoc,
7559 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007560 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007561 SourceLocation IdentLoc,
7562 IdentifierInfo *NamespcName,
7563 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007564 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7565 assert(NamespcName && "Invalid NamespcName.");
7566 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007567
7568 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00007569 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00007570 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007571 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007572
Craig Topperc3ec1492014-05-26 06:22:03 +00007573 UsingDirectiveDecl *UDir = nullptr;
7574 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007575 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007576 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007577
Douglas Gregor34074322009-01-14 22:20:51 +00007578 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007579 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7580 LookupParsedName(R, S, &SS);
7581 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007582 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007583
Douglas Gregorcdf87022010-06-29 17:53:46 +00007584 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007585 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007586 // Allow "using namespace std;" or "using namespace ::std;" even if
7587 // "std" hasn't been defined yet, for GCC compatibility.
7588 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7589 NamespcName->isStr("std")) {
7590 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007591 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007592 R.resolveKind();
7593 }
7594 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007595 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007596 }
7597
John McCall9f3059a2009-10-09 21:13:30 +00007598 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00007599 NamedDecl *Named = R.getRepresentativeDecl();
7600 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
7601 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007602
Nico Riecke50e59a2014-11-24 17:29:52 +00007603 // The use of a nested name specifier may trigger deprecation warnings.
7604 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007605
Douglas Gregor889ceb72009-02-03 19:21:40 +00007606 // C++ [namespace.udir]p1:
7607 // A using-directive specifies that the names in the nominated
7608 // namespace can be used in the scope in which the
7609 // using-directive appears after the using-directive. During
7610 // unqualified name lookup (3.4.1), the names appear as if they
7611 // were declared in the nearest enclosing namespace which
7612 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007613 // namespace. [Note: in this context, "contains" means "contains
7614 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007615
7616 // Find enclosing context containing both using-directive and
7617 // nominated namespace.
7618 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7619 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7620 CommonAncestor = CommonAncestor->getParent();
7621
Sebastian Redla6602e92009-11-23 15:34:23 +00007622 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007623 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007624 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007625
Douglas Gregora172e082011-03-26 22:25:30 +00007626 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007627 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007628 Diag(IdentLoc, diag::warn_using_directive_in_header);
7629 }
7630
Douglas Gregor889ceb72009-02-03 19:21:40 +00007631 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007632 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007633 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007634 }
7635
Richard Smith54ecd982013-02-20 19:22:51 +00007636 if (UDir)
7637 ProcessDeclAttributeList(S, UDir, AttrList);
7638
John McCall48871652010-08-21 09:40:31 +00007639 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007640}
7641
7642void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007643 // If the scope has an associated entity and the using directive is at
7644 // namespace or translation unit scope, add the UsingDirectiveDecl into
7645 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007646 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007647 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007648 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007649 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007650 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007651 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007652 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007653}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007654
Douglas Gregorfec52632009-06-20 00:51:54 +00007655
John McCall48871652010-08-21 09:40:31 +00007656Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007657 AccessSpecifier AS,
7658 bool HasUsingKeyword,
7659 SourceLocation UsingLoc,
7660 CXXScopeSpec &SS,
7661 UnqualifiedId &Name,
7662 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007663 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007664 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007665 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007666
Douglas Gregor220f4272009-11-04 16:30:06 +00007667 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007668 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007669 case UnqualifiedId::IK_Identifier:
7670 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007671 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007672 case UnqualifiedId::IK_ConversionFunctionId:
7673 break;
7674
7675 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007676 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007677 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007678 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007679 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007680 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007681 diag::err_using_decl_constructor)
7682 << SS.getRange();
7683
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007684 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007685
Craig Topperc3ec1492014-05-26 06:22:03 +00007686 return nullptr;
7687
Douglas Gregor220f4272009-11-04 16:30:06 +00007688 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007689 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007690 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007691 return nullptr;
7692
Douglas Gregor220f4272009-11-04 16:30:06 +00007693 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007694 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007695 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007696 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007697 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007698
7699 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7700 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007701 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007702 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007703
Richard Smithc2bc61b2013-03-18 21:12:30 +00007704 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007705 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007706 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007707 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7708 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007709 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007710 }
7711
Douglas Gregorc4356532010-12-16 00:46:58 +00007712 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7713 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007714 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007715
John McCall3f746822009-11-17 05:59:44 +00007716 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007717 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007718 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007719 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007720 if (UD)
7721 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007722
John McCall48871652010-08-21 09:40:31 +00007723 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007724}
7725
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007726/// \brief Determine whether a using declaration considers the given
7727/// declarations as "equivalent", e.g., if they are redeclarations of
7728/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007729static bool
7730IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7731 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007732 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007733
Richard Smithdda56e42011-04-15 14:24:37 +00007734 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007735 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007736 return Context.hasSameType(TD1->getUnderlyingType(),
7737 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007738
7739 return false;
7740}
7741
7742
John McCall84d87672009-12-10 09:41:52 +00007743/// Determines whether to create a using shadow decl for a particular
7744/// decl, given the set of decls existing prior to this using lookup.
7745bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007746 const LookupResult &Previous,
7747 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007748 // Diagnose finding a decl which is not from a base class of the
7749 // current class. We do this now because there are cases where this
7750 // function will silently decide not to build a shadow decl, which
7751 // will pre-empt further diagnostics.
7752 //
Richard Smith5cbeb752016-05-05 02:13:49 +00007753 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00007754 // the qualifier.
7755 //
7756 // FIXME: diagnose the following if we care enough:
7757 // struct A { int foo; };
7758 // struct B : A { using A::foo; };
7759 // template <class T> struct C : A {};
7760 // template <class T> struct D : C<T> { using B::foo; } // <---
7761 // This is invalid (during instantiation) in C++03 because B::foo
7762 // resolves to the using decl in B, which is not a base class of D<T>.
7763 // We can't diagnose it immediately because C<T> is an unknown
7764 // specialization. The UsingShadowDecl in D<T> then points directly
7765 // to A::foo, which will look well-formed when we instantiate.
7766 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007767 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007768 DeclContext *OrigDC = Orig->getDeclContext();
7769
7770 // Handle enums and anonymous structs.
7771 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7772 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7773 while (OrigRec->isAnonymousStructOrUnion())
7774 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7775
7776 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7777 if (OrigDC == CurContext) {
7778 Diag(Using->getLocation(),
7779 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007780 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007781 Diag(Orig->getLocation(), diag::note_using_decl_target);
7782 return true;
7783 }
7784
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007785 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007786 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007787 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007788 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007789 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007790 Diag(Orig->getLocation(), diag::note_using_decl_target);
7791 return true;
7792 }
7793 }
7794
7795 if (Previous.empty()) return false;
7796
7797 NamedDecl *Target = Orig;
7798 if (isa<UsingShadowDecl>(Target))
7799 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7800
John McCalla17e83e2009-12-11 02:33:26 +00007801 // If the target happens to be one of the previous declarations, we
7802 // don't have a conflict.
7803 //
7804 // FIXME: but we might be increasing its access, in which case we
7805 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007806 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007807 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007808 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7809 I != E; ++I) {
7810 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00007811 // We can have UsingDecls in our Previous results because we use the same
7812 // LookupResult for checking whether the UsingDecl itself is a valid
7813 // redeclaration.
7814 if (isa<UsingDecl>(D))
7815 continue;
7816
Richard Smithfd8634a2013-10-23 02:17:46 +00007817 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7818 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7819 PrevShadow = Shadow;
7820 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00007821 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
7822 // We don't conflict with an existing using shadow decl of an equivalent
7823 // declaration, but we're not a redeclaration of it.
7824 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00007825 }
John McCalla17e83e2009-12-11 02:33:26 +00007826
Richard Smithf091e122015-09-15 01:28:55 +00007827 if (isVisible(D))
7828 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00007829 }
7830
Richard Smithfd8634a2013-10-23 02:17:46 +00007831 if (FoundEquivalentDecl)
7832 return false;
7833
Alp Tokera2794f92014-01-22 07:29:52 +00007834 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007835 NamedDecl *OldDecl = nullptr;
7836 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7837 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007838 case Ovl_Overload:
7839 return false;
7840
7841 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007842 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007843 break;
Richard Smith18819302014-02-06 01:31:33 +00007844
John McCall84d87672009-12-10 09:41:52 +00007845 // We found a decl with the exact signature.
7846 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007847 // If we're in a record, we want to hide the target, so we
7848 // return true (without a diagnostic) to tell the caller not to
7849 // build a shadow decl.
7850 if (CurContext->isRecord())
7851 return true;
7852
7853 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007854 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007855 break;
7856 }
7857
7858 Diag(Target->getLocation(), diag::note_using_decl_target);
7859 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7860 return true;
7861 }
7862
7863 // Target is not a function.
7864
John McCall84d87672009-12-10 09:41:52 +00007865 if (isa<TagDecl>(Target)) {
7866 // No conflict between a tag and a non-tag.
7867 if (!Tag) return false;
7868
John McCalle29c5cd2009-12-10 19:51:03 +00007869 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007870 Diag(Target->getLocation(), diag::note_using_decl_target);
7871 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7872 return true;
7873 }
7874
7875 // No conflict between a tag and a non-tag.
7876 if (!NonTag) return false;
7877
John McCalle29c5cd2009-12-10 19:51:03 +00007878 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007879 Diag(Target->getLocation(), diag::note_using_decl_target);
7880 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7881 return true;
7882}
7883
John McCall3f746822009-11-17 05:59:44 +00007884/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007885UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007886 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007887 NamedDecl *Orig,
7888 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007889
7890 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007891 NamedDecl *Target = Orig;
7892 if (isa<UsingShadowDecl>(Target)) {
7893 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7894 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007895 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007896
John McCall3f746822009-11-17 05:59:44 +00007897 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007898 = UsingShadowDecl::Create(Context, CurContext,
7899 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007900 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007901
Douglas Gregor457104e2010-09-29 04:25:11 +00007902 Shadow->setAccess(UD->getAccess());
7903 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7904 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007905
7906 Shadow->setPreviousDecl(PrevDecl);
7907
John McCall3f746822009-11-17 05:59:44 +00007908 if (S)
John McCall3969e302009-12-08 07:46:18 +00007909 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007910 else
John McCall3969e302009-12-08 07:46:18 +00007911 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007912
John McCall3969e302009-12-08 07:46:18 +00007913
John McCall84d87672009-12-10 09:41:52 +00007914 return Shadow;
7915}
John McCall3969e302009-12-08 07:46:18 +00007916
John McCall84d87672009-12-10 09:41:52 +00007917/// Hides a using shadow declaration. This is required by the current
7918/// using-decl implementation when a resolvable using declaration in a
7919/// class is followed by a declaration which would hide or override
7920/// one or more of the using decl's targets; for example:
7921///
7922/// struct Base { void foo(int); };
7923/// struct Derived : Base {
7924/// using Base::foo;
7925/// void foo(int);
7926/// };
7927///
7928/// The governing language is C++03 [namespace.udecl]p12:
7929///
7930/// When a using-declaration brings names from a base class into a
7931/// derived class scope, member functions in the derived class
7932/// override and/or hide member functions with the same name and
7933/// parameter types in a base class (rather than conflicting).
7934///
7935/// There are two ways to implement this:
7936/// (1) optimistically create shadow decls when they're not hidden
7937/// by existing declarations, or
7938/// (2) don't create any shadow decls (or at least don't make them
7939/// visible) until we've fully parsed/instantiated the class.
7940/// The problem with (1) is that we might have to retroactively remove
7941/// a shadow decl, which requires several O(n) operations because the
7942/// decl structures are (very reasonably) not designed for removal.
7943/// (2) avoids this but is very fiddly and phase-dependent.
7944void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007945 if (Shadow->getDeclName().getNameKind() ==
7946 DeclarationName::CXXConversionFunctionName)
7947 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7948
John McCall84d87672009-12-10 09:41:52 +00007949 // Remove it from the DeclContext...
7950 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007951
John McCall84d87672009-12-10 09:41:52 +00007952 // ...and the scope, if applicable...
7953 if (S) {
John McCall48871652010-08-21 09:40:31 +00007954 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007955 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007956 }
7957
John McCall84d87672009-12-10 09:41:52 +00007958 // ...and the using decl.
7959 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7960
7961 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007962 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007963}
7964
Richard Smith09d5b3a2014-05-01 00:35:04 +00007965/// Find the base specifier for a base class with the given type.
7966static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7967 QualType DesiredBase,
7968 bool &AnyDependentBases) {
7969 // Check whether the named type is a direct base class.
7970 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7971 for (auto &Base : Derived->bases()) {
7972 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7973 if (CanonicalDesiredBase == BaseType)
7974 return &Base;
7975 if (BaseType->isDependentType())
7976 AnyDependentBases = true;
7977 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007978 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007979}
7980
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007981namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007982class UsingValidatorCCC : public CorrectionCandidateCallback {
7983public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007984 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007985 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007986 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007987 IsInstantiation(IsInstantiation), OldNNS(NNS),
7988 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007989
Craig Toppera798a9d2014-03-02 09:32:10 +00007990 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007991 NamedDecl *ND = Candidate.getCorrectionDecl();
7992
7993 // Keywords are not valid here.
7994 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007995 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007996
7997 // Completely unqualified names are invalid for a 'using' declaration.
7998 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7999 return false;
8000
Richard Smith09d5b3a2014-05-01 00:35:04 +00008001 if (RequireMemberOf) {
8002 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8003 if (FoundRecord && FoundRecord->isInjectedClassName()) {
8004 // No-one ever wants a using-declaration to name an injected-class-name
8005 // of a base class, unless they're declaring an inheriting constructor.
8006 ASTContext &Ctx = ND->getASTContext();
8007 if (!Ctx.getLangOpts().CPlusPlus11)
8008 return false;
8009 QualType FoundType = Ctx.getRecordType(FoundRecord);
8010
8011 // Check that the injected-class-name is named as a member of its own
8012 // type; we don't want to suggest 'using Derived::Base;', since that
8013 // means something else.
8014 NestedNameSpecifier *Specifier =
8015 Candidate.WillReplaceSpecifier()
8016 ? Candidate.getCorrectionSpecifier()
8017 : OldNNS;
8018 if (!Specifier->getAsType() ||
8019 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8020 return false;
8021
8022 // Check that this inheriting constructor declaration actually names a
8023 // direct base class of the current class.
8024 bool AnyDependentBases = false;
8025 if (!findDirectBaseWithType(RequireMemberOf,
8026 Ctx.getRecordType(FoundRecord),
8027 AnyDependentBases) &&
8028 !AnyDependentBases)
8029 return false;
8030 } else {
8031 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8032 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8033 return false;
8034
8035 // FIXME: Check that the base class member is accessible?
8036 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00008037 } else {
8038 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8039 if (FoundRecord && FoundRecord->isInjectedClassName())
8040 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008041 }
8042
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008043 if (isa<TypeDecl>(ND))
8044 return HasTypenameKeyword || !IsInstantiation;
8045
8046 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008047 }
8048
8049private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008050 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008051 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008052 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00008053 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008054};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008055} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008056
John McCalle61f2ba2009-11-18 02:36:19 +00008057/// Builds a using declaration.
8058///
8059/// \param IsInstantiation - Whether this call arises from an
8060/// instantiation of an unresolved using declaration. We treat
8061/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008062NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8063 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008064 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008065 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008066 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008067 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008068 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008069 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008070 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008071 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008072 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008073
Anders Carlssonf038fc22009-08-28 05:49:21 +00008074 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008075
Anders Carlsson59140b32009-08-28 03:16:11 +00008076 if (SS.isEmpty()) {
8077 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008078 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008079 }
Mike Stump11289f42009-09-09 15:08:12 +00008080
John McCall84d87672009-12-10 09:41:52 +00008081 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008082 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008083 ForRedeclaration);
8084 Previous.setHideTags(false);
8085 if (S) {
8086 LookupName(Previous, S);
8087
8088 // It is really dumb that we have to do this.
8089 LookupResult::Filter F = Previous.makeFilter();
8090 while (F.hasNext()) {
8091 NamedDecl *D = F.next();
8092 if (!isDeclInScope(D, CurContext, S))
8093 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008094 // If we found a local extern declaration that's not ordinarily visible,
8095 // and this declaration is being added to a non-block scope, ignore it.
8096 // We're only checking for scope conflicts here, not also for violations
8097 // of the linkage rules.
8098 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8099 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8100 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008101 }
8102 F.done();
8103 } else {
8104 assert(IsInstantiation && "no scope in non-instantiation");
8105 assert(CurContext->isRecord() && "scope not record in instantiation");
8106 LookupQualifiedName(Previous, CurContext);
8107 }
8108
John McCall84d87672009-12-10 09:41:52 +00008109 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008110 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8111 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008112 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008113
8114 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008115 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008116 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008117
John McCall84c16cf2009-11-12 03:15:40 +00008118 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008119 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008120 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008121 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008122 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008123 // FIXME: not all declaration name kinds are legal here
8124 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8125 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008126 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008127 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008128 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008129 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8130 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008131 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008132 D->setAccess(AS);
8133 CurContext->addDecl(D);
8134 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008135 }
John McCallb96ec562009-12-04 22:46:56 +00008136
Richard Smith09d5b3a2014-05-01 00:35:04 +00008137 auto Build = [&](bool Invalid) {
8138 UsingDecl *UD =
8139 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8140 HasTypenameKeyword);
8141 UD->setAccess(AS);
8142 CurContext->addDecl(UD);
8143 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008144 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008145 };
8146 auto BuildInvalid = [&]{ return Build(true); };
8147 auto BuildValid = [&]{ return Build(false); };
8148
8149 if (RequireCompleteDeclContext(SS, LookupContext))
8150 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008151
Richard Smith78163e22015-04-01 19:31:06 +00008152 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008153 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008154
John McCall3969e302009-12-08 07:46:18 +00008155 // Unlike most lookups, we don't always want to hide tag
8156 // declarations: tag names are visible through the using declaration
8157 // even if hidden by ordinary names, *except* in a dependent context
8158 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008159 if (!IsInstantiation)
8160 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008161
John McCall5dadb652012-04-07 03:04:20 +00008162 // For the purposes of this lookup, we have a base object type
8163 // equal to that of the current context.
8164 if (CurContext->isRecord()) {
8165 R.setBaseObjectType(
8166 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8167 }
8168
John McCall27b18f82009-11-17 02:14:36 +00008169 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008170
Richard Smith78163e22015-04-01 19:31:06 +00008171 // Try to correct typos if possible. If constructor name lookup finds no
8172 // results, that means the named class has no explicit constructors, and we
8173 // suppressed declaring implicit ones (probably because it's dependent or
8174 // invalid).
8175 if (R.empty() &&
8176 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008177 if (TypoCorrection Corrected = CorrectTypo(
8178 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8179 llvm::make_unique<UsingValidatorCCC>(
8180 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8181 dyn_cast<CXXRecordDecl>(CurContext)),
8182 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008183 // We reject any correction for which ND would be NULL.
8184 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008185
Richard Smithf9b15102013-08-17 00:46:16 +00008186 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008187 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008188 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8189 << NameInfo.getName() << LookupContext << 0
8190 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008191
8192 // If we corrected to an inheriting constructor, handle it as one.
8193 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8194 if (RD && RD->isInjectedClassName()) {
8195 // Fix up the information we'll use to build the using declaration.
8196 if (Corrected.WillReplaceSpecifier()) {
8197 NestedNameSpecifierLocBuilder Builder;
8198 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8199 QualifierLoc.getSourceRange());
8200 QualifierLoc = Builder.getWithLocInContext(Context);
8201 }
8202
8203 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8204 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008205 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00008206 for (auto *Ctor : LookupConstructors(RD))
8207 R.addDecl(Ctor);
8208 } else {
8209 // FIXME: Pick up all the declarations if we found an overloaded function.
8210 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008211 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008212 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008213 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008214 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008215 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008216 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008217 }
8218
Richard Smith09d5b3a2014-05-01 00:35:04 +00008219 if (R.isAmbiguous())
8220 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008221
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008222 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008223 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008224 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008225 Diag(IdentLoc, diag::err_using_typename_non_type);
8226 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8227 Diag((*I)->getUnderlyingDecl()->getLocation(),
8228 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008229 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008230 }
8231 } else {
8232 // If we asked for a non-typename and we got a type, error out,
8233 // but only if this is an instantiation of an unresolved using
8234 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008235 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008236 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8237 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008238 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008239 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008240 }
8241
Richard Smith5cbeb752016-05-05 02:13:49 +00008242 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008243 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008244 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008245 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8246 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008247 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008248 }
Mike Stump11289f42009-09-09 15:08:12 +00008249
Richard Smith5cbeb752016-05-05 02:13:49 +00008250 // C++14 [namespace.udecl]p7:
8251 // A using-declaration shall not name a scoped enumerator.
8252 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
8253 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
8254 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
8255 << SS.getRange();
8256 return BuildInvalid();
8257 }
8258 }
8259
Richard Smith09d5b3a2014-05-01 00:35:04 +00008260 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00008261
8262 // The normal rules do not apply to inheriting constructor declarations.
8263 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8264 // Suppress access diagnostics; the access check is instead performed at the
8265 // point of use for an inheriting constructor.
8266 R.suppressDiagnostics();
8267 CheckInheritingConstructorUsingDecl(UD);
8268 return UD;
8269 }
8270
8271 // Otherwise, look up the target name.
8272
John McCall84d87672009-12-10 09:41:52 +00008273 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008274 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008275 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8276 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008277 }
John McCall3f746822009-11-17 05:59:44 +00008278
8279 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008280}
8281
Sebastian Redl08905022011-02-05 19:23:19 +00008282/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008283bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008284 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008285
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008286 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008287 assert(SourceType &&
8288 "Using decl naming constructor doesn't have type in scope spec.");
8289 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8290
8291 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008292 bool AnyDependentBases = false;
8293 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8294 AnyDependentBases);
8295 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008296 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008297 diag::err_using_decl_constructor_not_in_direct_base)
8298 << UD->getNameInfo().getSourceRange()
8299 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008300 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008301 return true;
8302 }
8303
Richard Smith09d5b3a2014-05-01 00:35:04 +00008304 if (Base)
8305 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008306
8307 return false;
8308}
8309
John McCall84d87672009-12-10 09:41:52 +00008310/// Checks that the given using declaration is not an invalid
8311/// redeclaration. Note that this is checking only for the using decl
8312/// itself, not for any ill-formedness among the UsingShadowDecls.
8313bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008314 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008315 const CXXScopeSpec &SS,
8316 SourceLocation NameLoc,
8317 const LookupResult &Prev) {
8318 // C++03 [namespace.udecl]p8:
8319 // C++0x [namespace.udecl]p10:
8320 // A using-declaration is a declaration and can therefore be used
8321 // repeatedly where (and only where) multiple declarations are
8322 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008323 //
John McCall032092f2010-11-29 18:01:58 +00008324 // That's in non-member contexts.
8325 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008326 return false;
8327
Aaron Ballman4a979672014-01-03 13:56:08 +00008328 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008329
8330 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8331 NamedDecl *D = *I;
8332
8333 bool DTypename;
8334 NestedNameSpecifier *DQual;
8335 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008336 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008337 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008338 } else if (UnresolvedUsingValueDecl *UD
8339 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8340 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008341 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008342 } else if (UnresolvedUsingTypenameDecl *UD
8343 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8344 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008345 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008346 } else continue;
8347
8348 // using decls differ if one says 'typename' and the other doesn't.
8349 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008350 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008351
8352 // using decls differ if they name different scopes (but note that
8353 // template instantiation can cause this check to trigger when it
8354 // didn't before instantiation).
8355 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8356 Context.getCanonicalNestedNameSpecifier(DQual))
8357 continue;
8358
8359 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008360 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008361 return true;
8362 }
8363
8364 return false;
8365}
8366
John McCall3969e302009-12-08 07:46:18 +00008367
John McCallb96ec562009-12-04 22:46:56 +00008368/// Checks that the given nested-name qualifier used in a using decl
8369/// in the current context is appropriately related to the current
8370/// scope. If an error is found, diagnoses it and returns true.
8371bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8372 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008373 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008374 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008375 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008376
John McCall3969e302009-12-08 07:46:18 +00008377 if (!CurContext->isRecord()) {
8378 // C++03 [namespace.udecl]p3:
8379 // C++0x [namespace.udecl]p8:
8380 // A using-declaration for a class member shall be a member-declaration.
8381
8382 // If we weren't able to compute a valid scope, it must be a
8383 // dependent class scope.
Richard Smith5cbeb752016-05-05 02:13:49 +00008384 if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
8385 auto *RD = NamedContext
8386 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
8387 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008388 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008389 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008390
John McCall3969e302009-12-08 07:46:18 +00008391 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8392 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008393
8394 // If we have a complete, non-dependent source type, try to suggest a
8395 // way to get the same effect.
8396 if (!RD)
8397 return true;
8398
8399 // Find what this using-declaration was referring to.
8400 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8401 R.setHideTags(false);
8402 R.suppressDiagnostics();
8403 LookupQualifiedName(R, RD);
8404
8405 if (R.getAsSingle<TypeDecl>()) {
8406 if (getLangOpts().CPlusPlus11) {
8407 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8408 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8409 << 0 // alias declaration
8410 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8411 NameInfo.getName().getAsString() +
8412 " = ");
8413 } else {
8414 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8415 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00008416 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00008417 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8418 << 1 // typedef declaration
8419 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8420 << FixItHint::CreateInsertion(
8421 InsertLoc, " " + NameInfo.getName().getAsString());
8422 }
8423 } else if (R.getAsSingle<VarDecl>()) {
8424 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8425 // repeating the type of the static data member here.
8426 FixItHint FixIt;
8427 if (getLangOpts().CPlusPlus11) {
8428 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8429 FixIt = FixItHint::CreateReplacement(
8430 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8431 }
8432
8433 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8434 << 2 // reference declaration
8435 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00008436 } else if (R.getAsSingle<EnumConstantDecl>()) {
8437 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8438 // repeating the type of the enumeration here, and we can't do so if
8439 // the type is anonymous.
8440 FixItHint FixIt;
8441 if (getLangOpts().CPlusPlus11) {
8442 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8443 FixIt = FixItHint::CreateReplacement(
8444 UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
8445 }
8446
8447 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8448 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
8449 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00008450 }
John McCall3969e302009-12-08 07:46:18 +00008451 return true;
8452 }
8453
8454 // Otherwise, everything is known to be fine.
8455 return false;
8456 }
8457
8458 // The current scope is a record.
8459
8460 // If the named context is dependent, we can't decide much.
8461 if (!NamedContext) {
8462 // FIXME: in C++0x, we can diagnose if we can prove that the
8463 // nested-name-specifier does not refer to a base class, which is
8464 // still possible in some cases.
8465
8466 // Otherwise we have to conservatively report that things might be
8467 // okay.
8468 return false;
8469 }
8470
8471 if (!NamedContext->isRecord()) {
8472 // Ideally this would point at the last name in the specifier,
8473 // but we don't have that level of source info.
8474 Diag(SS.getRange().getBegin(),
8475 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008476 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008477 return true;
8478 }
8479
Douglas Gregor7c842292010-12-21 07:41:49 +00008480 if (!NamedContext->isDependentContext() &&
8481 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8482 return true;
8483
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008484 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00008485 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00008486 // In a using-declaration used as a member-declaration, the
8487 // nested-name-specifier shall name a base class of the class
8488 // being defined.
8489
8490 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8491 cast<CXXRecordDecl>(NamedContext))) {
8492 if (CurContext == NamedContext) {
8493 Diag(NameLoc,
8494 diag::err_using_decl_nested_name_specifier_is_current_class)
8495 << SS.getRange();
8496 return true;
8497 }
8498
8499 Diag(SS.getRange().getBegin(),
8500 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008501 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008502 << cast<CXXRecordDecl>(CurContext)
8503 << SS.getRange();
8504 return true;
8505 }
8506
8507 return false;
8508 }
8509
8510 // C++03 [namespace.udecl]p4:
8511 // A using-declaration used as a member-declaration shall refer
8512 // to a member of a base class of the class being defined [etc.].
8513
8514 // Salient point: SS doesn't have to name a base class as long as
8515 // lookup only finds members from base classes. Therefore we can
8516 // diagnose here only if we can prove that that can't happen,
8517 // i.e. if the class hierarchies provably don't intersect.
8518
8519 // TODO: it would be nice if "definitely valid" results were cached
8520 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8521 // need to be repeated.
8522
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008523 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8524 auto Collect = [&Bases](const CXXRecordDecl *Base) {
8525 Bases.insert(Base);
8526 return true;
John McCall3969e302009-12-08 07:46:18 +00008527 };
8528
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008529 // Collect all bases. Return false if we find a dependent base.
8530 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00008531 return false;
8532
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008533 // Returns true if the base is dependent or is one of the accumulated base
8534 // classes.
8535 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8536 return !Bases.count(Base);
8537 };
8538
8539 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00008540 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008541 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8542 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00008543 return false;
8544
8545 Diag(SS.getRange().getBegin(),
8546 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008547 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008548 << cast<CXXRecordDecl>(CurContext)
8549 << SS.getRange();
8550
8551 return true;
John McCallb96ec562009-12-04 22:46:56 +00008552}
8553
Richard Smithdda56e42011-04-15 14:24:37 +00008554Decl *Sema::ActOnAliasDeclaration(Scope *S,
8555 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008556 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008557 SourceLocation UsingLoc,
8558 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008559 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00008560 TypeResult Type,
8561 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008562 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00008563 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00008564 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008565 assert((S->getFlags() & Scope::DeclScope) &&
8566 "got alias-declaration outside of declaration scope");
8567
8568 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008569 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008570
8571 bool Invalid = false;
8572 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008573 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008574 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008575
8576 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008577 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008578
8579 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008580 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008581 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008582 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8583 TInfo->getTypeLoc().getBeginLoc());
8584 }
Richard Smithdda56e42011-04-15 14:24:37 +00008585
8586 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8587 LookupName(Previous, S);
8588
8589 // Warn about shadowing the name of a template parameter.
8590 if (Previous.isSingleResult() &&
8591 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008592 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008593 Previous.clear();
8594 }
8595
8596 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8597 "name in alias declaration must be an identifier");
8598 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8599 Name.StartLocation,
8600 Name.Identifier, TInfo);
8601
8602 NewTD->setAccess(AS);
8603
8604 if (Invalid)
8605 NewTD->setInvalidDecl();
8606
Richard Smith54ecd982013-02-20 19:22:51 +00008607 ProcessDeclAttributeList(S, NewTD, AttrList);
8608
Richard Smith3f1b5d02011-05-05 21:57:07 +00008609 CheckTypedefForVariablyModifiedType(S, NewTD);
8610 Invalid |= NewTD->isInvalidDecl();
8611
Richard Smithdda56e42011-04-15 14:24:37 +00008612 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008613
8614 NamedDecl *NewND;
8615 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008616 TypeAliasTemplateDecl *OldDecl = nullptr;
8617 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008618
8619 if (TemplateParamLists.size() != 1) {
8620 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008621 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8622 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008623 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008624 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008625
Richard Smith882593f2016-04-06 17:38:58 +00008626 // Check that we can declare a template here.
8627 if (CheckTemplateDeclScope(S, TemplateParams))
8628 return nullptr;
8629
Richard Smith3f1b5d02011-05-05 21:57:07 +00008630 // Only consider previous declarations in the same scope.
8631 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8632 /*ExplicitInstantiationOrSpecialization*/false);
8633 if (!Previous.empty()) {
8634 Redeclaration = true;
8635
8636 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8637 if (!OldDecl && !Invalid) {
8638 Diag(UsingLoc, diag::err_redefinition_different_kind)
8639 << Name.Identifier;
8640
8641 NamedDecl *OldD = Previous.getRepresentativeDecl();
8642 if (OldD->getLocation().isValid())
8643 Diag(OldD->getLocation(), diag::note_previous_definition);
8644
8645 Invalid = true;
8646 }
8647
8648 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8649 if (TemplateParameterListsAreEqual(TemplateParams,
8650 OldDecl->getTemplateParameters(),
8651 /*Complain=*/true,
8652 TPL_TemplateMatch))
8653 OldTemplateParams = OldDecl->getTemplateParameters();
8654 else
8655 Invalid = true;
8656
8657 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8658 if (!Invalid &&
8659 !Context.hasSameType(OldTD->getUnderlyingType(),
8660 NewTD->getUnderlyingType())) {
8661 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8662 // but we can't reasonably accept it.
8663 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8664 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8665 if (OldTD->getLocation().isValid())
8666 Diag(OldTD->getLocation(), diag::note_previous_definition);
8667 Invalid = true;
8668 }
8669 }
8670 }
8671
8672 // Merge any previous default template arguments into our parameters,
8673 // and check the parameter list.
8674 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8675 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008676 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008677
8678 TypeAliasTemplateDecl *NewDecl =
8679 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8680 Name.Identifier, TemplateParams,
8681 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008682 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008683
8684 NewDecl->setAccess(AS);
8685
8686 if (Invalid)
8687 NewDecl->setInvalidDecl();
8688 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008689 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008690
8691 NewND = NewDecl;
8692 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00008693 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8694 setTagNameForLinkagePurposes(TD, NewTD);
8695 handleTagNumbering(TD, S);
8696 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00008697 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8698 NewND = NewTD;
8699 }
Richard Smithdda56e42011-04-15 14:24:37 +00008700
8701 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008702 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008703
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008704 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008705 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008706}
8707
Richard Smithf4634362014-09-03 23:11:22 +00008708Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8709 SourceLocation AliasLoc,
8710 IdentifierInfo *Alias, CXXScopeSpec &SS,
8711 SourceLocation IdentLoc,
8712 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008713
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008714 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008715 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8716 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008717
John McCall27b18f82009-11-17 02:14:36 +00008718 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008719 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008720
John McCall9f3059a2009-10-09 21:13:30 +00008721 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008722 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008723 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008724 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008725 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008726 }
Richard Smithf4634362014-09-03 23:11:22 +00008727 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +00008728 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +00008729
8730 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00008731 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8732 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00008733 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00008734
Richard Smith2b2a1762015-12-03 23:24:04 +00008735 // Check we're not shadowing a template parameter.
8736 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8737 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8738 PrevR.clear();
8739 }
Aaron Ballman43f40102014-11-14 22:34:56 +00008740
Richard Smith2b2a1762015-12-03 23:24:04 +00008741 // Filter out any other lookup result from an enclosing scope.
8742 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8743 /*AllowInlineNamespace*/false);
8744
8745 // Find the previous declaration and check that we can redeclare it.
8746 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +00008747 if (PrevR.isSingleResult()) {
8748 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8749 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00008750 // We already have an alias with the same name that points to the same
8751 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00008752 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8753 Prev = AD;
8754 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00008755 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8756 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +00008757 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +00008758 << AD->getNamespace();
8759 return nullptr;
8760 }
Richard Smith2b2a1762015-12-03 23:24:04 +00008761 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +00008762 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +00008763 ? diag::err_redefinition
8764 : diag::err_redefinition_different_kind;
8765 Diag(AliasLoc, DiagID) << Alias;
8766 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8767 return nullptr;
8768 }
8769 }
Mike Stump11289f42009-09-09 15:08:12 +00008770
Nico Riecke50e59a2014-11-24 17:29:52 +00008771 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008772 DiagnoseUseOfDecl(ND, IdentLoc);
8773
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008774 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008775 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008776 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008777 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +00008778 if (Prev)
8779 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +00008780
John McCalld8d0d432010-02-16 06:53:13 +00008781 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008782 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008783}
8784
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008785Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008786Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8787 CXXMethodDecl *MD) {
8788 CXXRecordDecl *ClassDecl = MD->getParent();
8789
Douglas Gregor6d880b12010-07-01 22:31:05 +00008790 // C++ [except.spec]p14:
8791 // An implicitly declared special member function (Clause 12) shall have an
8792 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008793 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008794 if (ClassDecl->isInvalidDecl())
8795 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008796
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008797 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008798 for (const auto &B : ClassDecl->bases()) {
8799 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008800 continue;
8801
Aaron Ballman574705e2014-03-13 15:41:46 +00008802 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008803 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008804 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8805 // If this is a deleted function, add it anyway. This might be conformant
8806 // with the standard. This might not. I'm not sure. It might not matter.
8807 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008808 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008809 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008810 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008811
8812 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008813 for (const auto &B : ClassDecl->vbases()) {
8814 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008815 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008816 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8817 // If this is a deleted function, add it anyway. This might be conformant
8818 // with the standard. This might not. I'm not sure. It might not matter.
8819 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008820 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008821 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008822 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008823
8824 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008825 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008826 if (F->hasInClassInitializer()) {
8827 if (Expr *E = F->getInClassInitializer())
8828 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008829 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008830 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008831 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8832 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8833 // If this is a deleted function, add it anyway. This might be conformant
8834 // with the standard. This might not. I'm not sure. It might not matter.
8835 // In particular, the problem is that this function never gets called. It
8836 // might just be ill-formed because this function attempts to refer to
8837 // a deleted function here.
8838 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008839 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008840 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008841 }
John McCalldb40c7f2010-12-14 08:05:40 +00008842
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008843 return ExceptSpec;
8844}
8845
Richard Smithc2bc61b2013-03-18 21:12:30 +00008846Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008847Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8848 CXXRecordDecl *ClassDecl = CD->getParent();
8849
8850 // C++ [except.spec]p14:
8851 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008852 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008853 if (ClassDecl->isInvalidDecl())
8854 return ExceptSpec;
8855
8856 // Inherited constructor.
8857 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8858 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8859 // FIXME: Copying or moving the parameters could add extra exceptions to the
8860 // set, as could the default arguments for the inherited constructor. This
8861 // will be addressed when we implement the resolution of core issue 1351.
8862 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8863
8864 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008865 for (const auto &B : ClassDecl->bases()) {
8866 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008867 continue;
8868
Aaron Ballman574705e2014-03-13 15:41:46 +00008869 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008870 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8871 if (BaseClassDecl == InheritedDecl)
8872 continue;
8873 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8874 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008875 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008876 }
8877 }
8878
8879 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008880 for (const auto &B : ClassDecl->vbases()) {
8881 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008882 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8883 if (BaseClassDecl == InheritedDecl)
8884 continue;
8885 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8886 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008887 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008888 }
8889 }
8890
8891 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008892 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008893 if (F->hasInClassInitializer()) {
8894 if (Expr *E = F->getInClassInitializer())
8895 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008896 } else if (const RecordType *RecordTy
8897 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8898 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8899 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8900 if (Constructor)
8901 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8902 }
8903 }
8904
Richard Smithc2bc61b2013-03-18 21:12:30 +00008905 return ExceptSpec;
8906}
8907
Richard Smith8bf22e52012-11-29 01:34:07 +00008908namespace {
8909/// RAII object to register a special member as being currently declared.
8910struct DeclaringSpecialMember {
8911 Sema &S;
8912 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +00008913 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +00008914 bool WasAlreadyBeingDeclared;
8915
8916 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith12e79312016-05-13 06:47:56 +00008917 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +00008918 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008919 if (WasAlreadyBeingDeclared)
8920 // This almost never happens, but if it does, ensure that our cache
8921 // doesn't contain a stale result.
8922 S.SpecialMemberCache.clear();
8923
8924 // FIXME: Register a note to be produced if we encounter an error while
8925 // declaring the special member.
8926 }
8927 ~DeclaringSpecialMember() {
8928 if (!WasAlreadyBeingDeclared)
8929 S.SpecialMembersBeingDeclared.erase(D);
8930 }
8931
8932 /// \brief Are we already trying to declare this special member?
8933 bool isAlreadyBeingDeclared() const {
8934 return WasAlreadyBeingDeclared;
8935 }
8936};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008937}
Richard Smith8bf22e52012-11-29 01:34:07 +00008938
Richard Smith12e79312016-05-13 06:47:56 +00008939void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
8940 // Look up any existing declarations, but don't trigger declaration of all
8941 // implicit special members with this name.
8942 DeclarationName Name = FD->getDeclName();
8943 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
8944 ForRedeclaration);
8945 for (auto *D : FD->getParent()->lookup(Name))
8946 if (auto *Acceptable = R.getAcceptableDecl(D))
8947 R.addDecl(Acceptable);
8948 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +00008949 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +00008950
8951 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
8952}
8953
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008954CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8955 CXXRecordDecl *ClassDecl) {
8956 // C++ [class.ctor]p5:
8957 // A default constructor for a class X is a constructor of class X
8958 // that can be called without an argument. If there is no
8959 // user-declared constructor for class X, a default constructor is
8960 // implicitly declared. An implicitly-declared default constructor
8961 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008962 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008963 "Should not build implicit default constructor!");
8964
Richard Smith8bf22e52012-11-29 01:34:07 +00008965 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8966 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008967 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008968
Richard Smithb5800092012-06-10 05:43:50 +00008969 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8970 CXXDefaultConstructor,
8971 false);
8972
Douglas Gregor6d880b12010-07-01 22:31:05 +00008973 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008974 CanQualType ClassType
8975 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008976 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008977 DeclarationName Name
8978 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008979 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008980 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008981 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8982 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8983 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008984 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008985 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008986
8987 if (getLangOpts().CUDA) {
8988 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8989 DefaultCon,
8990 /* ConstRHS */ false,
8991 /* Diagnose */ false);
8992 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008993
8994 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008995 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008996 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008997
Richard Smith6b02d462012-12-08 08:32:28 +00008998 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8999 // constructors is easy to compute.
9000 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9001
Douglas Gregor9672f922010-07-03 00:47:00 +00009002 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00009003 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00009004
Richard Smith12e79312016-05-13 06:47:56 +00009005 Scope *S = getScopeForContext(ClassDecl);
9006 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9007
9008 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9009 SetDeclDeleted(DefaultCon, ClassLoc);
9010
9011 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +00009012 PushOnScopeChains(DefaultCon, S, false);
9013 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00009014
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009015 return DefaultCon;
9016}
9017
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009018void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9019 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009020 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009021 !Constructor->doesThisDeclarationHaveABody() &&
9022 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00009023 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00009024
Anders Carlsson423f5d82010-04-23 16:04:08 +00009025 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00009026 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00009027
Eli Friedmaneaf34142012-10-18 20:14:08 +00009028 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009029 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00009030 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00009031 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009032 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00009033 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00009034 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00009035 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00009036 }
Douglas Gregor73193272010-09-20 16:48:21 +00009037
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009038 // The exception specification is needed because we are defining the
9039 // function.
9040 ResolveExceptionSpec(CurrentLocation,
9041 Constructor->getType()->castAs<FunctionProtoType>());
9042
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009043 SourceLocation Loc = Constructor->getLocEnd().isValid()
9044 ? Constructor->getLocEnd()
9045 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009046 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00009047
Eli Friedman276dd182013-09-05 00:02:25 +00009048 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00009049 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009050
9051 if (ASTMutationListener *L = getASTMutationListener()) {
9052 L->CompletedImplicitDefinition(Constructor);
9053 }
Richard Trieuef64e942013-10-25 00:56:00 +00009054
9055 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009056}
9057
Richard Smith938f40b2011-06-11 17:19:42 +00009058void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009059 // Perform any delayed checks on exception specifications.
9060 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00009061}
9062
Richard Smith185be182013-04-10 05:48:59 +00009063namespace {
9064/// Information on inheriting constructors to declare.
9065class InheritingConstructorInfo {
9066public:
9067 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
9068 : SemaRef(SemaRef), Derived(Derived) {
9069 // Mark the constructors that we already have in the derived class.
9070 //
9071 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9072 // unless there is a user-declared constructor with the same signature in
9073 // the class where the using-declaration appears.
9074 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9075 }
9076
9077 void inheritAll(CXXRecordDecl *RD) {
9078 visitAll(RD, &InheritingConstructorInfo::inherit);
9079 }
9080
9081private:
9082 /// Information about an inheriting constructor.
9083 struct InheritingConstructor {
9084 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00009085 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00009086
9087 /// If \c true, a constructor with this signature is already declared
9088 /// in the derived class.
9089 bool DeclaredInDerived;
9090
9091 /// The constructor which is inherited.
9092 const CXXConstructorDecl *BaseCtor;
9093
9094 /// The derived constructor we declared.
9095 CXXConstructorDecl *DerivedCtor;
9096 };
9097
9098 /// Inheriting constructors with a given canonical type. There can be at
9099 /// most one such non-template constructor, and any number of templated
9100 /// constructors.
9101 struct InheritingConstructorsForType {
9102 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009103 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9104 Templates;
Richard Smith185be182013-04-10 05:48:59 +00009105
9106 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9107 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9108 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9109 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9110 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9111 false, S.TPL_TemplateMatch))
9112 return Templates[I].second;
9113 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9114 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009115 }
Richard Smith185be182013-04-10 05:48:59 +00009116
9117 return NonTemplate;
9118 }
9119 };
9120
9121 /// Get or create the inheriting constructor record for a constructor.
9122 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9123 QualType CtorType) {
9124 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9125 .getEntry(SemaRef, Ctor);
9126 }
9127
9128 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9129
9130 /// Process all constructors for a class.
9131 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009132 for (const auto *Ctor : RD->ctors())
9133 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009134 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9135 I(RD->decls_begin()), E(RD->decls_end());
9136 I != E; ++I) {
9137 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9138 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9139 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009140 }
9141 }
Richard Smith185be182013-04-10 05:48:59 +00009142
9143 /// Note that a constructor (or constructor template) was declared in Derived.
9144 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9145 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9146 }
9147
9148 /// Inherit a single constructor.
9149 void inherit(const CXXConstructorDecl *Ctor) {
9150 const FunctionProtoType *CtorType =
9151 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009152 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009153 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9154
9155 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9156
9157 // Core issue (no number yet): the ellipsis is always discarded.
9158 if (EPI.Variadic) {
9159 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9160 SemaRef.Diag(Ctor->getLocation(),
9161 diag::note_using_decl_constructor_ellipsis);
9162 EPI.Variadic = false;
9163 }
9164
9165 // Declare a constructor for each number of parameters.
9166 //
9167 // C++11 [class.inhctor]p1:
9168 // The candidate set of inherited constructors from the class X named in
9169 // the using-declaration consists of [... modulo defects ...] for each
9170 // constructor or constructor template of X, the set of constructors or
9171 // constructor templates that results from omitting any ellipsis parameter
9172 // specification and successively omitting parameters with a default
9173 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009174 unsigned MinParams = minParamsToInherit(Ctor);
9175 unsigned Params = Ctor->getNumParams();
9176 if (Params >= MinParams) {
9177 do
9178 declareCtor(UsingLoc, Ctor,
9179 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009180 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009181 while (Params > MinParams &&
9182 Ctor->getParamDecl(--Params)->hasDefaultArg());
9183 }
Richard Smith185be182013-04-10 05:48:59 +00009184 }
9185
9186 /// Find the using-declaration which specified that we should inherit the
9187 /// constructors of \p Base.
9188 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9189 // No fancy lookup required; just look for the base constructor name
9190 // directly within the derived class.
9191 ASTContext &Context = SemaRef.Context;
9192 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9193 Context.getCanonicalType(Context.getRecordType(Base)));
Richard Smithcf4bdde2015-02-21 02:45:19 +00009194 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith185be182013-04-10 05:48:59 +00009195 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9196 }
9197
9198 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9199 // C++11 [class.inhctor]p3:
9200 // [F]or each constructor template in the candidate set of inherited
9201 // constructors, a constructor template is implicitly declared
9202 if (Ctor->getDescribedFunctionTemplate())
9203 return 0;
9204
9205 // For each non-template constructor in the candidate set of inherited
9206 // constructors other than a constructor having no parameters or a
9207 // copy/move constructor having a single parameter, a constructor is
9208 // implicitly declared [...]
9209 if (Ctor->getNumParams() == 0)
9210 return 1;
9211 if (Ctor->isCopyOrMoveConstructor())
9212 return 2;
9213
9214 // Per discussion on core reflector, never inherit a constructor which
9215 // would become a default, copy, or move constructor of Derived either.
9216 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9217 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9218 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9219 }
9220
9221 /// Declare a single inheriting constructor, inheriting the specified
9222 /// constructor, with the given type.
9223 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9224 QualType DerivedType) {
9225 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9226
9227 // C++11 [class.inhctor]p3:
9228 // ... a constructor is implicitly declared with the same constructor
9229 // characteristics unless there is a user-declared constructor with
9230 // the same signature in the class where the using-declaration appears
9231 if (Entry.DeclaredInDerived)
9232 return;
9233
9234 // C++11 [class.inhctor]p7:
9235 // If two using-declarations declare inheriting constructors with the
9236 // same signature, the program is ill-formed
9237 if (Entry.DerivedCtor) {
9238 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9239 // Only diagnose this once per constructor.
9240 if (Entry.DerivedCtor->isInvalidDecl())
9241 return;
9242 Entry.DerivedCtor->setInvalidDecl();
9243
9244 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9245 SemaRef.Diag(BaseCtor->getLocation(),
9246 diag::note_using_decl_constructor_conflict_current_ctor);
9247 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9248 diag::note_using_decl_constructor_conflict_previous_ctor);
9249 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9250 diag::note_using_decl_constructor_conflict_previous_using);
9251 } else {
9252 // Core issue (no number): if the same inheriting constructor is
9253 // produced by multiple base class constructors from the same base
9254 // class, the inheriting constructor is defined as deleted.
9255 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9256 }
9257
9258 return;
9259 }
9260
9261 ASTContext &Context = SemaRef.Context;
9262 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9263 Context.getCanonicalType(Context.getRecordType(Derived)));
9264 DeclarationNameInfo NameInfo(Name, UsingLoc);
9265
Craig Topperc3ec1492014-05-26 06:22:03 +00009266 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009267 if (const FunctionTemplateDecl *FTD =
9268 BaseCtor->getDescribedFunctionTemplate()) {
9269 TemplateParams = FTD->getTemplateParameters();
9270 // We're reusing template parameters from a different DeclContext. This
9271 // is questionable at best, but works out because the template depth in
9272 // both places is guaranteed to be 0.
9273 // FIXME: Rebuild the template parameters in the new context, and
9274 // transform the function type to refer to them.
9275 }
9276
9277 // Build type source info pointing at the using-declaration. This is
9278 // required by template instantiation.
9279 TypeSourceInfo *TInfo =
9280 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9281 FunctionProtoTypeLoc ProtoLoc =
9282 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9283
9284 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9285 Context, Derived, UsingLoc, NameInfo, DerivedType,
9286 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9287 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9288
9289 // Build an unevaluated exception specification for this constructor.
9290 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9291 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009292 EPI.ExceptionSpec.Type = EST_Unevaluated;
9293 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009294 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009295 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009296
9297 // Build the parameter declarations.
9298 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009299 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009300 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009301 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009302 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009303 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9304 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009305 PD->setScopeInfo(0, I);
9306 PD->setImplicit();
9307 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009308 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009309 }
9310
9311 // Set up the new constructor.
9312 DerivedCtor->setAccess(BaseCtor->getAccess());
9313 DerivedCtor->setParams(ParamDecls);
9314 DerivedCtor->setInheritedConstructor(BaseCtor);
9315 if (BaseCtor->isDeleted())
9316 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9317
9318 // If this is a constructor template, build the template declaration.
9319 if (TemplateParams) {
9320 FunctionTemplateDecl *DerivedTemplate =
9321 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9322 TemplateParams, DerivedCtor);
9323 DerivedTemplate->setAccess(BaseCtor->getAccess());
9324 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9325 Derived->addDecl(DerivedTemplate);
9326 } else {
9327 Derived->addDecl(DerivedCtor);
9328 }
9329
9330 Entry.BaseCtor = BaseCtor;
9331 Entry.DerivedCtor = DerivedCtor;
9332 }
9333
9334 Sema &SemaRef;
9335 CXXRecordDecl *Derived;
9336 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9337 MapType Map;
9338};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009339}
Richard Smith185be182013-04-10 05:48:59 +00009340
9341void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9342 // Defer declaring the inheriting constructors until the class is
9343 // instantiated.
9344 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009345 return;
9346
Richard Smith185be182013-04-10 05:48:59 +00009347 // Find base classes from which we might inherit constructors.
9348 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009349 for (const auto &BaseIt : ClassDecl->bases())
9350 if (BaseIt.getInheritConstructors())
9351 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009352
Richard Smith185be182013-04-10 05:48:59 +00009353 // Go no further if we're not inheriting any constructors.
9354 if (InheritedBases.empty())
9355 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009356
Richard Smith185be182013-04-10 05:48:59 +00009357 // Declare the inherited constructors.
9358 InheritingConstructorInfo ICI(*this, ClassDecl);
9359 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9360 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009361}
9362
Richard Smithc2bc61b2013-03-18 21:12:30 +00009363void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9364 CXXConstructorDecl *Constructor) {
9365 CXXRecordDecl *ClassDecl = Constructor->getParent();
9366 assert(Constructor->getInheritedConstructor() &&
9367 !Constructor->doesThisDeclarationHaveABody() &&
9368 !Constructor->isDeleted());
9369
9370 SynthesizedFunctionScope Scope(*this, Constructor);
9371 DiagnosticErrorTrap Trap(Diags);
9372 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9373 Trap.hasErrorOccurred()) {
9374 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9375 << Context.getTagDeclType(ClassDecl);
9376 Constructor->setInvalidDecl();
9377 return;
9378 }
9379
9380 SourceLocation Loc = Constructor->getLocation();
9381 Constructor->setBody(new (Context) CompoundStmt(Loc));
9382
Eli Friedman276dd182013-09-05 00:02:25 +00009383 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009384 MarkVTableUsed(CurrentLocation, ClassDecl);
9385
9386 if (ASTMutationListener *L = getASTMutationListener()) {
9387 L->CompletedImplicitDefinition(Constructor);
9388 }
9389}
9390
9391
Alexis Huntf91729462011-05-12 22:46:25 +00009392Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009393Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9394 CXXRecordDecl *ClassDecl = MD->getParent();
9395
Douglas Gregorf1203042010-07-01 19:09:28 +00009396 // C++ [except.spec]p14:
9397 // An implicitly declared special member function (Clause 12) shall have
9398 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009399 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009400 if (ClassDecl->isInvalidDecl())
9401 return ExceptSpec;
9402
Douglas Gregorf1203042010-07-01 19:09:28 +00009403 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009404 for (const auto &B : ClassDecl->bases()) {
9405 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009406 continue;
9407
Aaron Ballman574705e2014-03-13 15:41:46 +00009408 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9409 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009410 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009411 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009412
Douglas Gregorf1203042010-07-01 19:09:28 +00009413 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009414 for (const auto &B : ClassDecl->vbases()) {
9415 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9416 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009417 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009418 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009419
Douglas Gregorf1203042010-07-01 19:09:28 +00009420 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009421 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009422 if (const RecordType *RecordTy
9423 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009424 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009425 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009426 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009427
Alexis Huntf91729462011-05-12 22:46:25 +00009428 return ExceptSpec;
9429}
9430
9431CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9432 // C++ [class.dtor]p2:
9433 // If a class has no user-declared destructor, a destructor is
9434 // declared implicitly. An implicitly-declared destructor is an
9435 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009436 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009437
Richard Smith8bf22e52012-11-29 01:34:07 +00009438 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9439 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009440 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009441
Douglas Gregor7454c562010-07-02 20:37:36 +00009442 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009443 CanQualType ClassType
9444 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009445 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009446 DeclarationName Name
9447 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009448 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009449 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009450 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009451 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009452 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009453 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009454 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009455
9456 if (getLangOpts().CUDA) {
9457 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9458 Destructor,
9459 /* ConstRHS */ false,
9460 /* Diagnose */ false);
9461 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009462
9463 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009464 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009465 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009466
Richard Smith6b02d462012-12-08 08:32:28 +00009467 // We don't need to use SpecialMemberIsTrivial here; triviality for
9468 // destructors is easy to compute.
9469 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9470
Douglas Gregor7454c562010-07-02 20:37:36 +00009471 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009472 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009473
Richard Smith12e79312016-05-13 06:47:56 +00009474 Scope *S = getScopeForContext(ClassDecl);
9475 CheckImplicitSpecialMemberDeclaration(S, Destructor);
9476
9477 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9478 SetDeclDeleted(Destructor, ClassLoc);
9479
Douglas Gregor7454c562010-07-02 20:37:36 +00009480 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +00009481 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +00009482 PushOnScopeChains(Destructor, S, false);
9483 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009484
Douglas Gregorf1203042010-07-01 19:09:28 +00009485 return Destructor;
9486}
9487
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009488void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009489 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009490 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009491 !Destructor->doesThisDeclarationHaveABody() &&
9492 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009493 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009494 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009495 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009496
Douglas Gregor54818f02010-05-12 16:39:35 +00009497 if (Destructor->isInvalidDecl())
9498 return;
9499
Eli Friedmaneaf34142012-10-18 20:14:08 +00009500 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009501
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009502 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009503 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9504 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009505
Douglas Gregor54818f02010-05-12 16:39:35 +00009506 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009507 Diag(CurrentLocation, diag::note_member_synthesized_at)
9508 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9509
9510 Destructor->setInvalidDecl();
9511 return;
9512 }
9513
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009514 // The exception specification is needed because we are defining the
9515 // function.
9516 ResolveExceptionSpec(CurrentLocation,
9517 Destructor->getType()->castAs<FunctionProtoType>());
9518
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009519 SourceLocation Loc = Destructor->getLocEnd().isValid()
9520 ? Destructor->getLocEnd()
9521 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009522 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009523 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009524 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009525
9526 if (ASTMutationListener *L = getASTMutationListener()) {
9527 L->CompletedImplicitDefinition(Destructor);
9528 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009529}
9530
Richard Smith84973e52012-04-21 18:42:51 +00009531/// \brief Perform any semantic analysis which needs to be delayed until all
9532/// pending class member declarations have been parsed.
9533void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009534 // If the context is an invalid C++ class, just suppress these checks.
9535 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9536 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009537 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009538 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009539 return;
9540 }
9541 }
Richard Smith84973e52012-04-21 18:42:51 +00009542}
9543
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009544static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9545 // Don't do anything for template patterns.
9546 if (Class->getDescribedClassTemplate())
9547 return;
9548
David Majnemer474b3232015-12-31 05:36:46 +00009549 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9550 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9551
9552 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009553 for (Decl *Member : Class->decls()) {
9554 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9555 if (!CD) {
9556 // Recurse on nested classes.
9557 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9558 getDefaultArgExprsForConstructors(S, NestedRD);
9559 continue;
9560 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9561 continue;
9562 }
9563
David Majnemer474b3232015-12-31 05:36:46 +00009564 CallingConv ActualCallingConv =
9565 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9566
9567 // Skip default constructors with typical calling conventions and no default
9568 // arguments.
9569 unsigned NumParams = CD->getNumParams();
9570 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9571 continue;
9572
9573 if (LastExportedDefaultCtor) {
9574 S.Diag(LastExportedDefaultCtor->getLocation(),
9575 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9576 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9577 << CD->getDeclName();
9578 return;
9579 }
9580 LastExportedDefaultCtor = CD;
9581
9582 for (unsigned I = 0; I != NumParams; ++I) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009583 // Skip any default arguments that we've already instantiated.
9584 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9585 continue;
9586
9587 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9588 CD->getParamDecl(I)).get();
David Majnemer9321f922015-06-11 02:38:06 +00009589 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009590 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9591 }
9592 }
9593}
9594
Hans Wennborg99000c22015-08-15 01:18:16 +00009595void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009596 auto *RD = dyn_cast<CXXRecordDecl>(D);
9597
9598 // Default constructors that are annotated with __declspec(dllexport) which
9599 // have default arguments or don't use the standard calling convention are
9600 // wrapped with a thunk called the default constructor closure.
9601 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9602 getDefaultArgExprsForConstructors(*this, RD);
Hans Wennborg99000c22015-08-15 01:18:16 +00009603
Reid Kleckner5b640342016-02-26 19:51:02 +00009604 referenceDLLExportedClassMethods();
9605}
9606
9607void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +00009608 if (!DelayedDllExportClasses.empty()) {
9609 // Calling ReferenceDllExportedMethods might cause the current function to
9610 // be called again, so use a local copy of DelayedDllExportClasses.
9611 SmallVector<CXXRecordDecl *, 4> WorkList;
9612 std::swap(DelayedDllExportClasses, WorkList);
9613 for (CXXRecordDecl *Class : WorkList)
9614 ReferenceDllExportedMethods(*this, Class);
9615 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009616}
9617
Richard Smithd3b5c9082012-07-27 04:22:15 +00009618void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9619 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009620 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009621 "adjusting dtor exception specs was introduced in c++11");
9622
Sebastian Redl623ea822011-05-19 05:13:44 +00009623 // C++11 [class.dtor]p3:
9624 // A declaration of a destructor that does not have an exception-
9625 // specification is implicitly considered to have the same exception-
9626 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009627 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009628 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009629 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009630 return;
9631
Chandler Carruth9a797572011-09-20 04:55:26 +00009632 // Replace the destructor's type, building off the existing one. Fortunately,
9633 // the only thing of interest in the destructor type is its extended info.
9634 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009635 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009636 EPI.ExceptionSpec.Type = EST_Unevaluated;
9637 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009638 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009639
Sebastian Redl623ea822011-05-19 05:13:44 +00009640 // FIXME: If the destructor has a body that could throw, and the newly created
9641 // spec doesn't allow exceptions, we should emit a warning, because this
9642 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009643 // However, we don't have a body or an exception specification yet, so it
9644 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009645}
9646
Pavel Labath58934982013-08-30 08:52:28 +00009647namespace {
9648/// \brief An abstract base class for all helper classes used in building the
9649// copy/move operators. These classes serve as factory functions and help us
9650// avoid using the same Expr* in the AST twice.
9651class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +00009652 ExprBuilder(const ExprBuilder&) = delete;
9653 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +00009654
9655protected:
9656 static Expr *assertNotNull(Expr *E) {
9657 assert(E && "Expression construction must not fail.");
9658 return E;
9659 }
9660
9661public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009662 ExprBuilder() {}
9663 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +00009664
9665 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9666};
9667
9668class RefBuilder: public ExprBuilder {
9669 VarDecl *Var;
9670 QualType VarType;
9671
9672public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009673 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009674 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009675 }
9676
9677 RefBuilder(VarDecl *Var, QualType VarType)
9678 : Var(Var), VarType(VarType) {}
9679};
9680
9681class ThisBuilder: public ExprBuilder {
9682public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009683 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009684 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009685 }
9686};
9687
9688class CastBuilder: public ExprBuilder {
9689 const ExprBuilder &Builder;
9690 QualType Type;
9691 ExprValueKind Kind;
9692 const CXXCastPath &Path;
9693
9694public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009695 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009696 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9697 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009698 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009699 }
9700
9701 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9702 const CXXCastPath &Path)
9703 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9704};
9705
9706class DerefBuilder: public ExprBuilder {
9707 const ExprBuilder &Builder;
9708
9709public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009710 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009711 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009712 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009713 }
9714
9715 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9716};
9717
9718class MemberBuilder: public ExprBuilder {
9719 const ExprBuilder &Builder;
9720 QualType Type;
9721 CXXScopeSpec SS;
9722 bool IsArrow;
9723 LookupResult &MemberLookup;
9724
9725public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009726 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009727 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009728 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +00009729 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009730 }
9731
9732 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9733 LookupResult &MemberLookup)
9734 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9735 MemberLookup(MemberLookup) {}
9736};
9737
9738class MoveCastBuilder: public ExprBuilder {
9739 const ExprBuilder &Builder;
9740
9741public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009742 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009743 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9744 }
9745
9746 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9747};
9748
9749class LvalueConvBuilder: public ExprBuilder {
9750 const ExprBuilder &Builder;
9751
9752public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009753 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009754 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009755 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009756 }
9757
9758 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9759};
9760
9761class SubscriptBuilder: public ExprBuilder {
9762 const ExprBuilder &Base;
9763 const ExprBuilder &Index;
9764
9765public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009766 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009767 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009768 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009769 }
9770
9771 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9772 : Base(Base), Index(Index) {}
9773};
9774
9775} // end anonymous namespace
9776
Richard Smith41ae3282012-11-14 00:50:40 +00009777/// When generating a defaulted copy or move assignment operator, if a field
9778/// should be copied with __builtin_memcpy rather than via explicit assignments,
9779/// do so. This optimization only applies for arrays of scalars, and for arrays
9780/// of class type where the selected copy/move-assignment operator is trivial.
9781static StmtResult
9782buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009783 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009784 // Compute the size of the memory buffer to be copied.
9785 QualType SizeType = S.Context.getSizeType();
9786 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9787 S.Context.getTypeSizeInChars(T).getQuantity());
9788
9789 // Take the address of the field references for "from" and "to". We
9790 // directly construct UnaryOperators here because semantic analysis
9791 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009792 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009793 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9794 S.Context.getPointerType(From->getType()),
9795 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009796 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009797 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9798 S.Context.getPointerType(To->getType()),
9799 VK_RValue, OK_Ordinary, Loc);
9800
9801 const Type *E = T->getBaseElementTypeUnsafe();
9802 bool NeedsCollectableMemCpy =
9803 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9804
9805 // Create a reference to the __builtin_objc_memmove_collectable function
9806 StringRef MemCpyName = NeedsCollectableMemCpy ?
9807 "__builtin_objc_memmove_collectable" :
9808 "__builtin_memcpy";
9809 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9810 Sema::LookupOrdinaryName);
9811 S.LookupName(R, S.TUScope, true);
9812
9813 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9814 if (!MemCpy)
9815 // Something went horribly wrong earlier, and we will have complained
9816 // about it.
9817 return StmtError();
9818
9819 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009820 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009821 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9822
9823 Expr *CallArgs[] = {
9824 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9825 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009826 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009827 Loc, CallArgs, Loc);
9828
9829 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009830 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009831}
9832
Sebastian Redl22653ba2011-08-30 19:58:05 +00009833/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009834/// \c To.
9835///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009836/// This routine is used to copy/move the members of a class with an
9837/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009838/// copied are arrays, this routine builds for loops to copy them.
9839///
9840/// \param S The Sema object used for type-checking.
9841///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009842/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009843///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009844/// \param T The type of the expressions being copied/moved. Both expressions
9845/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009846///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009847/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009848///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009849/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009850///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009851/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009852/// Otherwise, it's a non-static member subobject.
9853///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009854/// \param Copying Whether we're copying or moving.
9855///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009856/// \param Depth Internal parameter recording the depth of the recursion.
9857///
Richard Smith41ae3282012-11-14 00:50:40 +00009858/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9859/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009860static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009861buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009862 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009863 bool CopyingBaseSubobject, bool Copying,
9864 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009865 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009866 // Each subobject is assigned in the manner appropriate to its type:
9867 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009868 // - if the subobject is of class type, as if by a call to operator= with
9869 // the subobject as the object expression and the corresponding
9870 // subobject of x as a single function argument (as if by explicit
9871 // qualification; that is, ignoring any possible virtual overriding
9872 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009873 //
9874 // C++03 [class.copy]p13:
9875 // - if the subobject is of class type, the copy assignment operator for
9876 // the class is used (as if by explicit qualification; that is,
9877 // ignoring any possible virtual overriding functions in more derived
9878 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009879 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9880 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009881
Douglas Gregorb139cd52010-05-01 20:49:11 +00009882 // Look for operator=.
9883 DeclarationName Name
9884 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9885 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9886 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009887
Richard Smith52c0b582012-11-13 00:54:12 +00009888 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9889 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009890 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009891 LookupResult::Filter F = OpLookup.makeFilter();
9892 while (F.hasNext()) {
9893 NamedDecl *D = F.next();
9894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9895 if (Method->isCopyAssignmentOperator() ||
9896 (!Copying && Method->isMoveAssignmentOperator()))
9897 continue;
9898
9899 F.erase();
9900 }
9901 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009902 }
Richard Smith52c0b582012-11-13 00:54:12 +00009903
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009904 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009905 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009906 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009907 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009908 // ambiguities), we need to cast "this" to that subobject type; to
9909 // ensure that we don't go through the virtual call mechanism, we need
9910 // to qualify the operator= name with the base class (see below). However,
9911 // this means that if the base class has a protected copy assignment
9912 // operator, the protected member access check will fail. So, we
9913 // rewrite "protected" access to "public" access in this case, since we
9914 // know by construction that we're calling from a derived class.
9915 if (CopyingBaseSubobject) {
9916 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9917 L != LEnd; ++L) {
9918 if (L.getAccess() == AS_protected)
9919 L.setAccess(AS_public);
9920 }
9921 }
Richard Smith52c0b582012-11-13 00:54:12 +00009922
Douglas Gregorb139cd52010-05-01 20:49:11 +00009923 // Create the nested-name-specifier that will be used to qualify the
9924 // reference to operator=; this is required to suppress the virtual
9925 // call mechanism.
9926 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009927 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009928 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009929 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009930 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009931 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009932
Douglas Gregorb139cd52010-05-01 20:49:11 +00009933 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009934 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009935 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9936 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009937 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009938 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00009939 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009940 /*SuppressQualifierCheck=*/true);
9941 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009942 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009943
Douglas Gregorb139cd52010-05-01 20:49:11 +00009944 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009945
Pavel Labath58934982013-08-30 08:52:28 +00009946 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009947 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009948 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009949 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009950 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009951 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009952
Richard Smith41ae3282012-11-14 00:50:40 +00009953 // If we built a call to a trivial 'operator=' while copying an array,
9954 // bail out. We'll replace the whole shebang with a memcpy.
9955 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9956 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009957 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009958
Richard Smith52c0b582012-11-13 00:54:12 +00009959 // Convert to an expression-statement, and clean up any produced
9960 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009961 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009962 }
John McCallab8c2732010-03-16 06:11:48 +00009963
Richard Smith52c0b582012-11-13 00:54:12 +00009964 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009965 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009966 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009967 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009968 ExprResult Assignment = S.CreateBuiltinBinOp(
9969 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009970 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009971 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009972 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009973 }
Richard Smith52c0b582012-11-13 00:54:12 +00009974
9975 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009976 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009977
Douglas Gregorb139cd52010-05-01 20:49:11 +00009978 // Construct a loop over the array bounds, e.g.,
9979 //
9980 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9981 //
9982 // that will copy each of the array elements.
9983 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009984
Douglas Gregorb139cd52010-05-01 20:49:11 +00009985 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009986 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009987 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009988 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009989 llvm::raw_svector_ostream OS(Str);
9990 OS << "__i" << Depth;
9991 IterationVarName = &S.Context.Idents.get(OS.str());
9992 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009993 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009994 IterationVarName, SizeType,
9995 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009996 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009997
Douglas Gregorb139cd52010-05-01 20:49:11 +00009998 // Initialize the iteration variable to zero.
9999 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010000 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010001
Pavel Labath58934982013-08-30 08:52:28 +000010002 // Creates a reference to the iteration variable.
10003 RefBuilder IterationVarRef(IterationVar, SizeType);
10004 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000010005
Douglas Gregorb139cd52010-05-01 20:49:11 +000010006 // Create the DeclStmt that holds the iteration variable.
10007 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010008
Douglas Gregorb139cd52010-05-01 20:49:11 +000010009 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000010010 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10011 MoveCastBuilder FromIndexMove(FromIndexCopy);
10012 const ExprBuilder *FromIndex;
10013 if (Copying)
10014 FromIndex = &FromIndexCopy;
10015 else
10016 FromIndex = &FromIndexMove;
10017
10018 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010019
10020 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000010021 StmtResult Copy =
10022 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000010023 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000010024 Copying, Depth + 1);
10025 // Bail out if copying fails or if we determined that we should use memcpy.
10026 if (Copy.isInvalid() || !Copy.get())
10027 return Copy;
10028
10029 // Create the comparison against the array bound.
10030 llvm::APInt Upper
10031 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10032 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000010033 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000010034 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10035 BO_NE, S.Context.BoolTy,
10036 VK_RValue, OK_Ordinary, Loc, false);
10037
10038 // Create the pre-increment of the iteration variable.
10039 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000010040 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10041 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010042
Douglas Gregorb139cd52010-05-01 20:49:11 +000010043 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +000010044 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010045 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +000010046 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010047 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010048}
10049
Richard Smith41ae3282012-11-14 00:50:40 +000010050static StmtResult
10051buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010052 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010053 bool CopyingBaseSubobject, bool Copying) {
10054 // Maybe we should use a memcpy?
10055 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10056 T.isTriviallyCopyableType(S.Context))
10057 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10058
10059 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10060 CopyingBaseSubobject,
10061 Copying, 0));
10062
10063 // If we ended up picking a trivial assignment operator for an array of a
10064 // non-trivially-copyable class type, just emit a memcpy.
10065 if (!Result.isInvalid() && !Result.get())
10066 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10067
10068 return Result;
10069}
10070
Richard Smithd3b5c9082012-07-27 04:22:15 +000010071Sema::ImplicitExceptionSpecification
10072Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10073 CXXRecordDecl *ClassDecl = MD->getParent();
10074
10075 ImplicitExceptionSpecification ExceptSpec(*this);
10076 if (ClassDecl->isInvalidDecl())
10077 return ExceptSpec;
10078
10079 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010080 assert(T->getNumParams() == 1 && "not a copy assignment op");
10081 unsigned ArgQuals =
10082 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010083
Douglas Gregor68e11362010-07-01 17:48:08 +000010084 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000010085 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000010086 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000010087
10088 // It is unspecified whether or not an implicit copy assignment operator
10089 // attempts to deduplicate calls to assignment operators of virtual bases are
10090 // made. As such, this exception specification is effectively unspecified.
10091 // Based on a similar decision made for constness in C++0x, we're erring on
10092 // the side of assuming such calls to be made regardless of whether they
10093 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000010094 for (const auto &Base : ClassDecl->bases()) {
10095 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000010096 continue;
10097
Douglas Gregor330b9cf2010-07-02 21:50:04 +000010098 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010099 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010100 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10101 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010102 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000010103 }
Alexis Hunt491ec602011-06-21 23:42:56 +000010104
Aaron Ballman445a9392014-03-13 16:15:17 +000010105 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010106 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010107 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010108 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10109 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010110 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010111 }
10112
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010113 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010114 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010115 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10116 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010117 LookupCopyingAssignment(FieldClassDecl,
10118 ArgQuals | FieldType.getCVRQualifiers(),
10119 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010120 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010121 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010122 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010123
Richard Smithd3b5c9082012-07-27 04:22:15 +000010124 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010125}
10126
10127CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10128 // Note: The following rules are largely analoguous to the copy
10129 // constructor rules. Note that virtual bases are not taken into account
10130 // for determining the argument type of the operator. Note also that
10131 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010132 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010133
Richard Smith8bf22e52012-11-29 01:34:07 +000010134 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10135 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010136 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010137
Alexis Hunt119f3652011-05-14 05:23:20 +000010138 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10139 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010140 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10141 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010142 ArgType = ArgType.withConst();
10143 ArgType = Context.getLValueReferenceType(ArgType);
10144
Richard Smith99005e62013-05-07 03:19:20 +000010145 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10146 CXXCopyAssignment,
10147 Const);
10148
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010149 // An implicitly-declared copy assignment operator is an inline public
10150 // member of its class.
10151 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010152 SourceLocation ClassLoc = ClassDecl->getLocation();
10153 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010154 CXXMethodDecl *CopyAssignment =
10155 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010156 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10157 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010158 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010159 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010160 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010161
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010162 if (getLangOpts().CUDA) {
10163 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10164 CopyAssignment,
10165 /* ConstRHS */ Const,
10166 /* Diagnose */ false);
10167 }
10168
Richard Smithd3b5c9082012-07-27 04:22:15 +000010169 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010170 FunctionProtoType::ExtProtoInfo EPI =
10171 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010172 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010173
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010174 // Add the parameter to the operator.
10175 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010176 ClassLoc, ClassLoc,
10177 /*Id=*/nullptr, ArgType,
10178 /*TInfo=*/nullptr, SC_None,
10179 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010180 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010181
Richard Smith6b02d462012-12-08 08:32:28 +000010182 CopyAssignment->setTrivial(
10183 ClassDecl->needsOverloadResolutionForCopyAssignment()
10184 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10185 : ClassDecl->hasTrivialCopyAssignment());
10186
Richard Smith6b02d462012-12-08 08:32:28 +000010187 // Note that we have added this copy-assignment operator.
10188 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10189
Richard Smith12e79312016-05-13 06:47:56 +000010190 Scope *S = getScopeForContext(ClassDecl);
10191 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10192
10193 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10194 SetDeclDeleted(CopyAssignment, ClassLoc);
10195
10196 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000010197 PushOnScopeChains(CopyAssignment, S, false);
10198 ClassDecl->addDecl(CopyAssignment);
10199
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010200 return CopyAssignment;
10201}
10202
Richard Smithd577fbb2013-06-13 03:23:42 +000010203/// Diagnose an implicit copy operation for a class which is odr-used, but
10204/// which is deprecated because the class has a user-declared copy constructor,
10205/// copy assignment operator, or destructor.
10206static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10207 SourceLocation UseLoc) {
10208 assert(CopyOp->isImplicit());
10209
10210 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010211 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010212
10213 // In Microsoft mode, assignment operations don't affect constructors and
10214 // vice versa.
10215 if (RD->hasUserDeclaredDestructor()) {
10216 UserDeclaredOperation = RD->getDestructor();
10217 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10218 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010219 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010220 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010221 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010222 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010223 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010224 break;
10225 }
10226 }
10227 assert(UserDeclaredOperation);
10228 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10229 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010230 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010231 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010232 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010233 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010234 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010235 break;
10236 }
10237 }
10238 assert(UserDeclaredOperation);
10239 }
10240
10241 if (UserDeclaredOperation) {
10242 S.Diag(UserDeclaredOperation->getLocation(),
10243 diag::warn_deprecated_copy_operation)
10244 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10245 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10246 S.Diag(UseLoc, diag::note_member_synthesized_at)
10247 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10248 : Sema::CXXCopyAssignment)
10249 << RD;
10250 }
10251}
10252
Douglas Gregorb139cd52010-05-01 20:49:11 +000010253void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10254 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010255 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010256 CopyAssignOperator->isOverloadedOperator() &&
10257 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010258 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10259 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010260 "DefineImplicitCopyAssignment called for wrong function");
10261
10262 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10263
10264 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10265 CopyAssignOperator->setInvalidDecl();
10266 return;
10267 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010268
10269 // C++11 [class.copy]p18:
10270 // The [definition of an implicitly declared copy assignment operator] is
10271 // deprecated if the class has a user-declared copy constructor or a
10272 // user-declared destructor.
10273 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10274 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10275
Eli Friedman276dd182013-09-05 00:02:25 +000010276 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010277
Eli Friedmaneaf34142012-10-18 20:14:08 +000010278 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010279 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010280
10281 // C++0x [class.copy]p30:
10282 // The implicitly-defined or explicitly-defaulted copy assignment operator
10283 // for a non-union class X performs memberwise copy assignment of its
10284 // subobjects. The direct base classes of X are assigned first, in the
10285 // order of their declaration in the base-specifier-list, and then the
10286 // immediate non-static data members of X are assigned, in the order in
10287 // which they were declared in the class definition.
10288
10289 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010290 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010291
10292 // The parameter for the "other" object, which we are copying from.
10293 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10294 Qualifiers OtherQuals = Other->getType().getQualifiers();
10295 QualType OtherRefType = Other->getType();
10296 if (const LValueReferenceType *OtherRef
10297 = OtherRefType->getAs<LValueReferenceType>()) {
10298 OtherRefType = OtherRef->getPointeeType();
10299 OtherQuals = OtherRefType.getQualifiers();
10300 }
10301
10302 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010303 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10304 ? CopyAssignOperator->getLocEnd()
10305 : CopyAssignOperator->getLocation();
10306
Pavel Labath58934982013-08-30 08:52:28 +000010307 // Builds a DeclRefExpr for the "other" object.
10308 RefBuilder OtherRef(Other, OtherRefType);
10309
10310 // Builds the "this" pointer.
10311 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010312
10313 // Assign base classes.
10314 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010315 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010316 // Form the assignment:
10317 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010318 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010319 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010320 Invalid = true;
10321 continue;
10322 }
10323
John McCallcf142162010-08-07 06:22:56 +000010324 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010325 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010326
Douglas Gregorb139cd52010-05-01 20:49:11 +000010327 // Construct the "from" expression, which is an implicit cast to the
10328 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010329 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10330 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010331
10332 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010333 DerefBuilder DerefThis(This);
10334 CastBuilder To(DerefThis,
10335 Context.getCVRQualifiedType(
10336 BaseType, CopyAssignOperator->getTypeQualifiers()),
10337 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010338
10339 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010340 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010341 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010342 /*CopyingBaseSubobject=*/true,
10343 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010344 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010345 Diag(CurrentLocation, diag::note_member_synthesized_at)
10346 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10347 CopyAssignOperator->setInvalidDecl();
10348 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010349 }
10350
10351 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010352 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010353 }
10354
Douglas Gregorb139cd52010-05-01 20:49:11 +000010355 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010356 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010357 // FIXME: We should form some kind of AST representation for the implied
10358 // memcpy in a union copy operation.
10359 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010360 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010361
10362 if (Field->isInvalidDecl()) {
10363 Invalid = true;
10364 continue;
10365 }
10366
Douglas Gregorb139cd52010-05-01 20:49:11 +000010367 // Check for members of reference type; we can't copy those.
10368 if (Field->getType()->isReferenceType()) {
10369 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10370 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10371 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010372 Diag(CurrentLocation, diag::note_member_synthesized_at)
10373 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010374 Invalid = true;
10375 continue;
10376 }
10377
10378 // Check for members of const-qualified, non-class type.
10379 QualType BaseType = Context.getBaseElementType(Field->getType());
10380 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10381 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10382 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10383 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010384 Diag(CurrentLocation, diag::note_member_synthesized_at)
10385 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010386 Invalid = true;
10387 continue;
10388 }
John McCall1b1a1db2011-06-17 00:18:42 +000010389
10390 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010391 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10392 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010393
10394 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010395 if (FieldType->isIncompleteArrayType()) {
10396 assert(ClassDecl->hasFlexibleArrayMember() &&
10397 "Incomplete array type is not valid");
10398 continue;
10399 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010400
10401 // Build references to the field in the object we're copying from and to.
10402 CXXScopeSpec SS; // Intentionally empty
10403 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10404 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010405 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010406 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010407
10408 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10409
10410 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010411
Douglas Gregorb139cd52010-05-01 20:49:11 +000010412 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010413 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010414 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010415 /*CopyingBaseSubobject=*/false,
10416 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010417 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010418 Diag(CurrentLocation, diag::note_member_synthesized_at)
10419 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10420 CopyAssignOperator->setInvalidDecl();
10421 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010422 }
10423
10424 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010425 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010426 }
10427
10428 if (!Invalid) {
10429 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010430 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010431
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010432 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010433 if (Return.isInvalid())
10434 Invalid = true;
10435 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010436 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010437
10438 if (Trap.hasErrorOccurred()) {
10439 Diag(CurrentLocation, diag::note_member_synthesized_at)
10440 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10441 Invalid = true;
10442 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010443 }
10444 }
10445
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010446 // The exception specification is needed because we are defining the
10447 // function.
10448 ResolveExceptionSpec(CurrentLocation,
10449 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10450
Douglas Gregorb139cd52010-05-01 20:49:11 +000010451 if (Invalid) {
10452 CopyAssignOperator->setInvalidDecl();
10453 return;
10454 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010455
10456 StmtResult Body;
10457 {
10458 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010459 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010460 /*isStmtExpr=*/false);
10461 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10462 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010463 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010464
10465 if (ASTMutationListener *L = getASTMutationListener()) {
10466 L->CompletedImplicitDefinition(CopyAssignOperator);
10467 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010468}
10469
Sebastian Redl22653ba2011-08-30 19:58:05 +000010470Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010471Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10472 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010473
Richard Smithd3b5c9082012-07-27 04:22:15 +000010474 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010475 if (ClassDecl->isInvalidDecl())
10476 return ExceptSpec;
10477
10478 // C++0x [except.spec]p14:
10479 // An implicitly declared special member function (Clause 12) shall have an
10480 // exception-specification. [...]
10481
10482 // It is unspecified whether or not an implicit move assignment operator
10483 // attempts to deduplicate calls to assignment operators of virtual bases are
10484 // made. As such, this exception specification is effectively unspecified.
10485 // Based on a similar decision made for constness in C++0x, we're erring on
10486 // the side of assuming such calls to be made regardless of whether they
10487 // actually happen.
10488 // Note that a move constructor is not implicitly declared when there are
10489 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010490 for (const auto &Base : ClassDecl->bases()) {
10491 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010492 continue;
10493
10494 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010495 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010496 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010497 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010498 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010499 }
10500
Aaron Ballman445a9392014-03-13 16:15:17 +000010501 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010502 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010503 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010504 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010505 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010506 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010507 }
10508
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010509 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010510 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010511 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010512 if (CXXMethodDecl *MoveAssign =
10513 LookupMovingAssignment(FieldClassDecl,
10514 FieldType.getCVRQualifiers(),
10515 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010516 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010517 }
10518 }
10519
10520 return ExceptSpec;
10521}
10522
10523CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010524 assert(ClassDecl->needsImplicitMoveAssignment());
10525
Richard Smith8bf22e52012-11-29 01:34:07 +000010526 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10527 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010528 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010529
Sebastian Redl22653ba2011-08-30 19:58:05 +000010530 // Note: The following rules are largely analoguous to the move
10531 // constructor rules.
10532
Sebastian Redl22653ba2011-08-30 19:58:05 +000010533 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10534 QualType RetType = Context.getLValueReferenceType(ArgType);
10535 ArgType = Context.getRValueReferenceType(ArgType);
10536
Richard Smith99005e62013-05-07 03:19:20 +000010537 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10538 CXXMoveAssignment,
10539 false);
10540
Sebastian Redl22653ba2011-08-30 19:58:05 +000010541 // An implicitly-declared move assignment operator is an inline public
10542 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010543 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10544 SourceLocation ClassLoc = ClassDecl->getLocation();
10545 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010546 CXXMethodDecl *MoveAssignment =
10547 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010548 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010549 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010550 MoveAssignment->setAccess(AS_public);
10551 MoveAssignment->setDefaulted();
10552 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010553
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010554 if (getLangOpts().CUDA) {
10555 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10556 MoveAssignment,
10557 /* ConstRHS */ false,
10558 /* Diagnose */ false);
10559 }
10560
Richard Smithd3b5c9082012-07-27 04:22:15 +000010561 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010562 FunctionProtoType::ExtProtoInfo EPI =
10563 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010564 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010565
Sebastian Redl22653ba2011-08-30 19:58:05 +000010566 // Add the parameter to the operator.
10567 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010568 ClassLoc, ClassLoc,
10569 /*Id=*/nullptr, ArgType,
10570 /*TInfo=*/nullptr, SC_None,
10571 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010572 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010573
Richard Smith6b02d462012-12-08 08:32:28 +000010574 MoveAssignment->setTrivial(
10575 ClassDecl->needsOverloadResolutionForMoveAssignment()
10576 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10577 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010578
Richard Smith12e79312016-05-13 06:47:56 +000010579 // Note that we have added this copy-assignment operator.
10580 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10581
10582 Scope *S = getScopeForContext(ClassDecl);
10583 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
10584
Richard Smithd951a1d2012-02-18 02:02:13 +000010585 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010586 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10587 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010588 }
10589
Richard Smith12e79312016-05-13 06:47:56 +000010590 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000010591 PushOnScopeChains(MoveAssignment, S, false);
10592 ClassDecl->addDecl(MoveAssignment);
10593
Sebastian Redl22653ba2011-08-30 19:58:05 +000010594 return MoveAssignment;
10595}
10596
Richard Smithb2504bd2013-11-04 04:26:14 +000010597/// Check if we're implicitly defining a move assignment operator for a class
10598/// with virtual bases. Such a move assignment might move-assign the virtual
10599/// base multiple times.
10600static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10601 SourceLocation CurrentLocation) {
10602 assert(!Class->isDependentContext() && "should not define dependent move");
10603
10604 // Only a virtual base could get implicitly move-assigned multiple times.
10605 // Only a non-trivial move assignment can observe this. We only want to
10606 // diagnose if we implicitly define an assignment operator that assigns
10607 // two base classes, both of which move-assign the same virtual base.
10608 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10609 Class->getNumBases() < 2)
10610 return;
10611
10612 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10613 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10614 VBaseMap VBases;
10615
Aaron Ballman574705e2014-03-13 15:41:46 +000010616 for (auto &BI : Class->bases()) {
10617 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010618 while (!Worklist.empty()) {
10619 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10620 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10621
10622 // If the base has no non-trivial move assignment operators,
10623 // we don't care about moves from it.
10624 if (!Base->hasNonTrivialMoveAssignment())
10625 continue;
10626
10627 // If there's nothing virtual here, skip it.
10628 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10629 continue;
10630
10631 // If we're not actually going to call a move assignment for this base,
10632 // or the selected move assignment is trivial, skip it.
10633 Sema::SpecialMemberOverloadResult *SMOR =
10634 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10635 /*ConstArg*/false, /*VolatileArg*/false,
10636 /*RValueThis*/true, /*ConstThis*/false,
10637 /*VolatileThis*/false);
10638 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10639 !SMOR->getMethod()->isMoveAssignmentOperator())
10640 continue;
10641
10642 if (BaseSpec->isVirtual()) {
10643 // We're going to move-assign this virtual base, and its move
10644 // assignment operator is not trivial. If this can happen for
10645 // multiple distinct direct bases of Class, diagnose it. (If it
10646 // only happens in one base, we'll diagnose it when synthesizing
10647 // that base class's move assignment operator.)
10648 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010649 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010650 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010651 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010652 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10653 << Class << Base;
10654 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10655 << (Base->getCanonicalDecl() ==
10656 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10657 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010658 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010659 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010660 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10661 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010662
10663 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010664 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010665 }
10666 } else {
10667 // Only walk over bases that have defaulted move assignment operators.
10668 // We assume that any user-provided move assignment operator handles
10669 // the multiple-moves-of-vbase case itself somehow.
10670 if (!SMOR->getMethod()->isDefaulted())
10671 continue;
10672
10673 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010674 for (auto &BI : Base->bases())
10675 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010676 }
10677 }
10678 }
10679}
10680
Sebastian Redl22653ba2011-08-30 19:58:05 +000010681void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10682 CXXMethodDecl *MoveAssignOperator) {
10683 assert((MoveAssignOperator->isDefaulted() &&
10684 MoveAssignOperator->isOverloadedOperator() &&
10685 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010686 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10687 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010688 "DefineImplicitMoveAssignment called for wrong function");
10689
10690 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10691
10692 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10693 MoveAssignOperator->setInvalidDecl();
10694 return;
10695 }
10696
Eli Friedman276dd182013-09-05 00:02:25 +000010697 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010698
Eli Friedmaneaf34142012-10-18 20:14:08 +000010699 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010700 DiagnosticErrorTrap Trap(Diags);
10701
10702 // C++0x [class.copy]p28:
10703 // The implicitly-defined or move assignment operator for a non-union class
10704 // X performs memberwise move assignment of its subobjects. The direct base
10705 // classes of X are assigned first, in the order of their declaration in the
10706 // base-specifier-list, and then the immediate non-static data members of X
10707 // are assigned, in the order in which they were declared in the class
10708 // definition.
10709
Richard Smithb2504bd2013-11-04 04:26:14 +000010710 // Issue a warning if our implicit move assignment operator will move
10711 // from a virtual base more than once.
10712 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010713
Sebastian Redl22653ba2011-08-30 19:58:05 +000010714 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010715 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010716
10717 // The parameter for the "other" object, which we are move from.
10718 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10719 QualType OtherRefType = Other->getType()->
10720 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010721 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010722 "Bad argument type of defaulted move assignment");
10723
10724 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010725 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10726 ? MoveAssignOperator->getLocEnd()
10727 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010728
Pavel Labath58934982013-08-30 08:52:28 +000010729 // Builds a reference to the "other" object.
10730 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010731 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010732 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010733
Pavel Labath58934982013-08-30 08:52:28 +000010734 // Builds the "this" pointer.
10735 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010736
Sebastian Redl22653ba2011-08-30 19:58:05 +000010737 // Assign base classes.
10738 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010739 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010740 // C++11 [class.copy]p28:
10741 // It is unspecified whether subobjects representing virtual base classes
10742 // are assigned more than once by the implicitly-defined copy assignment
10743 // operator.
10744 // FIXME: Do not assign to a vbase that will be assigned by some other base
10745 // class. For a move-assignment, this can result in the vbase being moved
10746 // multiple times.
10747
Sebastian Redl22653ba2011-08-30 19:58:05 +000010748 // Form the assignment:
10749 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010750 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010751 if (!BaseType->isRecordType()) {
10752 Invalid = true;
10753 continue;
10754 }
10755
10756 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010757 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010758
10759 // Construct the "from" expression, which is an implicit cast to the
10760 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010761 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010762
10763 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010764 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010765
10766 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010767 CastBuilder To(DerefThis,
10768 Context.getCVRQualifiedType(
10769 BaseType, MoveAssignOperator->getTypeQualifiers()),
10770 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010771
10772 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010773 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010774 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010775 /*CopyingBaseSubobject=*/true,
10776 /*Copying=*/false);
10777 if (Move.isInvalid()) {
10778 Diag(CurrentLocation, diag::note_member_synthesized_at)
10779 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10780 MoveAssignOperator->setInvalidDecl();
10781 return;
10782 }
10783
10784 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010785 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010786 }
10787
Sebastian Redl22653ba2011-08-30 19:58:05 +000010788 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010789 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010790 // FIXME: We should form some kind of AST representation for the implied
10791 // memcpy in a union copy operation.
10792 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010793 continue;
10794
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010795 if (Field->isInvalidDecl()) {
10796 Invalid = true;
10797 continue;
10798 }
10799
Sebastian Redl22653ba2011-08-30 19:58:05 +000010800 // Check for members of reference type; we can't move those.
10801 if (Field->getType()->isReferenceType()) {
10802 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10803 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10804 Diag(Field->getLocation(), diag::note_declared_at);
10805 Diag(CurrentLocation, diag::note_member_synthesized_at)
10806 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10807 Invalid = true;
10808 continue;
10809 }
10810
10811 // Check for members of const-qualified, non-class type.
10812 QualType BaseType = Context.getBaseElementType(Field->getType());
10813 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10814 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10815 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10816 Diag(Field->getLocation(), diag::note_declared_at);
10817 Diag(CurrentLocation, diag::note_member_synthesized_at)
10818 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10819 Invalid = true;
10820 continue;
10821 }
10822
10823 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010824 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10825 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010826
10827 QualType FieldType = Field->getType().getNonReferenceType();
10828 if (FieldType->isIncompleteArrayType()) {
10829 assert(ClassDecl->hasFlexibleArrayMember() &&
10830 "Incomplete array type is not valid");
10831 continue;
10832 }
10833
10834 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010835 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10836 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010837 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010838 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010839 MemberBuilder From(MoveOther, OtherRefType,
10840 /*IsArrow=*/false, MemberLookup);
10841 MemberBuilder To(This, getCurrentThisType(),
10842 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010843
Pavel Labath58934982013-08-30 08:52:28 +000010844 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010845 "Member reference with rvalue base must be rvalue except for reference "
10846 "members, which aren't allowed for move assignment.");
10847
Sebastian Redl22653ba2011-08-30 19:58:05 +000010848 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010849 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010850 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010851 /*CopyingBaseSubobject=*/false,
10852 /*Copying=*/false);
10853 if (Move.isInvalid()) {
10854 Diag(CurrentLocation, diag::note_member_synthesized_at)
10855 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10856 MoveAssignOperator->setInvalidDecl();
10857 return;
10858 }
Richard Smith11d19592012-11-12 23:33:00 +000010859
Sebastian Redl22653ba2011-08-30 19:58:05 +000010860 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010861 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010862 }
10863
10864 if (!Invalid) {
10865 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010866 ExprResult ThisObj =
10867 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10868
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010869 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010870 if (Return.isInvalid())
10871 Invalid = true;
10872 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010873 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010874
10875 if (Trap.hasErrorOccurred()) {
10876 Diag(CurrentLocation, diag::note_member_synthesized_at)
10877 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10878 Invalid = true;
10879 }
10880 }
10881 }
10882
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010883 // The exception specification is needed because we are defining the
10884 // function.
10885 ResolveExceptionSpec(CurrentLocation,
10886 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10887
Sebastian Redl22653ba2011-08-30 19:58:05 +000010888 if (Invalid) {
10889 MoveAssignOperator->setInvalidDecl();
10890 return;
10891 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010892
10893 StmtResult Body;
10894 {
10895 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010896 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010897 /*isStmtExpr=*/false);
10898 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10899 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010900 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010901
10902 if (ASTMutationListener *L = getASTMutationListener()) {
10903 L->CompletedImplicitDefinition(MoveAssignOperator);
10904 }
10905}
10906
Richard Smithd3b5c9082012-07-27 04:22:15 +000010907Sema::ImplicitExceptionSpecification
10908Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10909 CXXRecordDecl *ClassDecl = MD->getParent();
10910
10911 ImplicitExceptionSpecification ExceptSpec(*this);
10912 if (ClassDecl->isInvalidDecl())
10913 return ExceptSpec;
10914
10915 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010916 assert(T->getNumParams() >= 1 && "not a copy ctor");
10917 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010918
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010919 // C++ [except.spec]p14:
10920 // An implicitly declared special member function (Clause 12) shall have an
10921 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010922 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010923 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010924 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010925 continue;
10926
Douglas Gregora6d69502010-07-02 23:41:54 +000010927 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010928 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010929 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010930 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010931 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010932 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010933 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010934 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010935 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010936 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010937 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010938 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010939 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010940 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010941 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010942 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10943 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010944 LookupCopyingConstructor(FieldClassDecl,
10945 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010946 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010947 }
10948 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010949
Richard Smithd3b5c9082012-07-27 04:22:15 +000010950 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010951}
10952
10953CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10954 CXXRecordDecl *ClassDecl) {
10955 // C++ [class.copy]p4:
10956 // If the class definition does not explicitly declare a copy
10957 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010958 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010959
Richard Smith8bf22e52012-11-29 01:34:07 +000010960 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10961 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010962 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010963
Alexis Hunt913820d2011-05-13 06:10:58 +000010964 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10965 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010966 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010967 if (Const)
10968 ArgType = ArgType.withConst();
10969 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010970
Richard Smithb5800092012-06-10 05:43:50 +000010971 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10972 CXXCopyConstructor,
10973 Const);
10974
Douglas Gregor54be3392010-07-01 17:57:27 +000010975 DeclarationName Name
10976 = Context.DeclarationNames.getCXXConstructorName(
10977 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010978 SourceLocation ClassLoc = ClassDecl->getLocation();
10979 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010980
10981 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010982 // member of its class.
10983 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010984 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010985 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010986 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010987 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010988 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010989
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010990 if (getLangOpts().CUDA) {
10991 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10992 CopyConstructor,
10993 /* ConstRHS */ Const,
10994 /* Diagnose */ false);
10995 }
10996
Richard Smithd3b5c9082012-07-27 04:22:15 +000010997 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010998 FunctionProtoType::ExtProtoInfo EPI =
10999 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011000 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011001 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011002
Douglas Gregor54be3392010-07-01 17:57:27 +000011003 // Add the parameter to the constructor.
11004 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011005 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011006 /*IdentifierInfo=*/nullptr,
11007 ArgType, /*TInfo=*/nullptr,
11008 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011009 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011010
Richard Smith6b02d462012-12-08 08:32:28 +000011011 CopyConstructor->setTrivial(
11012 ClassDecl->needsOverloadResolutionForCopyConstructor()
11013 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11014 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011015
Richard Smith6b02d462012-12-08 08:32:28 +000011016 // Note that we have declared this constructor.
11017 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11018
Richard Smith12e79312016-05-13 06:47:56 +000011019 Scope *S = getScopeForContext(ClassDecl);
11020 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11021
11022 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11023 SetDeclDeleted(CopyConstructor, ClassLoc);
11024
11025 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011026 PushOnScopeChains(CopyConstructor, S, false);
11027 ClassDecl->addDecl(CopyConstructor);
11028
Douglas Gregor54be3392010-07-01 17:57:27 +000011029 return CopyConstructor;
11030}
11031
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011032void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011033 CXXConstructorDecl *CopyConstructor) {
11034 assert((CopyConstructor->isDefaulted() &&
11035 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011036 !CopyConstructor->doesThisDeclarationHaveABody() &&
11037 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011038 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011039
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011040 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011041 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011042
Richard Smithd577fbb2013-06-13 03:23:42 +000011043 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011044 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011045 // deprecated if the class has a user-declared copy assignment operator
11046 // or a user-declared destructor.
11047 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11048 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11049
Eli Friedmaneaf34142012-10-18 20:14:08 +000011050 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011051 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011052
David Blaikie3fc2f912013-01-17 05:26:25 +000011053 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011054 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011055 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011056 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011057 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011058 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011059 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11060 ? CopyConstructor->getLocEnd()
11061 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011062 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011063 CopyConstructor->setBody(
11064 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011065 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011066
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011067 // The exception specification is needed because we are defining the
11068 // function.
11069 ResolveExceptionSpec(CurrentLocation,
11070 CopyConstructor->getType()->castAs<FunctionProtoType>());
11071
Eli Friedman276dd182013-09-05 00:02:25 +000011072 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011073 MarkVTableUsed(CurrentLocation, ClassDecl);
11074
Sebastian Redlab238a72011-04-24 16:28:06 +000011075 if (ASTMutationListener *L = getASTMutationListener()) {
11076 L->CompletedImplicitDefinition(CopyConstructor);
11077 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011078}
11079
Sebastian Redl22653ba2011-08-30 19:58:05 +000011080Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011081Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11082 CXXRecordDecl *ClassDecl = MD->getParent();
11083
Sebastian Redl22653ba2011-08-30 19:58:05 +000011084 // C++ [except.spec]p14:
11085 // An implicitly declared special member function (Clause 12) shall have an
11086 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000011087 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011088 if (ClassDecl->isInvalidDecl())
11089 return ExceptSpec;
11090
11091 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000011092 for (const auto &B : ClassDecl->bases()) {
11093 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011094 continue;
11095
Aaron Ballman574705e2014-03-13 15:41:46 +000011096 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011097 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011098 CXXConstructorDecl *Constructor =
11099 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011100 // If this is a deleted function, add it anyway. This might be conformant
11101 // with the standard. This might not. I'm not sure. It might not matter.
11102 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000011103 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011104 }
11105 }
11106
11107 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000011108 for (const auto &B : ClassDecl->vbases()) {
11109 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011110 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011111 CXXConstructorDecl *Constructor =
11112 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011113 // If this is a deleted function, add it anyway. This might be conformant
11114 // with the standard. This might not. I'm not sure. It might not matter.
11115 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011116 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011117 }
11118 }
11119
11120 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011121 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011122 QualType FieldType = Context.getBaseElementType(F->getType());
11123 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11124 CXXConstructorDecl *Constructor =
11125 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011126 // If this is a deleted function, add it anyway. This might be conformant
11127 // with the standard. This might not. I'm not sure. It might not matter.
11128 // In particular, the problem is that this function never gets called. It
11129 // might just be ill-formed because this function attempts to refer to
11130 // a deleted function here.
11131 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011132 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011133 }
11134 }
11135
11136 return ExceptSpec;
11137}
11138
11139CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11140 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011141 assert(ClassDecl->needsImplicitMoveConstructor());
11142
Richard Smith8bf22e52012-11-29 01:34:07 +000011143 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11144 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011145 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011146
Sebastian Redl22653ba2011-08-30 19:58:05 +000011147 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11148 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011149
Richard Smithb5800092012-06-10 05:43:50 +000011150 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11151 CXXMoveConstructor,
11152 false);
11153
Sebastian Redl22653ba2011-08-30 19:58:05 +000011154 DeclarationName Name
11155 = Context.DeclarationNames.getCXXConstructorName(
11156 Context.getCanonicalType(ClassType));
11157 SourceLocation ClassLoc = ClassDecl->getLocation();
11158 DeclarationNameInfo NameInfo(Name, ClassLoc);
11159
Richard Smith99005e62013-05-07 03:19:20 +000011160 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011161 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011162 // member of its class.
11163 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011164 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011165 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011166 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011167 MoveConstructor->setAccess(AS_public);
11168 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011169
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011170 if (getLangOpts().CUDA) {
11171 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11172 MoveConstructor,
11173 /* ConstRHS */ false,
11174 /* Diagnose */ false);
11175 }
11176
Richard Smithd3b5c9082012-07-27 04:22:15 +000011177 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011178 FunctionProtoType::ExtProtoInfo EPI =
11179 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011180 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011181 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011182
Sebastian Redl22653ba2011-08-30 19:58:05 +000011183 // Add the parameter to the constructor.
11184 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11185 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011186 /*IdentifierInfo=*/nullptr,
11187 ArgType, /*TInfo=*/nullptr,
11188 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011189 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011190
Richard Smith6b02d462012-12-08 08:32:28 +000011191 MoveConstructor->setTrivial(
11192 ClassDecl->needsOverloadResolutionForMoveConstructor()
11193 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11194 : ClassDecl->hasTrivialMoveConstructor());
11195
Richard Smith12e79312016-05-13 06:47:56 +000011196 // Note that we have declared this constructor.
11197 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11198
11199 Scope *S = getScopeForContext(ClassDecl);
11200 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
11201
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000011202 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011203 ClassDecl->setImplicitMoveConstructorIsDeleted();
11204 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011205 }
11206
Richard Smith12e79312016-05-13 06:47:56 +000011207 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011208 PushOnScopeChains(MoveConstructor, S, false);
11209 ClassDecl->addDecl(MoveConstructor);
11210
11211 return MoveConstructor;
11212}
11213
11214void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11215 CXXConstructorDecl *MoveConstructor) {
11216 assert((MoveConstructor->isDefaulted() &&
11217 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011218 !MoveConstructor->doesThisDeclarationHaveABody() &&
11219 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011220 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11221
11222 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11223 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11224
Eli Friedmaneaf34142012-10-18 20:14:08 +000011225 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011226 DiagnosticErrorTrap Trap(Diags);
11227
David Blaikie3fc2f912013-01-17 05:26:25 +000011228 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011229 Trap.hasErrorOccurred()) {
11230 Diag(CurrentLocation, diag::note_member_synthesized_at)
11231 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11232 MoveConstructor->setInvalidDecl();
11233 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011234 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11235 ? MoveConstructor->getLocEnd()
11236 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011237 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011238 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011239 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011240 }
11241
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011242 // The exception specification is needed because we are defining the
11243 // function.
11244 ResolveExceptionSpec(CurrentLocation,
11245 MoveConstructor->getType()->castAs<FunctionProtoType>());
11246
Eli Friedman276dd182013-09-05 00:02:25 +000011247 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011248 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011249
11250 if (ASTMutationListener *L = getASTMutationListener()) {
11251 L->CompletedImplicitDefinition(MoveConstructor);
11252 }
11253}
11254
Douglas Gregor74f7d502012-02-15 19:33:52 +000011255bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011256 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011257}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011258
11259void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011260 SourceLocation CurrentLocation,
11261 CXXConversionDecl *Conv) {
11262 CXXRecordDecl *Lambda = Conv->getParent();
11263 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11264 // If we are defining a specialization of a conversion to function-ptr
11265 // cache the deduced template arguments for this specialization
11266 // so that we can use them to retrieve the corresponding call-operator
11267 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011268 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11269
Faisal Vali571df122013-09-29 08:45:24 +000011270 // Retrieve the corresponding call-operator specialization.
11271 if (Lambda->isGenericLambda()) {
11272 assert(Conv->isFunctionTemplateSpecialization());
11273 FunctionTemplateDecl *CallOpTemplate =
11274 CallOp->getDescribedFunctionTemplate();
11275 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011276 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011277 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011278 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011279 InsertPos);
11280 assert(CallOpSpec &&
11281 "Conversion operator must have a corresponding call operator");
11282 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11283 }
11284 // Mark the call operator referenced (and add to pending instantiations
11285 // if necessary).
11286 // For both the conversion and static-invoker template specializations
11287 // we construct their body's in this function, so no need to add them
11288 // to the PendingInstantiations.
11289 MarkFunctionReferenced(CurrentLocation, CallOp);
11290
Eli Friedmaneaf34142012-10-18 20:14:08 +000011291 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011292 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011293
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011294 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011295 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11296 // ... and get the corresponding specialization for a generic lambda.
11297 if (Lambda->isGenericLambda()) {
11298 assert(DeducedTemplateArgs &&
11299 "Must have deduced template arguments from Conversion Operator");
11300 FunctionTemplateDecl *InvokeTemplate =
11301 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011302 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011303 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011304 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011305 InsertPos);
11306 assert(InvokeSpec &&
11307 "Must have a corresponding static invoker specialization");
11308 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11309 }
11310 // Construct the body of the conversion function { return __invoke; }.
11311 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011312 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011313 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011314 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011315 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11316 Conv->getLocation(),
11317 Conv->getLocation()));
11318
11319 Conv->markUsed(Context);
11320 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011321
Faisal Vali571df122013-09-29 08:45:24 +000011322 // Fill in the __invoke function with a dummy implementation. IR generation
11323 // will fill in the actual details.
11324 Invoker->markUsed(Context);
11325 Invoker->setReferenced();
11326 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11327
Douglas Gregord3b672c2012-02-16 01:06:16 +000011328 if (ASTMutationListener *L = getASTMutationListener()) {
11329 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011330 L->CompletedImplicitDefinition(Invoker);
11331 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011332}
11333
Faisal Vali571df122013-09-29 08:45:24 +000011334
11335
Douglas Gregord3b672c2012-02-16 01:06:16 +000011336void Sema::DefineImplicitLambdaToBlockPointerConversion(
11337 SourceLocation CurrentLocation,
11338 CXXConversionDecl *Conv)
11339{
Faisal Vali850da1a2013-09-29 17:08:32 +000011340 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011341
Eli Friedman276dd182013-09-05 00:02:25 +000011342 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011343
Eli Friedmaneaf34142012-10-18 20:14:08 +000011344 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011345 DiagnosticErrorTrap Trap(Diags);
11346
Douglas Gregored90df32012-02-22 05:02:47 +000011347 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011348 Expr *This = ActOnCXXThis(CurrentLocation).get();
11349 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011350
Eli Friedman98b01ed2012-03-01 04:01:32 +000011351 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11352 Conv->getLocation(),
11353 Conv, DerefThis);
11354
11355 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11356 // behavior. Note that only the general conversion function does this
11357 // (since it's unusable otherwise); in the case where we inline the
11358 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011359 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011360 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11361 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011362 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011363
11364 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011365 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011366 Conv->setInvalidDecl();
11367 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011368 }
Douglas Gregored90df32012-02-22 05:02:47 +000011369
Douglas Gregored90df32012-02-22 05:02:47 +000011370 // Create the return statement that returns the block from the conversion
11371 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011372 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011373 if (Return.isInvalid()) {
11374 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11375 Conv->setInvalidDecl();
11376 return;
11377 }
11378
11379 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011380 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011381 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011382 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011383 Conv->getLocation()));
11384
Douglas Gregored90df32012-02-22 05:02:47 +000011385 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011386 if (ASTMutationListener *L = getASTMutationListener()) {
11387 L->CompletedImplicitDefinition(Conv);
11388 }
11389}
11390
Douglas Gregord2f70072012-03-10 06:53:13 +000011391/// \brief Determine whether the given list arguments contains exactly one
11392/// "real" (non-default) argument.
11393static bool hasOneRealArgument(MultiExprArg Args) {
11394 switch (Args.size()) {
11395 case 0:
11396 return false;
11397
11398 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011399 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011400 return false;
11401
11402 // fall through
11403 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011404 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011405 }
11406
11407 return false;
11408}
11409
John McCalldadc5752010-08-24 06:29:42 +000011410ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011411Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000011412 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000011413 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011414 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011415 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011416 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011417 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011418 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011419 unsigned ConstructKind,
11420 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011421 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011422
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011423 // C++0x [class.copy]p34:
11424 // When certain criteria are met, an implementation is allowed to
11425 // omit the copy/move construction of a class object, even if the
11426 // copy/move constructor and/or destructor for the object have
11427 // side effects. [...]
11428 // - when a temporary class object that has not been bound to a
11429 // reference (12.2) would be copied/moved to a class object
11430 // with the same cv-unqualified type, the copy/move operation
11431 // can be omitted by constructing the temporary object
11432 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011433 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011434 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011435 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011436 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011437 }
Mike Stump11289f42009-09-09 15:08:12 +000011438
Richard Smithc2bebe92016-05-11 20:37:46 +000011439 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
11440 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011441 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011442 IsListInitialization,
11443 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011444 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011445}
11446
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011447/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11448/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011449ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011450Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000011451 NamedDecl *FoundDecl,
11452 CXXConstructorDecl *Constructor,
11453 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011454 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011455 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011456 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011457 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011458 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011459 unsigned ConstructKind,
11460 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011461 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011462 return CXXConstructExpr::Create(
Richard Smithc2bebe92016-05-11 20:37:46 +000011463 Context, DeclInitType, ConstructLoc, FoundDecl, Constructor, Elidable,
11464 ExprArgs, HadMultipleCandidates, IsListInitialization,
11465 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011466 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11467 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011468}
11469
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011470ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11471 assert(Field->hasInClassInitializer());
11472
11473 // If we already have the in-class initializer nothing needs to be done.
11474 if (Field->getInClassInitializer())
11475 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11476
11477 // Maybe we haven't instantiated the in-class initializer. Go check the
11478 // pattern FieldDecl to see if it has one.
11479 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11480
11481 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11482 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11483 DeclContext::lookup_result Lookup =
11484 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000011485
11486 // Lookup can return at most two results: the pattern for the field, or the
11487 // injected class name of the parent record. No other member can have the
11488 // same name as the field.
11489 assert(!Lookup.empty() && Lookup.size() <= 2 &&
11490 "more than two lookup results for field name");
11491 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
11492 if (!Pattern) {
11493 assert(isa<CXXRecordDecl>(Lookup[0]) &&
11494 "cannot have other non-field member with same name");
11495 Pattern = cast<FieldDecl>(Lookup[1]);
11496 }
11497
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011498 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11499 getTemplateInstantiationArgs(Field)))
11500 return ExprError();
11501 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11502 }
11503
11504 // DR1351:
11505 // If the brace-or-equal-initializer of a non-static data member
11506 // invokes a defaulted default constructor of its class or of an
11507 // enclosing class in a potentially evaluated subexpression, the
11508 // program is ill-formed.
11509 //
11510 // This resolution is unworkable: the exception specification of the
11511 // default constructor can be needed in an unevaluated context, in
11512 // particular, in the operand of a noexcept-expression, and we can be
11513 // unable to compute an exception specification for an enclosed class.
11514 //
11515 // Any attempt to resolve the exception specification of a defaulted default
11516 // constructor before the initializer is lexically complete will ultimately
11517 // come here at which point we can diagnose it.
11518 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11519 if (OutermostClass == ParentRD) {
11520 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11521 << ParentRD << Field;
11522 } else {
11523 Diag(Field->getLocEnd(),
11524 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11525 << ParentRD << OutermostClass << Field;
11526 }
11527
11528 return ExprError();
11529}
11530
John McCall03c48482010-02-02 09:10:11 +000011531void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011532 if (VD->isInvalidDecl()) return;
11533
John McCall03c48482010-02-02 09:10:11 +000011534 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011535 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011536 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011537 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011538
Chandler Carruth86d17d32011-03-27 21:26:48 +000011539 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011540 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011541 CheckDestructorAccess(VD->getLocation(), Destructor,
11542 PDiag(diag::err_access_dtor_var)
11543 << VD->getDeclName()
11544 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011545 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011546
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011547 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011548 if (!VD->hasGlobalStorage()) return;
11549
11550 // Emit warning for non-trivial dtor in global scope (a real global,
11551 // class-static, function-static).
11552 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11553
11554 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011555 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011556 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011557}
11558
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011559/// \brief Given a constructor and the set of arguments provided for the
11560/// constructor, convert the arguments and add any required default arguments
11561/// to form a proper call to this constructor.
11562///
11563/// \returns true if an error occurred, false otherwise.
11564bool
11565Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11566 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011567 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011568 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011569 bool AllowExplicit,
11570 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011571 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11572 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011573 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011574
11575 const FunctionProtoType *Proto
11576 = Constructor->getType()->getAs<FunctionProtoType>();
11577 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011578 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011579
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011580 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011581 if (NumArgs < NumParams)
11582 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011583 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011584 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011585
11586 VariadicCallType CallType =
11587 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011588 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011589 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011590 Proto, 0,
11591 llvm::makeArrayRef(Args, NumArgs),
11592 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011593 CallType, AllowExplicit,
11594 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011595 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011596
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011597 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011598
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011599 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011600 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011601 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011602
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011603 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011604}
11605
Anders Carlssone363c8e2009-12-12 00:32:00 +000011606static inline bool
11607CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11608 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011609 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011610 if (isa<NamespaceDecl>(DC)) {
11611 return SemaRef.Diag(FnDecl->getLocation(),
11612 diag::err_operator_new_delete_declared_in_namespace)
11613 << FnDecl->getDeclName();
11614 }
11615
11616 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011617 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011618 return SemaRef.Diag(FnDecl->getLocation(),
11619 diag::err_operator_new_delete_declared_static)
11620 << FnDecl->getDeclName();
11621 }
11622
Anders Carlsson60659a82009-12-12 02:43:16 +000011623 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011624}
11625
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011626static inline bool
11627CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11628 CanQualType ExpectedResultType,
11629 CanQualType ExpectedFirstParamType,
11630 unsigned DependentParamTypeDiag,
11631 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011632 QualType ResultType =
11633 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011634
11635 // Check that the result type is not dependent.
11636 if (ResultType->isDependentType())
11637 return SemaRef.Diag(FnDecl->getLocation(),
11638 diag::err_operator_new_delete_dependent_result_type)
11639 << FnDecl->getDeclName() << ExpectedResultType;
11640
11641 // Check that the result type is what we expect.
11642 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11643 return SemaRef.Diag(FnDecl->getLocation(),
11644 diag::err_operator_new_delete_invalid_result_type)
11645 << FnDecl->getDeclName() << ExpectedResultType;
11646
11647 // A function template must have at least 2 parameters.
11648 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11649 return SemaRef.Diag(FnDecl->getLocation(),
11650 diag::err_operator_new_delete_template_too_few_parameters)
11651 << FnDecl->getDeclName();
11652
11653 // The function decl must have at least 1 parameter.
11654 if (FnDecl->getNumParams() == 0)
11655 return SemaRef.Diag(FnDecl->getLocation(),
11656 diag::err_operator_new_delete_too_few_parameters)
11657 << FnDecl->getDeclName();
11658
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011659 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011660 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11661 if (FirstParamType->isDependentType())
11662 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11663 << FnDecl->getDeclName() << ExpectedFirstParamType;
11664
11665 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011666 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011667 ExpectedFirstParamType)
11668 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11669 << FnDecl->getDeclName() << ExpectedFirstParamType;
11670
11671 return false;
11672}
11673
Anders Carlsson12308f42009-12-11 23:23:22 +000011674static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011675CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011676 // C++ [basic.stc.dynamic.allocation]p1:
11677 // A program is ill-formed if an allocation function is declared in a
11678 // namespace scope other than global scope or declared static in global
11679 // scope.
11680 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11681 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011682
11683 CanQualType SizeTy =
11684 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11685
11686 // C++ [basic.stc.dynamic.allocation]p1:
11687 // The return type shall be void*. The first parameter shall have type
11688 // std::size_t.
11689 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11690 SizeTy,
11691 diag::err_operator_new_dependent_param_type,
11692 diag::err_operator_new_param_type))
11693 return true;
11694
11695 // C++ [basic.stc.dynamic.allocation]p1:
11696 // The first parameter shall not have an associated default argument.
11697 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011698 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011699 diag::err_operator_new_default_arg)
11700 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11701
11702 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011703}
11704
11705static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011706CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011707 // C++ [basic.stc.dynamic.deallocation]p1:
11708 // A program is ill-formed if deallocation functions are declared in a
11709 // namespace scope other than global scope or declared static in global
11710 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011711 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11712 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011713
11714 // C++ [basic.stc.dynamic.deallocation]p2:
11715 // Each deallocation function shall return void and its first parameter
11716 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011717 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11718 SemaRef.Context.VoidPtrTy,
11719 diag::err_operator_delete_dependent_param_type,
11720 diag::err_operator_delete_param_type))
11721 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011722
Anders Carlsson12308f42009-12-11 23:23:22 +000011723 return false;
11724}
11725
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011726/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11727/// of this overloaded operator is well-formed. If so, returns false;
11728/// otherwise, emits appropriate diagnostics and returns true.
11729bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011730 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011731 "Expected an overloaded operator declaration");
11732
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011733 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11734
Mike Stump11289f42009-09-09 15:08:12 +000011735 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011736 // The allocation and deallocation functions, operator new,
11737 // operator new[], operator delete and operator delete[], are
11738 // described completely in 3.7.3. The attributes and restrictions
11739 // found in the rest of this subclause do not apply to them unless
11740 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011741 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011742 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011743
Anders Carlsson22f443f2009-12-12 00:26:23 +000011744 if (Op == OO_New || Op == OO_Array_New)
11745 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011746
11747 // C++ [over.oper]p6:
11748 // An operator function shall either be a non-static member
11749 // function or be a non-member function and have at least one
11750 // parameter whose type is a class, a reference to a class, an
11751 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011752 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11753 if (MethodDecl->isStatic())
11754 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011755 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011756 } else {
11757 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011758 for (auto Param : FnDecl->params()) {
11759 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011760 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11761 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011762 ClassOrEnumParam = true;
11763 break;
11764 }
11765 }
11766
Douglas Gregord69246b2008-11-17 16:14:12 +000011767 if (!ClassOrEnumParam)
11768 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011769 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011770 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011771 }
11772
11773 // C++ [over.oper]p8:
11774 // An operator function cannot have default arguments (8.3.6),
11775 // except where explicitly stated below.
11776 //
Mike Stump11289f42009-09-09 15:08:12 +000011777 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011778 // (C++ [over.call]p1).
11779 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011780 for (auto Param : FnDecl->params()) {
11781 if (Param->hasDefaultArg())
11782 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011783 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011784 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011785 }
11786 }
11787
Douglas Gregor6cf08062008-11-10 13:38:07 +000011788 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11789 { false, false, false }
11790#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11791 , { Unary, Binary, MemberOnly }
11792#include "clang/Basic/OperatorKinds.def"
11793 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011794
Douglas Gregor6cf08062008-11-10 13:38:07 +000011795 bool CanBeUnaryOperator = OperatorUses[Op][0];
11796 bool CanBeBinaryOperator = OperatorUses[Op][1];
11797 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011798
11799 // C++ [over.oper]p8:
11800 // [...] Operator functions cannot have more or fewer parameters
11801 // than the number required for the corresponding operator, as
11802 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011803 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011804 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011805 if (Op != OO_Call &&
11806 ((NumParams == 1 && !CanBeUnaryOperator) ||
11807 (NumParams == 2 && !CanBeBinaryOperator) ||
11808 (NumParams < 1) || (NumParams > 2))) {
11809 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011810 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011811 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011812 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011813 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011814 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011815 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011816 assert(CanBeBinaryOperator &&
11817 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011818 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011819 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011820
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011821 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011822 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011823 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011824
Douglas Gregord69246b2008-11-17 16:14:12 +000011825 // Overloaded operators other than operator() cannot be variadic.
11826 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011827 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011828 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011829 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011830 }
11831
11832 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011833 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11834 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011835 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011836 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011837 }
11838
11839 // C++ [over.inc]p1:
11840 // The user-defined function called operator++ implements the
11841 // prefix and postfix ++ operator. If this function is a member
11842 // function with no parameters, or a non-member function with one
11843 // parameter of class or enumeration type, it defines the prefix
11844 // increment operator ++ for objects of that type. If the function
11845 // is a member function with one parameter (which shall be of type
11846 // int) or a non-member function with two parameters (the second
11847 // of which shall be of type int), it defines the postfix
11848 // increment operator ++ for objects of that type.
11849 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11850 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011851 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011852
Richard Smith538b52a2014-01-30 22:24:05 +000011853 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11854 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011855 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011856 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011857 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011858 }
11859
Douglas Gregord69246b2008-11-17 16:14:12 +000011860 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011861}
Chris Lattner3b024a32008-12-17 07:09:26 +000011862
Richard Smithc28aee62016-02-17 00:04:04 +000011863static bool
11864checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
11865 FunctionTemplateDecl *TpDecl) {
11866 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
11867
11868 // Must have one or two template parameters.
11869 if (TemplateParams->size() == 1) {
11870 NonTypeTemplateParmDecl *PmDecl =
11871 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
11872
11873 // The template parameter must be a char parameter pack.
11874 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11875 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
11876 return false;
11877
11878 } else if (TemplateParams->size() == 2) {
11879 TemplateTypeParmDecl *PmType =
11880 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
11881 NonTypeTemplateParmDecl *PmArgs =
11882 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
11883
11884 // The second template parameter must be a parameter pack with the
11885 // first template parameter as its type.
11886 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
11887 PmArgs->isTemplateParameterPack()) {
11888 const TemplateTypeParmType *TArgs =
11889 PmArgs->getType()->getAs<TemplateTypeParmType>();
11890 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11891 TArgs->getIndex() == PmType->getIndex()) {
11892 if (SemaRef.ActiveTemplateInstantiations.empty())
11893 SemaRef.Diag(TpDecl->getLocation(),
11894 diag::ext_string_literal_operator_template);
11895 return false;
11896 }
11897 }
11898 }
11899
11900 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
11901 diag::err_literal_operator_template)
11902 << TpDecl->getTemplateParameters()->getSourceRange();
11903 return true;
11904}
11905
Alexis Huntc88db062010-01-13 09:01:02 +000011906/// CheckLiteralOperatorDeclaration - Check whether the declaration
11907/// of this literal operator function is well-formed. If so, returns
11908/// false; otherwise, emits appropriate diagnostics and returns true.
11909bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011910 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011911 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11912 << FnDecl->getDeclName();
11913 return true;
11914 }
11915
Richard Smith72eebee2012-03-04 09:41:16 +000011916 if (FnDecl->isExternC()) {
11917 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11918 return true;
11919 }
11920
Richard Smithbcc22fc2012-03-09 08:00:36 +000011921 // This might be the definition of a literal operator template.
11922 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000011923
Richard Smithbcc22fc2012-03-09 08:00:36 +000011924 // This might be a specialization of a literal operator template.
11925 if (!TpDecl)
11926 TpDecl = FnDecl->getPrimaryTemplate();
11927
Richard Smithb8b41d32013-10-07 19:57:58 +000011928 // template <char...> type operator "" name() and
11929 // template <class T, T...> type operator "" name() are the only valid
11930 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011931 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000011932 if (FnDecl->param_size() != 0) {
11933 Diag(FnDecl->getLocation(),
11934 diag::err_literal_operator_template_with_params);
11935 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000011936 }
Richard Smithc28aee62016-02-17 00:04:04 +000011937
11938 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
11939 return true;
11940
11941 } else if (FnDecl->param_size() == 1) {
11942 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
11943
11944 QualType ParamType = Param->getType().getUnqualifiedType();
11945
11946 // Only unsigned long long int, long double, any character type, and const
11947 // char * are allowed as the only parameters.
11948 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
11949 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
11950 Context.hasSameType(ParamType, Context.CharTy) ||
11951 Context.hasSameType(ParamType, Context.WideCharTy) ||
11952 Context.hasSameType(ParamType, Context.Char16Ty) ||
11953 Context.hasSameType(ParamType, Context.Char32Ty)) {
11954 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
11955 QualType InnerType = Ptr->getPointeeType();
11956
11957 // Pointer parameter must be a const char *.
11958 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
11959 Context.CharTy) &&
11960 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
11961 Diag(Param->getSourceRange().getBegin(),
11962 diag::err_literal_operator_param)
11963 << ParamType << "'const char *'" << Param->getSourceRange();
11964 return true;
11965 }
11966
11967 } else if (ParamType->isRealFloatingType()) {
11968 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
11969 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
11970 return true;
11971
11972 } else if (ParamType->isIntegerType()) {
11973 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
11974 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
11975 return true;
11976
11977 } else {
11978 Diag(Param->getSourceRange().getBegin(),
11979 diag::err_literal_operator_invalid_param)
11980 << ParamType << Param->getSourceRange();
11981 return true;
11982 }
11983
11984 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000011985 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11986
Richard Smithc28aee62016-02-17 00:04:04 +000011987 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000011988
Richard Smithc28aee62016-02-17 00:04:04 +000011989 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
11990
11991 // Two parameter function must have a pointer to const as a
11992 // first parameter; let's strip those qualifiers.
11993 const PointerType *PT = FirstParamType->getAs<PointerType>();
11994
11995 if (!PT) {
11996 Diag((*Param)->getSourceRange().getBegin(),
11997 diag::err_literal_operator_param)
11998 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
11999 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012000 }
12001
Richard Smithc28aee62016-02-17 00:04:04 +000012002 QualType PointeeType = PT->getPointeeType();
12003 // First parameter must be const
12004 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12005 Diag((*Param)->getSourceRange().getBegin(),
12006 diag::err_literal_operator_param)
12007 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12008 return true;
12009 }
Alexis Huntc88db062010-01-13 09:01:02 +000012010
Richard Smithc28aee62016-02-17 00:04:04 +000012011 QualType InnerType = PointeeType.getUnqualifiedType();
12012 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12013 // are allowed as the first parameter to a two-parameter function
12014 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12015 Context.hasSameType(InnerType, Context.WideCharTy) ||
12016 Context.hasSameType(InnerType, Context.Char16Ty) ||
12017 Context.hasSameType(InnerType, Context.Char32Ty))) {
12018 Diag((*Param)->getSourceRange().getBegin(),
12019 diag::err_literal_operator_param)
12020 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12021 return true;
12022 }
12023
12024 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012025 ++Param;
12026
Richard Smithc28aee62016-02-17 00:04:04 +000012027 // The second parameter must be a std::size_t.
12028 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12029 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12030 Diag((*Param)->getSourceRange().getBegin(),
12031 diag::err_literal_operator_param)
12032 << SecondParamType << Context.getSizeType()
12033 << (*Param)->getSourceRange();
12034 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012035 }
Richard Smithc28aee62016-02-17 00:04:04 +000012036 } else {
12037 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012038 return true;
12039 }
12040
Richard Smithc28aee62016-02-17 00:04:04 +000012041 // Parameters are good.
12042
Richard Smith768cecc2012-03-09 08:16:22 +000012043 // A parameter-declaration-clause containing a default argument is not
12044 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012045 for (auto Param : FnDecl->params()) {
12046 if (Param->hasDefaultArg()) {
12047 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012048 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012049 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012050 break;
12051 }
12052 }
12053
Richard Smith0df56f42012-03-08 02:39:21 +000012054 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012055 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12056 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012057 // C++11 [usrlit.suffix]p1:
12058 // Literal suffix identifiers that do not start with an underscore
12059 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012060 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12061 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012062 }
Richard Smith0df56f42012-03-08 02:39:21 +000012063
Alexis Huntc88db062010-01-13 09:01:02 +000012064 return false;
12065}
12066
Douglas Gregor07665a62009-01-05 19:45:36 +000012067/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12068/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012069/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12070/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012071/// the '{' brace. Otherwise, this linkage specification does not
12072/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012073Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012074 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012075 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012076 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12077 if (!Lit->isAscii()) {
12078 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12079 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012080 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012081 }
12082
12083 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012084 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012085 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012086 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012087 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012088 Language = LinkageSpecDecl::lang_cxx;
12089 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012090 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12091 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012092 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000012093 }
Mike Stump11289f42009-09-09 15:08:12 +000012094
Chris Lattner438e5012008-12-17 07:13:27 +000012095 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000012096
Richard Smith4ee696d2014-02-17 23:25:27 +000012097 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12098 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000012099 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012100 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000012101 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000012102 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000012103}
12104
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000012105/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000012106/// the C++ linkage specification LinkageSpec. If RBraceLoc is
12107/// valid, it's the position of the closing '}' brace in a linkage
12108/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000012109Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012110 Decl *LinkageSpec,
12111 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012112 if (RBraceLoc.isValid()) {
12113 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12114 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012115 }
Richard Smith4ee696d2014-02-17 23:25:27 +000012116 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000012117 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000012118}
12119
Michael Han84324352013-02-22 17:15:32 +000012120Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12121 AttributeList *AttrList,
12122 SourceLocation SemiLoc) {
12123 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12124 // Attribute declarations appertain to empty declaration so we handle
12125 // them here.
12126 if (AttrList)
12127 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000012128
Michael Han84324352013-02-22 17:15:32 +000012129 CurContext->addDecl(ED);
12130 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000012131}
12132
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012133/// \brief Perform semantic analysis for the variable declaration that
12134/// occurs within a C++ catch clause, returning the newly-created
12135/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012136VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000012137 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000012138 SourceLocation StartLoc,
12139 SourceLocation Loc,
12140 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012141 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012142 QualType ExDeclType = TInfo->getType();
12143
Sebastian Redl54c04d42008-12-22 19:15:10 +000012144 // Arrays and functions decay.
12145 if (ExDeclType->isArrayType())
12146 ExDeclType = Context.getArrayDecayedType(ExDeclType);
12147 else if (ExDeclType->isFunctionType())
12148 ExDeclType = Context.getPointerType(ExDeclType);
12149
12150 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12151 // The exception-declaration shall not denote a pointer or reference to an
12152 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000012153 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000012154 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012155 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000012156 Invalid = true;
12157 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012158
Sebastian Redl54c04d42008-12-22 19:15:10 +000012159 QualType BaseType = ExDeclType;
12160 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000012161 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012162 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012163 BaseType = Ptr->getPointeeType();
12164 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000012165 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000012166 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000012167 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012168 BaseType = Ref->getPointeeType();
12169 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000012170 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012171 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000012172 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000012173 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000012174 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012175
Mike Stump11289f42009-09-09 15:08:12 +000012176 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012177 RequireNonAbstractType(Loc, ExDeclType,
12178 diag::err_abstract_type_in_decl,
12179 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000012180 Invalid = true;
12181
John McCall2ca705e2010-07-24 00:37:23 +000012182 // Only the non-fragile NeXT runtime currently supports C++ catches
12183 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012184 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000012185 QualType T = ExDeclType;
12186 if (const ReferenceType *RT = T->getAs<ReferenceType>())
12187 T = RT->getPointeeType();
12188
12189 if (T->isObjCObjectType()) {
12190 Diag(Loc, diag::err_objc_object_catch);
12191 Invalid = true;
12192 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000012193 // FIXME: should this be a test for macosx-fragile specifically?
12194 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000012195 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000012196 }
12197 }
12198
Abramo Bagnaradff19302011-03-08 08:55:46 +000012199 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000012200 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000012201 ExDecl->setExceptionVariable(true);
12202
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012203 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012204 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012205 Invalid = true;
12206
Douglas Gregor750734c2011-07-06 18:14:43 +000012207 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000012208 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000012209 // Insulate this from anything else we might currently be parsing.
12210 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12211
Douglas Gregor6de584c2010-03-05 23:38:39 +000012212 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000012213 // The object declared in an exception-declaration or, if the
12214 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000012215 // copy-initialized (8.5) from the exception object. [...]
12216 // The object is destroyed when the handler exits, after the destruction
12217 // of any automatic objects initialized within the handler.
12218 //
Nick Lewycky0f292892013-09-22 10:06:57 +000012219 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000012220 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000012221 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000012222
12223 InitializedEntity entity =
12224 InitializedEntity::InitializeVariable(ExDecl);
12225 InitializationKind initKind =
12226 InitializationKind::CreateCopy(Loc, SourceLocation());
12227
12228 Expr *opaqueValue =
12229 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000012230 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12231 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000012232 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000012233 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000012234 else {
12235 // If the constructor used was non-trivial, set this as the
12236 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012237 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000012238 if (!construct->getConstructor()->isTrivial()) {
12239 Expr *init = MaybeCreateExprWithCleanups(construct);
12240 ExDecl->setInit(init);
12241 }
12242
12243 // And make sure it's destructable.
12244 FinalizeVarWithDestructor(ExDecl, recordType);
12245 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000012246 }
12247 }
12248
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012249 if (Invalid)
12250 ExDecl->setInvalidDecl();
12251
12252 return ExDecl;
12253}
12254
12255/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12256/// handler.
John McCall48871652010-08-21 09:40:31 +000012257Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000012258 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000012259 bool Invalid = D.isInvalidType();
12260
12261 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000012262 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12263 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000012264 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12265 D.getIdentifierLoc());
12266 Invalid = true;
12267 }
12268
Sebastian Redl54c04d42008-12-22 19:15:10 +000012269 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012270 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000012271 LookupOrdinaryName,
12272 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012273 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012274 // it contains any previous declaration, except for function parameters in
12275 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012276 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012277 if (isDeclInScope(PrevDecl, CurContext, S)) {
12278 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12279 << D.getIdentifier();
12280 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12281 Invalid = true;
12282 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012283 // Maybe we will complain about the shadowed template parameter.
12284 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012285 }
12286
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012287 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012288 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12289 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012290 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012291 }
12292
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012293 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012294 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012295 D.getIdentifierLoc(),
12296 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012297 if (Invalid)
12298 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012299
Sebastian Redl54c04d42008-12-22 19:15:10 +000012300 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012301 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012302 PushOnScopeChains(ExDecl, S);
12303 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012304 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012305
Douglas Gregor758a8692009-06-17 21:51:59 +000012306 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012307 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012308}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012309
Abramo Bagnaraea947882011-03-08 16:41:52 +000012310Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012311 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012312 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012313 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012314 StringLiteral *AssertMessage =
12315 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012316
Richard Smithded9c2e2012-07-11 22:37:56 +000012317 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012318 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012319
12320 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12321 AssertMessage, RParenLoc, false);
12322}
12323
12324Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12325 Expr *AssertExpr,
12326 StringLiteral *AssertMessage,
12327 SourceLocation RParenLoc,
12328 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012329 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012330 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12331 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012332 // In a static_assert-declaration, the constant-expression shall be a
12333 // constant expression that can be contextually converted to bool.
12334 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12335 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012336 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012337
Richard Smith902ca212011-12-14 23:32:26 +000012338 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012339 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012340 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012341 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012342 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012343
Richard Smithded9c2e2012-07-11 22:37:56 +000012344 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012345 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012346 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012347 if (AssertMessage)
12348 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012349 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012350 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012351 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012352 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012353 }
Mike Stump11289f42009-09-09 15:08:12 +000012354
Abramo Bagnaraea947882011-03-08 16:41:52 +000012355 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012356 AssertExpr, AssertMessage, RParenLoc,
12357 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012358
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012359 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012360 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012361}
Sebastian Redlf769df52009-03-24 22:27:57 +000012362
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012363/// \brief Perform semantic analysis of the given friend type declaration.
12364///
12365/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012366FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012367 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012368 TypeSourceInfo *TSInfo) {
12369 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12370
12371 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012372 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012373
Richard Smithc8239732011-10-18 21:39:00 +000012374 // C++03 [class.friend]p2:
12375 // An elaborated-type-specifier shall be used in a friend declaration
12376 // for a class.*
12377 //
12378 // * The class-key of the elaborated-type-specifier is required.
12379 if (!ActiveTemplateInstantiations.empty()) {
12380 // Do not complain about the form of friend template types during
12381 // template instantiation; we will already have complained when the
12382 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012383 } else {
12384 if (!T->isElaboratedTypeSpecifier()) {
12385 // If we evaluated the type to a record type, suggest putting
12386 // a tag in front.
12387 if (const RecordType *RT = T->getAs<RecordType>()) {
12388 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012389
12390 SmallString<16> InsertionText(" ");
12391 InsertionText += RD->getKindName();
12392
Nick Lewycky36722d22013-02-06 05:59:33 +000012393 Diag(TypeRange.getBegin(),
12394 getLangOpts().CPlusPlus11 ?
12395 diag::warn_cxx98_compat_unelaborated_friend_type :
12396 diag::ext_unelaborated_friend_type)
12397 << (unsigned) RD->getTagKind()
12398 << T
Craig Topper07fa1762015-11-15 02:31:46 +000012399 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000012400 InsertionText);
12401 } else {
12402 Diag(FriendLoc,
12403 getLangOpts().CPlusPlus11 ?
12404 diag::warn_cxx98_compat_nonclass_type_friend :
12405 diag::ext_nonclass_type_friend)
12406 << T
12407 << TypeRange;
12408 }
12409 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012410 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012411 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012412 diag::warn_cxx98_compat_enum_friend :
12413 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012414 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012415 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012416 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012417
Nick Lewycky36722d22013-02-06 05:59:33 +000012418 // C++11 [class.friend]p3:
12419 // A friend declaration that does not declare a function shall have one
12420 // of the following forms:
12421 // friend elaborated-type-specifier ;
12422 // friend simple-type-specifier ;
12423 // friend typename-specifier ;
12424 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12425 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12426 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012427
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012428 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012429 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012430 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012431 return FriendDecl::Create(Context, CurContext,
12432 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12433 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012434}
12435
John McCallace48cd2010-10-19 01:40:49 +000012436/// Handle a friend tag declaration where the scope specifier was
12437/// templated.
12438Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12439 unsigned TagSpec, SourceLocation TagLoc,
12440 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012441 IdentifierInfo *Name,
12442 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012443 AttributeList *Attr,
12444 MultiTemplateParamsArg TempParamLists) {
12445 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12446
12447 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012448 bool Invalid = false;
12449
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012450 if (TemplateParameterList *TemplateParams =
12451 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012452 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012453 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012454 if (TemplateParams->size() > 0) {
12455 // This is a declaration of a class template.
12456 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012457 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012458
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012459 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12460 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012461 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012462 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012463 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012464 } else {
12465 // The "template<>" header is extraneous.
12466 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12467 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12468 isExplicitSpecialization = true;
12469 }
12470 }
12471
Craig Topperc3ec1492014-05-26 06:22:03 +000012472 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012473
John McCallace48cd2010-10-19 01:40:49 +000012474 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012475 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012476 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012477 isAllExplicitSpecializations = false;
12478 break;
12479 }
12480 }
12481
12482 // FIXME: don't ignore attributes.
12483
12484 // If it's explicit specializations all the way down, just forget
12485 // about the template header and build an appropriate non-templated
12486 // friend. TODO: for source fidelity, remember the headers.
12487 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012488 if (SS.isEmpty()) {
12489 bool Owned = false;
12490 bool IsDependent = false;
12491 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012492 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012493 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012494 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012495 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012496 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012497 /*UnderlyingType=*/TypeResult(),
12498 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012499 }
Richard Smith649c7b062014-01-08 00:56:48 +000012500
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012501 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012502 ElaboratedTypeKeyword Keyword
12503 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012504 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012505 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012506 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012507 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012508
12509 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12510 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012511 DependentNameTypeLoc TL =
12512 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012513 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012514 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012515 TL.setNameLoc(NameLoc);
12516 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012517 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012518 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012519 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012520 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012521 }
12522
12523 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012524 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012525 Friend->setAccess(AS_public);
12526 CurContext->addDecl(Friend);
12527 return Friend;
12528 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012529
12530 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12531
12532
John McCallace48cd2010-10-19 01:40:49 +000012533
12534 // Handle the case of a templated-scope friend class. e.g.
12535 // template <class T> class A<T>::B;
12536 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012537 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12538 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012539 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12540 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12541 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012542 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012543 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012544 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012545 TL.setNameLoc(NameLoc);
12546
12547 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012548 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012549 Friend->setAccess(AS_public);
12550 Friend->setUnsupportedFriend(true);
12551 CurContext->addDecl(Friend);
12552 return Friend;
12553}
12554
12555
John McCall11083da2009-09-16 22:47:08 +000012556/// Handle a friend type declaration. This works in tandem with
12557/// ActOnTag.
12558///
12559/// Notes on friend class templates:
12560///
12561/// We generally treat friend class declarations as if they were
12562/// declaring a class. So, for example, the elaborated type specifier
12563/// in a friend declaration is required to obey the restrictions of a
12564/// class-head (i.e. no typedefs in the scope chain), template
12565/// parameters are required to match up with simple template-ids, &c.
12566/// However, unlike when declaring a template specialization, it's
12567/// okay to refer to a template specialization without an empty
12568/// template parameter declaration, e.g.
12569/// friend class A<T>::B<unsigned>;
12570/// We permit this as a special case; if there are any template
12571/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012572/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012573Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012574 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012575 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012576
12577 assert(DS.isFriendSpecified());
12578 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12579
John McCall11083da2009-09-16 22:47:08 +000012580 // Try to convert the decl specifier to a type. This works for
12581 // friend templates because ActOnTag never produces a ClassTemplateDecl
12582 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012583 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012584 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12585 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012586 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012587 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012588
Douglas Gregor6c110f32010-12-16 01:14:37 +000012589 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012590 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012591
John McCall11083da2009-09-16 22:47:08 +000012592 // This is definitely an error in C++98. It's probably meant to
12593 // be forbidden in C++0x, too, but the specification is just
12594 // poorly written.
12595 //
12596 // The problem is with declarations like the following:
12597 // template <T> friend A<T>::foo;
12598 // where deciding whether a class C is a friend or not now hinges
12599 // on whether there exists an instantiation of A that causes
12600 // 'foo' to equal C. There are restrictions on class-heads
12601 // (which we declare (by fiat) elaborated friend declarations to
12602 // be) that makes this tractable.
12603 //
12604 // FIXME: handle "template <> friend class A<T>;", which
12605 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012606 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012607 Diag(Loc, diag::err_tagless_friend_type_template)
12608 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012609 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012610 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012611
John McCallaa74a0c2009-08-28 07:59:38 +000012612 // C++98 [class.friend]p1: A friend of a class is a function
12613 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012614 // This is fixed in DR77, which just barely didn't make the C++03
12615 // deadline. It's also a very silly restriction that seriously
12616 // affects inner classes and which nobody else seems to implement;
12617 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012618 //
12619 // But note that we could warn about it: it's always useless to
12620 // friend one of your own members (it's not, however, worthless to
12621 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012622
John McCall11083da2009-09-16 22:47:08 +000012623 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012624 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012625 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012626 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012627 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012628 TSI,
John McCall11083da2009-09-16 22:47:08 +000012629 DS.getFriendSpecLoc());
12630 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012631 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012632
12633 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012634 return nullptr;
12635
John McCall11083da2009-09-16 22:47:08 +000012636 D->setAccess(AS_public);
12637 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012638
John McCall48871652010-08-21 09:40:31 +000012639 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012640}
12641
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012642NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12643 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012644 const DeclSpec &DS = D.getDeclSpec();
12645
12646 assert(DS.isFriendSpecified());
12647 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12648
12649 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012650 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012651
12652 // C++ [class.friend]p1
12653 // A friend of a class is a function or class....
12654 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012655 // It *doesn't* see through dependent types, which is correct
12656 // according to [temp.arg.type]p3:
12657 // If a declaration acquires a function type through a
12658 // type dependent on a template-parameter and this causes
12659 // a declaration that does not use the syntactic form of a
12660 // function declarator to have a function type, the program
12661 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012662 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012663 Diag(Loc, diag::err_unexpected_friend);
12664
12665 // It might be worthwhile to try to recover by creating an
12666 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012667 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012668 }
12669
12670 // C++ [namespace.memdef]p3
12671 // - If a friend declaration in a non-local class first declares a
12672 // class or function, the friend class or function is a member
12673 // of the innermost enclosing namespace.
12674 // - The name of the friend is not found by simple name lookup
12675 // until a matching declaration is provided in that namespace
12676 // scope (either before or after the class declaration granting
12677 // friendship).
12678 // - If a friend function is called, its name may be found by the
12679 // name lookup that considers functions from namespaces and
12680 // classes associated with the types of the function arguments.
12681 // - When looking for a prior declaration of a class or a function
12682 // declared as a friend, scopes outside the innermost enclosing
12683 // namespace scope are not considered.
12684
John McCallde3fd222010-10-12 23:13:28 +000012685 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012686 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12687 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012688 assert(Name);
12689
Douglas Gregor6c110f32010-12-16 01:14:37 +000012690 // Check for unexpanded parameter packs.
12691 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12692 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12693 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012694 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012695
John McCall07e91c02009-08-06 02:15:43 +000012696 // The context we found the declaration in, or in which we should
12697 // create the declaration.
12698 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012699 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012700 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012701 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012702
Richard Smith114394f2013-08-09 04:35:01 +000012703 // There are five cases here.
12704 // - There's no scope specifier and we're in a local class. Only look
12705 // for functions declared in the immediately-enclosing block scope.
12706 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012707 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012708 if ((SS.isInvalid() || !SS.isSet()) &&
12709 (FunctionContainingLocalClass =
12710 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12711 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012712 // If a friend declaration appears in a local class and the name
12713 // specified is an unqualified name, a prior declaration is
12714 // looked up without considering scopes that are outside the
12715 // innermost enclosing non-class scope. For a friend function
12716 // declaration, if there is no prior declaration, the program is
12717 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012718
12719 // Find the innermost enclosing non-class scope. This is the block
12720 // scope containing the local class definition (or for a nested class,
12721 // the outer local class).
12722 DCScope = S->getFnParent();
12723
12724 // Look up the function name in the scope.
12725 Previous.clear(LookupLocalFriendName);
12726 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12727
12728 if (!Previous.empty()) {
12729 // All possible previous declarations must have the same context:
12730 // either they were declared at block scope or they are members of
12731 // one of the enclosing local classes.
12732 DC = Previous.getRepresentativeDecl()->getDeclContext();
12733 } else {
12734 // This is ill-formed, but provide the context that we would have
12735 // declared the function in, if we were permitted to, for error recovery.
12736 DC = FunctionContainingLocalClass;
12737 }
Richard Smith541b38b2013-09-20 01:15:31 +000012738 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012739
12740 // C++ [class.friend]p6:
12741 // A function can be defined in a friend declaration of a class if and
12742 // only if the class is a non-local class (9.8), the function name is
12743 // unqualified, and the function has namespace scope.
12744 if (D.isFunctionDefinition()) {
12745 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12746 }
12747
12748 // - There's no scope specifier, in which case we just go to the
12749 // appropriate scope and look for a function or function template
12750 // there as appropriate.
12751 } else if (SS.isInvalid() || !SS.isSet()) {
12752 // C++11 [namespace.memdef]p3:
12753 // If the name in a friend declaration is neither qualified nor
12754 // a template-id and the declaration is a function or an
12755 // elaborated-type-specifier, the lookup to determine whether
12756 // the entity has been previously declared shall not consider
12757 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012758 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012759
John McCallf7cfb222010-10-13 05:45:15 +000012760 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012761 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012762
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012763 // Skip class contexts. If someone can cite chapter and verse
12764 // for this behavior, that would be nice --- it's what GCC and
12765 // EDG do, and it seems like a reasonable intent, but the spec
12766 // really only says that checks for unqualified existing
12767 // declarations should stop at the nearest enclosing namespace,
12768 // not that they should only consider the nearest enclosing
12769 // namespace.
12770 while (DC->isRecord())
12771 DC = DC->getParent();
12772
12773 DeclContext *LookupDC = DC;
12774 while (LookupDC->isTransparentContext())
12775 LookupDC = LookupDC->getParent();
12776
12777 while (true) {
12778 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012779
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012780 if (!Previous.empty()) {
12781 DC = LookupDC;
12782 break;
John McCallf4776592010-10-14 22:22:28 +000012783 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012784
12785 if (isTemplateId) {
12786 if (isa<TranslationUnitDecl>(LookupDC)) break;
12787 } else {
12788 if (LookupDC->isFileContext()) break;
12789 }
12790 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012791 }
12792
John McCallccbc0322010-10-13 06:22:15 +000012793 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012794
John McCallde3fd222010-10-12 23:13:28 +000012795 // - There's a non-dependent scope specifier, in which case we
12796 // compute it and do a previous lookup there for a function
12797 // or function template.
12798 } else if (!SS.getScopeRep()->isDependent()) {
12799 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012800 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012801
Craig Topperc3ec1492014-05-26 06:22:03 +000012802 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012803
12804 LookupQualifiedName(Previous, DC);
12805
12806 // Ignore things found implicitly in the wrong scope.
12807 // TODO: better diagnostics for this case. Suggesting the right
12808 // qualified scope would be nice...
12809 LookupResult::Filter F = Previous.makeFilter();
12810 while (F.hasNext()) {
12811 NamedDecl *D = F.next();
12812 if (!DC->InEnclosingNamespaceSetOf(
12813 D->getDeclContext()->getRedeclContext()))
12814 F.erase();
12815 }
12816 F.done();
12817
12818 if (Previous.empty()) {
12819 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012820 Diag(Loc, diag::err_qualified_friend_not_found)
12821 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012822 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012823 }
12824
12825 // C++ [class.friend]p1: A friend of a class is a function or
12826 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012827 if (DC->Equals(CurContext))
12828 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012829 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012830 diag::warn_cxx98_compat_friend_is_member :
12831 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012832
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012833 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012834 // C++ [class.friend]p6:
12835 // A function can be defined in a friend declaration of a class if and
12836 // only if the class is a non-local class (9.8), the function name is
12837 // unqualified, and the function has namespace scope.
12838 SemaDiagnosticBuilder DB
12839 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12840
12841 DB << SS.getScopeRep();
12842 if (DC->isFileContext())
12843 DB << FixItHint::CreateRemoval(SS.getRange());
12844 SS.clear();
12845 }
John McCallde3fd222010-10-12 23:13:28 +000012846
12847 // - There's a scope specifier that does not match any template
12848 // parameter lists, in which case we use some arbitrary context,
12849 // create a method or method template, and wait for instantiation.
12850 // - There's a scope specifier that does match some template
12851 // parameter lists, which we don't handle right now.
12852 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012853 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012854 // C++ [class.friend]p6:
12855 // A function can be defined in a friend declaration of a class if and
12856 // only if the class is a non-local class (9.8), the function name is
12857 // unqualified, and the function has namespace scope.
12858 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12859 << SS.getScopeRep();
12860 }
12861
John McCallde3fd222010-10-12 23:13:28 +000012862 DC = CurContext;
12863 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012864 }
David Majnemere14d5302015-09-30 22:07:43 +000012865
John McCallf7cfb222010-10-13 05:45:15 +000012866 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000012867 int DiagArg = -1;
12868 switch (D.getName().getKind()) {
12869 case UnqualifiedId::IK_ConstructorTemplateId:
12870 case UnqualifiedId::IK_ConstructorName:
12871 DiagArg = 0;
12872 break;
12873 case UnqualifiedId::IK_DestructorName:
12874 DiagArg = 1;
12875 break;
12876 case UnqualifiedId::IK_ConversionFunctionId:
12877 DiagArg = 2;
12878 break;
12879 case UnqualifiedId::IK_Identifier:
12880 case UnqualifiedId::IK_ImplicitSelfParam:
12881 case UnqualifiedId::IK_LiteralOperatorId:
12882 case UnqualifiedId::IK_OperatorFunctionId:
12883 case UnqualifiedId::IK_TemplateId:
12884 break;
David Majnemere14d5302015-09-30 22:07:43 +000012885 }
John McCall07e91c02009-08-06 02:15:43 +000012886 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000012887 if (DiagArg >= 0) {
12888 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000012889 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012890 }
John McCall07e91c02009-08-06 02:15:43 +000012891 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012892
Douglas Gregordd847ba2011-11-03 16:37:14 +000012893 // FIXME: This is an egregious hack to cope with cases where the scope stack
12894 // does not contain the declaration context, i.e., in an out-of-line
12895 // definition of a class.
12896 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12897 if (!DCScope) {
12898 FakeDCScope.setEntity(DC);
12899 DCScope = &FakeDCScope;
12900 }
Richard Smith114394f2013-08-09 04:35:01 +000012901
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012902 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012903 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012904 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012905 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012906
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012907 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012908
Richard Smith114394f2013-08-09 04:35:01 +000012909 // If we performed typo correction, we might have added a scope specifier
12910 // and changed the decl context.
12911 DC = ND->getDeclContext();
12912
John McCall759e32b2009-08-31 22:39:49 +000012913 // Add the function declaration to the appropriate lookup tables,
12914 // adjusting the redeclarations list as necessary. We don't
12915 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012916 //
John McCall759e32b2009-08-31 22:39:49 +000012917 // Also update the scope-based lookup if the target context's
12918 // lookup context is in lexical scope.
12919 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012920 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012921 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012922 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012923 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012924 }
John McCallaa74a0c2009-08-28 07:59:38 +000012925
12926 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012927 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012928 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012929 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012930 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012931
John McCalla0a96892012-08-10 03:15:35 +000012932 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012933 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012934 } else {
12935 if (DC->isRecord()) CheckFriendAccess(ND);
12936
John McCall2c2eb122010-10-16 06:59:13 +000012937 FunctionDecl *FD;
12938 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12939 FD = FTD->getTemplatedDecl();
12940 else
12941 FD = cast<FunctionDecl>(ND);
12942
David Majnemer502b0ed2013-06-25 23:09:30 +000012943 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12944 // default argument expression, that declaration shall be a definition
12945 // and shall be the only declaration of the function or function
12946 // template in the translation unit.
12947 if (functionDeclHasDefaultArgument(FD)) {
12948 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12949 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12950 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12951 } else if (!D.isFunctionDefinition())
12952 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12953 }
12954
John McCall2c2eb122010-10-16 06:59:13 +000012955 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012956 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12957 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12958 << SS.getScopeRep() << SS.getRange()
12959 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012960 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012961 }
John McCall2c2eb122010-10-16 06:59:13 +000012962 }
John McCallde3fd222010-10-12 23:13:28 +000012963
John McCall48871652010-08-21 09:40:31 +000012964 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012965}
12966
John McCall48871652010-08-21 09:40:31 +000012967void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12968 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012969
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012970 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012971 if (!Fn) {
12972 Diag(DelLoc, diag::err_deleted_non_function);
12973 return;
12974 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012975
Douglas Gregorec9fd132012-01-14 16:38:05 +000012976 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012977 // Don't consider the implicit declaration we generate for explicit
12978 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012979 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12980 Prev->getPreviousDecl()) &&
12981 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012982 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012983 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12984 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12985 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012986 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012987 // If the declaration wasn't the first, we delete the function anyway for
12988 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012989 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012990 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012991
Nico Rieck9de0a572014-05-29 16:51:19 +000012992 // dllimport/dllexport cannot be deleted.
12993 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12994 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12995 Fn->setInvalidDecl();
12996 }
12997
Richard Smithb4d2a152013-04-02 19:38:47 +000012998 if (Fn->isDeleted())
12999 return;
13000
13001 // See if we're deleting a function which is already known to override a
13002 // non-deleted virtual function.
13003 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13004 bool IssuedDiagnostic = false;
13005 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13006 E = MD->end_overridden_methods();
13007 I != E; ++I) {
13008 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13009 if (!IssuedDiagnostic) {
13010 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13011 IssuedDiagnostic = true;
13012 }
13013 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13014 }
13015 }
13016 }
13017
Richard Smithb63b6ee2014-01-22 01:43:19 +000013018 // C++11 [basic.start.main]p3:
13019 // A program that defines main as deleted [...] is ill-formed.
13020 if (Fn->isMain())
13021 Diag(DelLoc, diag::err_deleted_main);
13022
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013023 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013024}
Sebastian Redl4c018662009-04-27 21:33:24 +000013025
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013026void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013027 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013028
13029 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000013030 if (MD->getParent()->isDependentType()) {
13031 MD->setDefaulted();
13032 MD->setExplicitlyDefaulted();
13033 return;
13034 }
13035
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013036 CXXSpecialMember Member = getSpecialMember(MD);
13037 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013038 if (!MD->isInvalidDecl())
13039 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013040 return;
13041 }
13042
13043 MD->setDefaulted();
13044 MD->setExplicitlyDefaulted();
13045
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013046 // If this definition appears within the record, do the checking when
13047 // the record is complete.
13048 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013049 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013050 // Find the uninstantiated declaration that actually had the '= default'
13051 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000013052 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013053
Richard Smith3901dfe2013-03-27 00:22:47 +000013054 // If the method was defaulted on its first declaration, we will have
13055 // already performed the checking in CheckCompletedCXXClass. Such a
13056 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013057 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013058 return;
13059
Richard Smithd3b5c9082012-07-27 04:22:15 +000013060 CheckExplicitlyDefaultedSpecialMember(MD);
13061
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013062 if (MD->isInvalidDecl())
13063 return;
13064
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013065 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013066 case CXXDefaultConstructor:
13067 DefineImplicitDefaultConstructor(DefaultLoc,
13068 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000013069 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013070 case CXXCopyConstructor:
13071 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013072 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013073 case CXXCopyAssignment:
13074 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000013075 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013076 case CXXDestructor:
13077 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000013078 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013079 case CXXMoveConstructor:
13080 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000013081 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013082 case CXXMoveAssignment:
13083 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000013084 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000013085 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000013086 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013087 }
13088 } else {
13089 Diag(DefaultLoc, diag::err_default_special_members);
13090 }
13091}
13092
Sebastian Redl4c018662009-04-27 21:33:24 +000013093static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013094 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013095 if (!SubStmt)
13096 continue;
13097 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013098 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000013099 diag::err_return_in_constructor_handler);
13100 if (!isa<Expr>(SubStmt))
13101 SearchForReturnInStmt(Self, SubStmt);
13102 }
13103}
13104
13105void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13106 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13107 CXXCatchStmt *Handler = TryBlock->getHandler(I);
13108 SearchForReturnInStmt(*this, Handler);
13109 }
13110}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013111
David Blaikie68f71a32013-01-18 23:03:15 +000013112bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000013113 const CXXMethodDecl *Old) {
13114 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13115 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13116
13117 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13118
13119 // If the calling conventions match, everything is fine
13120 if (NewCC == OldCC)
13121 return false;
13122
Hans Wennborg2545efe2013-12-11 17:42:11 +000013123 // If the calling conventions mismatch because the new function is static,
13124 // suppress the calling convention mismatch error; the error about static
13125 // function override (err_static_overrides_virtual from
13126 // Sema::CheckFunctionDeclaration) is more clear.
13127 if (New->getStorageClass() == SC_Static)
13128 return false;
13129
Reid Kleckner78af0702013-08-27 23:08:25 +000013130 Diag(New->getLocation(),
13131 diag::err_conflicting_overriding_cc_attributes)
13132 << New->getDeclName() << New->getType() << Old->getType();
13133 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13134 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000013135}
13136
Mike Stump11289f42009-09-09 15:08:12 +000013137bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013138 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000013139 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13140 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013141
Chandler Carruth284bb2e2010-02-15 11:53:20 +000013142 if (Context.hasSameType(NewTy, OldTy) ||
13143 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013144 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013145
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013146 // Check if the return types are covariant
13147 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000013148
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013149 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013150 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13151 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013152 NewClassTy = NewPT->getPointeeType();
13153 OldClassTy = OldPT->getPointeeType();
13154 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013155 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13156 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13157 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13158 NewClassTy = NewRT->getPointeeType();
13159 OldClassTy = OldRT->getPointeeType();
13160 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013161 }
13162 }
Mike Stump11289f42009-09-09 15:08:12 +000013163
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013164 // The return types aren't either both pointers or references to a class type.
13165 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000013166 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013167 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013168 << New->getDeclName() << NewTy << OldTy
13169 << New->getReturnTypeSourceRange();
13170 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13171 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000013172
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013173 return true;
13174 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013175
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000013176 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000013177 // C++14 [class.virtual]p8:
13178 // If the class type in the covariant return type of D::f differs from
13179 // that of B::f, the class type in the return type of D::f shall be
13180 // complete at the point of declaration of D::f or shall be the class
13181 // type D.
13182 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13183 if (!RT->isBeingDefined() &&
13184 RequireCompleteType(New->getLocation(), NewClassTy,
13185 diag::err_covariant_return_incomplete,
13186 New->getDeclName()))
13187 return true;
13188 }
13189
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013190 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000013191 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000013192 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13193 << New->getDeclName() << NewTy << OldTy
13194 << New->getReturnTypeSourceRange();
13195 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13196 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013197 return true;
13198 }
Mike Stump11289f42009-09-09 15:08:12 +000013199
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013200 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013201 if (CheckDerivedToBaseConversion(
13202 NewClassTy, OldClassTy,
13203 diag::err_covariant_return_inaccessible_base,
13204 diag::err_covariant_return_ambiguous_derived_to_base_conv,
13205 New->getLocation(), New->getReturnTypeSourceRange(),
13206 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000013207 // FIXME: this note won't trigger for delayed access control
13208 // diagnostics, and it's impossible to get an undelayed error
13209 // here from access control during the original parse because
13210 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013211 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13212 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013213 return true;
13214 }
13215 }
Mike Stump11289f42009-09-09 15:08:12 +000013216
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013217 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013218 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013219 Diag(New->getLocation(),
13220 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013221 << New->getDeclName() << NewTy << OldTy
13222 << New->getReturnTypeSourceRange();
13223 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13224 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013225 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000013226 }
Mike Stump11289f42009-09-09 15:08:12 +000013227
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013228
13229 // The new class type must have the same or less qualifiers as the old type.
13230 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13231 Diag(New->getLocation(),
13232 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013233 << New->getDeclName() << NewTy << OldTy
13234 << New->getReturnTypeSourceRange();
13235 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13236 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013237 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000013238 }
Mike Stump11289f42009-09-09 15:08:12 +000013239
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013240 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013241}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013242
Douglas Gregor21920e372009-12-01 17:24:26 +000013243/// \brief Mark the given method pure.
13244///
13245/// \param Method the method to be marked pure.
13246///
13247/// \param InitRange the source range that covers the "0" initializer.
13248bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013249 SourceLocation EndLoc = InitRange.getEnd();
13250 if (EndLoc.isValid())
13251 Method->setRangeEnd(EndLoc);
13252
Douglas Gregor21920e372009-12-01 17:24:26 +000013253 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13254 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000013255 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013256 }
Douglas Gregor21920e372009-12-01 17:24:26 +000013257
13258 if (!Method->isInvalidDecl())
13259 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13260 << Method->getDeclName() << InitRange;
13261 return true;
13262}
13263
Richard Smith9ba0fec2015-06-30 01:28:56 +000013264void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13265 if (D->getFriendObjectKind())
13266 Diag(D->getLocation(), diag::err_pure_friend);
13267 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13268 CheckPureMethod(M, ZeroLoc);
13269 else
13270 Diag(D->getLocation(), diag::err_illegal_initializer);
13271}
13272
Douglas Gregor926410d2012-02-21 02:22:07 +000013273/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013274static bool isStaticDataMember(const Decl *D) {
13275 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13276 return Var->isStaticDataMember();
13277
13278 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000013279}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013280
John McCall1f4ee7b2009-12-19 09:28:58 +000013281/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13282/// an initializer for the out-of-line declaration 'Dcl'. The scope
13283/// is a fresh scope pushed for just this purpose.
13284///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013285/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13286/// static data member of class X, names should be looked up in the scope of
13287/// class X.
John McCall48871652010-08-21 09:40:31 +000013288void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013289 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013290 if (!D || D->isInvalidDecl())
13291 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013292
Richard Smitha2302242013-12-05 07:51:02 +000013293 // We will always have a nested name specifier here, but this declaration
13294 // might not be out of line if the specifier names the current namespace:
13295 // extern int n;
13296 // int ::n = 0;
13297 if (D->isOutOfLine())
13298 EnterDeclaratorContext(S, D->getDeclContext());
13299
Douglas Gregor926410d2012-02-21 02:22:07 +000013300 // If we are parsing the initializer for a static data member, push a
13301 // new expression evaluation context that is associated with this static
13302 // data member.
13303 if (isStaticDataMember(D))
13304 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013305}
13306
13307/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013308/// initializer for the out-of-line declaration 'D'.
13309void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013310 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013311 if (!D || D->isInvalidDecl())
13312 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013313
Douglas Gregor926410d2012-02-21 02:22:07 +000013314 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013315 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013316
Richard Smitha2302242013-12-05 07:51:02 +000013317 if (D->isOutOfLine())
13318 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013319}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013320
13321/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13322/// C++ if/switch/while/for statement.
13323/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013324DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013325 // C++ 6.4p2:
13326 // The declarator shall not specify a function or an array.
13327 // The type-specifier-seq shall not contain typedef and shall not declare a
13328 // new class or enumeration.
13329 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13330 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013331
13332 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013333 if (!Dcl)
13334 return true;
13335
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013336 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13337 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013338 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013339 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013340 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013341
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013342 return Dcl;
13343}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013344
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013345void Sema::LoadExternalVTableUses() {
13346 if (!ExternalSource)
13347 return;
13348
13349 SmallVector<ExternalVTableUse, 4> VTables;
13350 ExternalSource->ReadUsedVTables(VTables);
13351 SmallVector<VTableUse, 4> NewUses;
13352 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13353 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13354 = VTablesUsed.find(VTables[I].Record);
13355 // Even if a definition wasn't required before, it may be required now.
13356 if (Pos != VTablesUsed.end()) {
13357 if (!Pos->second && VTables[I].DefinitionRequired)
13358 Pos->second = true;
13359 continue;
13360 }
13361
13362 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13363 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13364 }
13365
13366 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13367}
13368
Douglas Gregor88d292c2010-05-13 16:44:06 +000013369void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13370 bool DefinitionRequired) {
13371 // Ignore any vtable uses in unevaluated operands or for classes that do
13372 // not have a vtable.
13373 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013374 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013375 return;
13376
Douglas Gregor88d292c2010-05-13 16:44:06 +000013377 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013378 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013379 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13380 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13381 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13382 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013383 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013384 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013385 // list, since we may have already processed the first entry.
13386 if (DefinitionRequired && !Pos.first->second) {
13387 Pos.first->second = true;
13388 } else {
13389 // Otherwise, we can early exit.
13390 return;
13391 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013392 } else {
13393 // The Microsoft ABI requires that we perform the destructor body
13394 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13395 // the deleting destructor is emitted with the vtable, not with the
13396 // destructor definition as in the Itanium ABI.
13397 // If it has a definition, we do the check at that point instead.
Hans Wennborg34804352016-04-13 20:21:15 +000013398 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13399 if (Class->hasUserDeclaredDestructor() &&
13400 !Class->getDestructor()->isDefined() &&
13401 !Class->getDestructor()->isDeleted()) {
13402 CXXDestructorDecl *DD = Class->getDestructor();
13403 ContextRAII SavedContext(*this, DD);
13404 CheckDestructor(DD);
13405 } else if (Class->hasAttr<DLLImportAttr>()) {
13406 // We always synthesize vtables on the import side. To make sure
13407 // CheckDestructor gets called, mark the destructor referenced.
13408 assert(Class->getDestructor() &&
13409 "The destructor has always been declared on a dllimport class");
13410 MarkFunctionReferenced(Loc, Class->getDestructor());
13411 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013412 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013413 }
13414
13415 // Local classes need to have their virtual members marked
13416 // immediately. For all other classes, we mark their virtual members
13417 // at the end of the translation unit.
13418 if (Class->isLocalClass())
13419 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013420 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013421 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013422}
13423
Douglas Gregor88d292c2010-05-13 16:44:06 +000013424bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013425 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013426 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013427 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013428
Douglas Gregor88d292c2010-05-13 16:44:06 +000013429 // Note: The VTableUses vector could grow as a result of marking
13430 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013431 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013432 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013433 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013434 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013435 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013436 if (!Class)
13437 continue;
13438
13439 SourceLocation Loc = VTableUses[I].second;
13440
Richard Smithd3b5c9082012-07-27 04:22:15 +000013441 bool DefineVTable = true;
13442
Douglas Gregor88d292c2010-05-13 16:44:06 +000013443 // If this class has a key function, but that key function is
13444 // defined in another translation unit, we don't need to emit the
13445 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013446 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013447 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013448 // The key function is in another translation unit.
13449 DefineVTable = false;
13450 TemplateSpecializationKind TSK =
13451 KeyFunction->getTemplateSpecializationKind();
13452 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13453 TSK != TSK_ImplicitInstantiation &&
13454 "Instantiations don't have key functions");
13455 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013456 } else if (!KeyFunction) {
13457 // If we have a class with no key function that is the subject
13458 // of an explicit instantiation declaration, suppress the
13459 // vtable; it will live with the explicit instantiation
13460 // definition.
13461 bool IsExplicitInstantiationDeclaration
13462 = Class->getTemplateSpecializationKind()
13463 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013464 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013465 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013466 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013467 if (TSK == TSK_ExplicitInstantiationDeclaration)
13468 IsExplicitInstantiationDeclaration = true;
13469 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13470 IsExplicitInstantiationDeclaration = false;
13471 break;
13472 }
13473 }
13474
13475 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013476 DefineVTable = false;
13477 }
13478
13479 // The exception specifications for all virtual members may be needed even
13480 // if we are not providing an authoritative form of the vtable in this TU.
13481 // We may choose to emit it available_externally anyway.
13482 if (!DefineVTable) {
13483 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13484 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013485 }
13486
13487 // Mark all of the virtual members of this class as referenced, so
13488 // that we can build a vtable. Then, tell the AST consumer that a
13489 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013490 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013491 MarkVirtualMembersReferenced(Loc, Class);
13492 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013493 if (VTablesUsed[Canonical])
13494 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013495
13496 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013497 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013498 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013499 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013500 if (!KeyFunction ||
13501 (KeyFunction->hasBody(KeyFunctionDef) &&
13502 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013503 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13504 TSK_ExplicitInstantiationDefinition
13505 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13506 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013507 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013508 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013509 VTableUses.clear();
13510
Douglas Gregor97509692011-04-22 22:25:37 +000013511 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013512}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013513
Richard Smithd3b5c9082012-07-27 04:22:15 +000013514void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13515 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013516 for (const auto *I : RD->methods())
13517 if (I->isVirtual() && !I->isPure())
13518 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013519}
13520
Rafael Espindola5b334082010-03-26 00:36:59 +000013521void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13522 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013523 // Mark all functions which will appear in RD's vtable as used.
13524 CXXFinalOverriderMap FinalOverriders;
13525 RD->getFinalOverriders(FinalOverriders);
13526 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13527 E = FinalOverriders.end();
13528 I != E; ++I) {
13529 for (OverridingMethods::const_iterator OI = I->second.begin(),
13530 OE = I->second.end();
13531 OI != OE; ++OI) {
13532 assert(OI->second.size() > 0 && "no final overrider");
13533 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013534
Richard Smith4ff9ff92012-07-07 06:59:51 +000013535 // C++ [basic.def.odr]p2:
13536 // [...] A virtual member function is used if it is not pure. [...]
13537 if (!Overrider->isPure())
13538 MarkFunctionReferenced(Loc, Overrider);
13539 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013540 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013541
13542 // Only classes that have virtual bases need a VTT.
13543 if (RD->getNumVBases() == 0)
13544 return;
13545
Aaron Ballman574705e2014-03-13 15:41:46 +000013546 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013547 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013548 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013549 if (Base->getNumVBases() == 0)
13550 continue;
13551 MarkVirtualMembersReferenced(Loc, Base);
13552 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013553}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013554
13555/// SetIvarInitializers - This routine builds initialization ASTs for the
13556/// Objective-C implementation whose ivars need be initialized.
13557void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013558 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013559 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013560 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013561 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013562 CollectIvarsToConstructOrDestruct(OID, ivars);
13563 if (ivars.empty())
13564 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013565 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013566 for (unsigned i = 0; i < ivars.size(); i++) {
13567 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013568 if (Field->isInvalidDecl())
13569 continue;
13570
Alexis Hunt1d792652011-01-08 20:30:50 +000013571 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013572 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13573 InitializationKind InitKind =
13574 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013575
13576 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13577 ExprResult MemberInit =
13578 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013579 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013580 // Note, MemberInit could actually come back empty if no initialization
13581 // is required (e.g., because it would call a trivial default constructor)
13582 if (!MemberInit.get() || MemberInit.isInvalid())
13583 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013584
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013585 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013586 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13587 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013588 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013589 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013590 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013591
13592 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013593 if (const RecordType *RecordTy =
13594 Context.getBaseElementType(Field->getType())
13595 ->getAs<RecordType>()) {
13596 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013597 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013598 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013599 CheckDestructorAccess(Field->getLocation(), Destructor,
13600 PDiag(diag::err_access_dtor_ivar)
13601 << Context.getBaseElementType(Field->getType()));
13602 }
13603 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013604 }
13605 ObjCImplementation->setIvarInitializers(Context,
13606 AllToInit.data(), AllToInit.size());
13607 }
13608}
Alexis Hunt6118d662011-05-04 05:57:24 +000013609
Alexis Hunt27a761d2011-05-04 23:29:54 +000013610static
13611void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13612 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13613 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13614 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13615 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013616 if (Ctor->isInvalidDecl())
13617 return;
13618
Richard Smith802c4b72012-08-23 06:16:52 +000013619 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13620
13621 // Target may not be determinable yet, for instance if this is a dependent
13622 // call in an uninstantiated template.
13623 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013624 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013625 (void)Target->hasBody(FNTarget);
13626 Target = const_cast<CXXConstructorDecl*>(
13627 cast_or_null<CXXConstructorDecl>(FNTarget));
13628 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013629
13630 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13631 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013632 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013633
David Blaikie82e95a32014-11-19 07:49:47 +000013634 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013635 return;
13636
13637 // We know that beyond here, we aren't chaining into a cycle.
13638 if (!Target || !Target->isDelegatingConstructor() ||
13639 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013640 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013641 Current.clear();
13642 // We've hit a cycle.
13643 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13644 Current.count(TCanonical)) {
13645 // If we haven't diagnosed this cycle yet, do so now.
13646 if (!Invalid.count(TCanonical)) {
13647 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013648 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013649 << Ctor;
13650
Richard Smith802c4b72012-08-23 06:16:52 +000013651 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013652 if (TCanonical != Canonical)
13653 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13654
13655 CXXConstructorDecl *C = Target;
13656 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013657 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013658 (void)C->getTargetConstructor()->hasBody(FNTarget);
13659 assert(FNTarget && "Ctor cycle through bodiless function");
13660
Richard Smith802c4b72012-08-23 06:16:52 +000013661 C = const_cast<CXXConstructorDecl*>(
13662 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013663 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13664 }
13665 }
13666
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013667 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013668 Current.clear();
13669 } else {
13670 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13671 }
13672}
13673
13674
Alexis Hunt6118d662011-05-04 05:57:24 +000013675void Sema::CheckDelegatingCtorCycles() {
13676 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13677
Douglas Gregorbae31202011-07-27 21:57:17 +000013678 for (DelegatingCtorDeclsType::iterator
13679 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013680 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013681 I != E; ++I)
13682 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013683
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013684 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13685 CE = Invalid.end();
13686 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013687 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013688}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013689
Douglas Gregor3024f072012-04-16 07:05:22 +000013690namespace {
13691 /// \brief AST visitor that finds references to the 'this' expression.
13692 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13693 Sema &S;
13694
13695 public:
13696 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13697
13698 bool VisitCXXThisExpr(CXXThisExpr *E) {
13699 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13700 << E->isImplicit();
13701 return false;
13702 }
13703 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013704}
Douglas Gregor3024f072012-04-16 07:05:22 +000013705
13706bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13707 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13708 if (!TSInfo)
13709 return false;
13710
13711 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013712 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013713 if (!ProtoTL)
13714 return false;
13715
13716 // C++11 [expr.prim.general]p3:
13717 // [The expression this] shall not appear before the optional
13718 // cv-qualifier-seq and it shall not appear within the declaration of a
13719 // static member function (although its type and value category are defined
13720 // within a static member function as they are within a non-static member
13721 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013722 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013723 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013724 FindCXXThisExpr Finder(*this);
13725
13726 // If the return type came after the cv-qualifier-seq, check it now.
13727 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013728 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013729 return true;
13730
13731 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013732 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13733 return true;
13734
13735 return checkThisInStaticMemberFunctionAttributes(Method);
13736}
13737
13738bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13739 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13740 if (!TSInfo)
13741 return false;
13742
13743 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013744 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013745 if (!ProtoTL)
13746 return false;
13747
David Blaikie6adc78e2013-02-18 22:06:02 +000013748 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013749 FindCXXThisExpr Finder(*this);
13750
Douglas Gregor3024f072012-04-16 07:05:22 +000013751 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013752 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013753 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013754 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013755 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013756 case EST_DynamicNone:
13757 case EST_MSAny:
13758 case EST_None:
13759 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013760
Douglas Gregor3024f072012-04-16 07:05:22 +000013761 case EST_ComputedNoexcept:
13762 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13763 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013764
Douglas Gregor3024f072012-04-16 07:05:22 +000013765 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013766 for (const auto &E : Proto->exceptions()) {
13767 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013768 return true;
13769 }
13770 break;
13771 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013772
13773 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013774}
13775
13776bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13777 FindCXXThisExpr Finder(*this);
13778
13779 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013780 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013781 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013782 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013783 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013784 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013785 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013786 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013787 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013788 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013789 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013790 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013791 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013792 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013793 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013794 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013795 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013796 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013797 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013798 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013799 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013800 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013801 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013802 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013803 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013804 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013805 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013806 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013807 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013808 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013809 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013810
13811 if (Arg && !Finder.TraverseStmt(Arg))
13812 return true;
13813
13814 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13815 if (!Finder.TraverseStmt(Args[I]))
13816 return true;
13817 }
13818 }
13819
13820 return false;
13821}
13822
Richard Smith2e321552014-11-12 02:00:47 +000013823void Sema::checkExceptionSpecification(
13824 bool IsTopLevel, ExceptionSpecificationType EST,
13825 ArrayRef<ParsedType> DynamicExceptions,
13826 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13827 SmallVectorImpl<QualType> &Exceptions,
13828 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013829 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013830 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013831 if (EST == EST_Dynamic) {
13832 Exceptions.reserve(DynamicExceptions.size());
13833 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13834 // FIXME: Preserve type source info.
13835 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13836
Richard Smith2e321552014-11-12 02:00:47 +000013837 if (IsTopLevel) {
13838 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13839 collectUnexpandedParameterPacks(ET, Unexpanded);
13840 if (!Unexpanded.empty()) {
13841 DiagnoseUnexpandedParameterPacks(
13842 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13843 Unexpanded);
13844 continue;
13845 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013846 }
13847
13848 // Check that the type is valid for an exception spec, and
13849 // drop it if not.
13850 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13851 Exceptions.push_back(ET);
13852 }
Richard Smith8acb4282014-07-31 21:57:55 +000013853 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013854 return;
13855 }
Richard Smith8acb4282014-07-31 21:57:55 +000013856
Douglas Gregor433e0532012-04-16 18:27:27 +000013857 if (EST == EST_ComputedNoexcept) {
13858 // If an error occurred, there's no expression here.
13859 if (NoexceptExpr) {
13860 assert((NoexceptExpr->isTypeDependent() ||
13861 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13862 Context.BoolTy) &&
13863 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013864 if (IsTopLevel && NoexceptExpr &&
13865 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013866 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013867 return;
13868 }
Richard Smith8acb4282014-07-31 21:57:55 +000013869
Douglas Gregor433e0532012-04-16 18:27:27 +000013870 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013871 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013872 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013873 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013874 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013875 }
13876 return;
13877 }
13878}
13879
Richard Smith0b3a4622014-11-13 20:01:57 +000013880void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13881 ExceptionSpecificationType EST,
13882 SourceRange SpecificationRange,
13883 ArrayRef<ParsedType> DynamicExceptions,
13884 ArrayRef<SourceRange> DynamicExceptionRanges,
13885 Expr *NoexceptExpr) {
13886 if (!MethodD)
13887 return;
13888
13889 // Dig out the method we're referring to.
13890 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13891 MethodD = FunTmpl->getTemplatedDecl();
13892
13893 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13894 if (!Method)
13895 return;
13896
13897 // Check the exception specification.
13898 llvm::SmallVector<QualType, 4> Exceptions;
13899 FunctionProtoType::ExceptionSpecInfo ESI;
13900 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13901 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13902 ESI);
13903
13904 // Update the exception specification on the function type.
13905 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13906
13907 if (Method->isStatic())
13908 checkThisInStaticMemberFunctionExceptionSpec(Method);
13909
13910 if (Method->isVirtual()) {
13911 // Check overrides, which we previously had to delay.
13912 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13913 OEnd = Method->end_overridden_methods();
13914 O != OEnd; ++O)
13915 CheckOverridingFunctionExceptionSpec(Method, *O);
13916 }
13917}
13918
John McCall5e77d762013-04-16 07:28:30 +000013919/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13920///
13921MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13922 SourceLocation DeclStart,
13923 Declarator &D, Expr *BitWidth,
13924 InClassInitStyle InitStyle,
13925 AccessSpecifier AS,
13926 AttributeList *MSPropertyAttr) {
13927 IdentifierInfo *II = D.getIdentifier();
13928 if (!II) {
13929 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013930 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013931 }
13932 SourceLocation Loc = D.getIdentifierLoc();
13933
13934 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13935 QualType T = TInfo->getType();
13936 if (getLangOpts().CPlusPlus) {
13937 CheckExtraCXXDefaultArguments(D);
13938
13939 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13940 UPPC_DataMemberType)) {
13941 D.setInvalidType();
13942 T = Context.IntTy;
13943 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13944 }
13945 }
13946
13947 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13948
13949 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13950 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13951 diag::err_invalid_thread)
13952 << DeclSpec::getSpecifierName(TSCS);
13953
13954 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013955 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013956 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13957 LookupName(Previous, S);
13958 switch (Previous.getResultKind()) {
13959 case LookupResult::Found:
13960 case LookupResult::FoundUnresolvedValue:
13961 PrevDecl = Previous.getAsSingle<NamedDecl>();
13962 break;
13963
13964 case LookupResult::FoundOverloaded:
13965 PrevDecl = Previous.getRepresentativeDecl();
13966 break;
13967
13968 case LookupResult::NotFound:
13969 case LookupResult::NotFoundInCurrentInstantiation:
13970 case LookupResult::Ambiguous:
13971 break;
13972 }
13973
13974 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13975 // Maybe we will complain about the shadowed template parameter.
13976 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13977 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013978 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013979 }
13980
13981 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013982 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013983
13984 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013985 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013986 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13987 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013988 ProcessDeclAttributes(TUScope, NewPD, D);
13989 NewPD->setAccess(AS);
13990
13991 if (NewPD->isInvalidDecl())
13992 Record->setInvalidDecl();
13993
13994 if (D.getDeclSpec().isModulePrivateSpecified())
13995 NewPD->setModulePrivate();
13996
13997 if (NewPD->isInvalidDecl() && PrevDecl) {
13998 // Don't introduce NewFD into scope; there's already something
13999 // with the same name in the same scope.
14000 } else if (II) {
14001 PushOnScopeChains(NewPD, S);
14002 } else
14003 Record->addDecl(NewPD);
14004
14005 return NewPD;
14006}