blob: 2cc0d071a9634352583b9dad89140e0dd7b349e2 [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.
1556bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1557 unsigned NumBases) {
1558 if (NumBases == 0)
1559 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;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001574 for (unsigned idx = 0; idx < NumBases; ++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.
1600 if (NumBases > 1)
1601 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.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001622 Class->setBases(Bases, 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.
Richard Trieu9becef62011-09-09 03:18:59 +00001657void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001658 unsigned NumBases) {
1659 if (!ClassDecl || !Bases || !NumBases)
1660 return;
1661
1662 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
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
Richard Smith0f59cb32015-12-18 21:45:41 +00001676 // FIXME: In a modules build, do we need the entire path to be visible for us
1677 // to be able to use the inheritance relationship?
1678 if (RequireCompleteType(Loc, Derived, 0) && !DerivedRD->isBeingDefined())
1679 return false;
1680
Douglas Gregor45bb4832013-03-26 23:36:30 +00001681 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001682 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001683 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001684
1685 // If either the base or the derived type is invalid, don't try to
1686 // check whether one is derived from the other.
1687 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
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
Richard Smith0f59cb32015-12-18 21:45:41 +00001704 if (RequireCompleteType(Loc, Derived, 0) && !DerivedRD->isBeingDefined())
1705 return false;
1706
Douglas Gregor45bb4832013-03-26 23:36:30 +00001707 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001708 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709 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.
1745bool
1746Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001747 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001748 unsigned AmbigiousBaseConvID,
1749 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001750 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001751 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001752 // First, determine whether the path from Derived to Base is
1753 // ambiguous. This is slightly more expensive than checking whether
1754 // the Derived to Base conversion exists, because here we need to
1755 // explore multiple paths to determine if there is an ambiguity.
1756 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1757 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00001758 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001759 assert(DerivationOkay &&
1760 "Can only be used with a derived-to-base conversion");
1761 (void)DerivationOkay;
1762
1763 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001764 if (InaccessibleBaseID) {
1765 // Check that the base class can be accessed.
1766 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1767 InaccessibleBaseID)) {
1768 case AR_inaccessible:
1769 return true;
1770 case AR_accessible:
1771 case AR_dependent:
1772 case AR_delayed:
1773 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001774 }
John McCall5b0829a2010-02-10 09:31:12 +00001775 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001776
1777 // Build a base path if necessary.
1778 if (BasePath)
1779 BuildBasePathArray(Paths, *BasePath);
1780 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001781 }
1782
David Majnemer626032f2013-06-22 06:43:58 +00001783 if (AmbigiousBaseConvID) {
1784 // We know that the derived-to-base conversion is ambiguous, and
1785 // we're going to produce a diagnostic. Perform the derived-to-base
1786 // search just one more time to compute all of the possible paths so
1787 // that we can print them out. This is more expensive than any of
1788 // the previous derived-to-base checks we've done, but at this point
1789 // performance isn't as much of an issue.
1790 Paths.clear();
1791 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001792 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00001793 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1794 (void)StillOkay;
1795
1796 // Build up a textual representation of the ambiguous paths, e.g.,
1797 // D -> B -> A, that will be used to illustrate the ambiguous
1798 // conversions in the diagnostic. We only print one of the paths
1799 // to each base class subobject.
1800 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1801
1802 Diag(Loc, AmbigiousBaseConvID)
1803 << Derived << Base << PathDisplayStr << Range << Name;
1804 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001805 return true;
1806}
1807
1808bool
1809Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001810 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001811 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001812 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001813 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001814 IgnoreAccess ? 0
1815 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001816 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001817 Loc, Range, DeclarationName(),
1818 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001819}
1820
1821
1822/// @brief Builds a string representing ambiguous paths from a
1823/// specific derived class to different subobjects of the same base
1824/// class.
1825///
1826/// This function builds a string that can be used in error messages
1827/// to show the different paths that one can take through the
1828/// inheritance hierarchy to go from the derived class to different
1829/// subobjects of a base class. The result looks something like this:
1830/// @code
1831/// struct D -> struct B -> struct A
1832/// struct D -> struct C -> struct A
1833/// @endcode
1834std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1835 std::string PathDisplayStr;
1836 std::set<unsigned> DisplayedPaths;
1837 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1838 Path != Paths.end(); ++Path) {
1839 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1840 // We haven't displayed a path to this particular base
1841 // class subobject yet.
1842 PathDisplayStr += "\n ";
1843 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1844 for (CXXBasePath::const_iterator Element = Path->begin();
1845 Element != Path->end(); ++Element)
1846 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1847 }
1848 }
1849
1850 return PathDisplayStr;
1851}
1852
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001853//===----------------------------------------------------------------------===//
1854// C++ class member Handling
1855//===----------------------------------------------------------------------===//
1856
Abramo Bagnarad7340582010-06-05 05:09:32 +00001857/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001858bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1859 SourceLocation ASLoc,
1860 SourceLocation ColonLoc,
1861 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001862 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001863 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001864 ASLoc, ColonLoc);
1865 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001866 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001867}
1868
Richard Smith18f07db2012-08-06 03:25:17 +00001869/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001870void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001871 if (D->isInvalidDecl())
1872 return;
1873
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001874 // We only care about "override" and "final" declarations.
1875 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1876 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001877
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001878 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001879
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001880 // We can't check dependent instance methods.
1881 if (MD && MD->isInstance() &&
1882 (MD->getParent()->hasAnyDependentBases() ||
1883 MD->getType()->isDependentType()))
1884 return;
1885
1886 if (MD && !MD->isVirtual()) {
1887 // If we have a non-virtual method, check if if hides a virtual method.
1888 // (In that case, it's most likely the method has the wrong type.)
1889 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1890 FindHiddenVirtualMethods(MD, OverloadedMethods);
1891
1892 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001893 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1894 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001895 diag::override_keyword_hides_virtual_member_function)
1896 << "override" << (OverloadedMethods.size() > 1);
1897 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001898 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001899 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001900 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1901 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001902 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001903 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1904 MD->setInvalidDecl();
1905 return;
1906 }
1907 // Fall through into the general case diagnostic.
1908 // FIXME: We might want to attempt typo correction here.
1909 }
1910
1911 if (!MD || !MD->isVirtual()) {
1912 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1913 Diag(OA->getLocation(),
1914 diag::override_keyword_only_allowed_on_virtual_member_functions)
1915 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1916 D->dropAttr<OverrideAttr>();
1917 }
1918 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1919 Diag(FA->getLocation(),
1920 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001921 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1922 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001923 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001924 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001925 return;
1926 }
Richard Smith18f07db2012-08-06 03:25:17 +00001927
Richard Smith18f07db2012-08-06 03:25:17 +00001928 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001929 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001930 // does not override a member function of a base class, the program is
1931 // ill-formed.
1932 bool HasOverriddenMethods =
1933 MD->begin_overridden_methods() != MD->end_overridden_methods();
1934 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1935 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1936 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001937}
1938
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001939void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1940 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1941 return;
1942 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1943 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1944 isa<CXXDestructorDecl>(MD))
1945 return;
1946
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001947 SourceLocation Loc = MD->getLocation();
1948 SourceLocation SpellingLoc = Loc;
1949 if (getSourceManager().isMacroArgExpansion(Loc))
1950 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1951 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1952 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001953 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001954
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001955 if (MD->size_overridden_methods() > 0) {
1956 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1957 << MD->getDeclName();
1958 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1959 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1960 }
1961}
1962
Richard Smith18f07db2012-08-06 03:25:17 +00001963/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001964/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001965/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001966bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1967 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001968 FinalAttr *FA = Old->getAttr<FinalAttr>();
1969 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001970 return false;
1971
1972 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001973 << New->getDeclName()
1974 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001975 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1976 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001977}
1978
Daniel Jasper0baec5492012-06-06 08:32:04 +00001979static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001980 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1981 // FIXME: Destruction of ObjC lifetime types has side-effects.
1982 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1983 return !RD->isCompleteDefinition() ||
1984 !RD->hasTrivialDefaultConstructor() ||
1985 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001986 return false;
1987}
1988
John McCall5e77d762013-04-16 07:28:30 +00001989static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001990 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001991 if (it->isDeclspecPropertyAttribute())
1992 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001994}
1995
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001996/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1997/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001998/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001999/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2000/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002001NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002002Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002003 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002004 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002005 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002006 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002007 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2008 DeclarationName Name = NameInfo.getName();
2009 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002010
2011 // For anonymous bitfields, the location should point to the type.
2012 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002013 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002014
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002015 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002016
John McCallb1cd7da2010-06-04 08:34:12 +00002017 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002018 assert(!DS.isFriendSpecified());
2019
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002020 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002021
John McCalldb632ac2012-09-25 07:32:39 +00002022 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2023 // The Microsoft extension __interface only permits public member functions
2024 // and prohibits constructors, destructors, operators, non-public member
2025 // functions, static methods and data members.
2026 unsigned InvalidDecl;
2027 bool ShowDeclName = true;
2028 if (!isFunc)
2029 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2030 else if (AS != AS_public)
2031 InvalidDecl = 2;
2032 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2033 InvalidDecl = 3;
2034 else switch (Name.getNameKind()) {
2035 case DeclarationName::CXXConstructorName:
2036 InvalidDecl = 4;
2037 ShowDeclName = false;
2038 break;
2039
2040 case DeclarationName::CXXDestructorName:
2041 InvalidDecl = 5;
2042 ShowDeclName = false;
2043 break;
2044
2045 case DeclarationName::CXXOperatorName:
2046 case DeclarationName::CXXConversionFunctionName:
2047 InvalidDecl = 6;
2048 break;
2049
2050 default:
2051 InvalidDecl = 0;
2052 break;
2053 }
2054
2055 if (InvalidDecl) {
2056 if (ShowDeclName)
2057 Diag(Loc, diag::err_invalid_member_in_interface)
2058 << (InvalidDecl-1) << Name;
2059 else
2060 Diag(Loc, diag::err_invalid_member_in_interface)
2061 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002062 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002063 }
2064 }
2065
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002066 // C++ 9.2p6: A member shall not be declared to have automatic storage
2067 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002068 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2069 // data members and cannot be applied to names declared const or static,
2070 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002071 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002072 case DeclSpec::SCS_unspecified:
2073 case DeclSpec::SCS_typedef:
2074 case DeclSpec::SCS_static:
2075 break;
2076 case DeclSpec::SCS_mutable:
2077 if (isFunc) {
2078 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Richard Smithb4a9e862013-04-12 22:46:28 +00002080 // FIXME: It would be nicer if the keyword was ignored only for this
2081 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002082 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002083 }
2084 break;
2085 default:
2086 Diag(DS.getStorageClassSpecLoc(),
2087 diag::err_storageclass_invalid_for_member);
2088 D.getMutableDeclSpec().ClearStorageClassSpecs();
2089 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002090 }
2091
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002092 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2093 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002094 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002095
David Blaikie35506f82013-01-30 01:22:18 +00002096 if (DS.isConstexprSpecified() && isInstField) {
2097 SemaDiagnosticBuilder B =
2098 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2099 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2100 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002101 B << 0 << 0;
2102 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2103 B << FixItHint::CreateRemoval(ConstexprLoc);
2104 else {
2105 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2106 D.getMutableDeclSpec().ClearConstexprSpec();
2107 const char *PrevSpec;
2108 unsigned DiagID;
2109 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2110 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2111 (void)Failed;
2112 assert(!Failed && "Making a constexpr member const shouldn't fail");
2113 }
David Blaikie35506f82013-01-30 01:22:18 +00002114 } else {
2115 B << 1;
2116 const char *PrevSpec;
2117 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002118 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002119 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2120 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002121 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002122 "This is the only DeclSpec that should fail to be applied");
2123 B << 1;
2124 } else {
2125 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2126 isInstField = false;
2127 }
2128 }
2129 }
2130
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002131 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002132 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002133 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002134
2135 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002136 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002137 Diag(Loc, diag::err_bad_variable_name)
2138 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002139 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002140 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002141
Benjamin Kramer365082d2012-05-19 16:34:46 +00002142 IdentifierInfo *II = Name.getAsIdentifierInfo();
2143
Douglas Gregor7c26c042011-09-21 14:40:46 +00002144 // Member field could not be with "template" keyword.
2145 // So TemplateParameterLists should be empty in this case.
2146 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002147 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002148 if (TemplateParams->size()) {
2149 // There is no such thing as a member field template.
2150 Diag(D.getIdentifierLoc(), diag::err_template_member)
2151 << II
2152 << SourceRange(TemplateParams->getTemplateLoc(),
2153 TemplateParams->getRAngleLoc());
2154 } else {
2155 // There is an extraneous 'template<>' for this member.
2156 Diag(TemplateParams->getTemplateLoc(),
2157 diag::err_template_member_noparams)
2158 << II
2159 << SourceRange(TemplateParams->getTemplateLoc(),
2160 TemplateParams->getRAngleLoc());
2161 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002162 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002163 }
2164
Douglas Gregora007d362010-10-13 22:19:53 +00002165 if (SS.isSet() && !SS.isInvalid()) {
2166 // The user provided a superfluous scope specifier inside a class
2167 // definition:
2168 //
2169 // class X {
2170 // int X::member;
2171 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002172 if (DeclContext *DC = computeDeclContext(SS, false))
2173 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002174 else
2175 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2176 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002177
Douglas Gregora007d362010-10-13 22:19:53 +00002178 SS.clear();
2179 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002180
John McCall5e77d762013-04-16 07:28:30 +00002181 AttributeList *MSPropertyAttr =
2182 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002183 if (MSPropertyAttr) {
2184 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2185 BitWidth, InitStyle, AS, MSPropertyAttr);
2186 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002187 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002188 isInstField = false;
2189 } else {
2190 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2191 BitWidth, InitStyle, AS);
2192 assert(Member && "HandleField never returns null");
2193 }
2194 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002195 Member = HandleDeclarator(S, D, TemplateParameterLists);
2196 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002197 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002198
2199 // Non-instance-fields can't have a bitfield.
2200 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002201 if (Member->isInvalidDecl()) {
2202 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002203 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002204 // C++ 9.6p3: A bit-field shall not be a static member.
2205 // "static member 'A' cannot be a bit-field"
2206 Diag(Loc, diag::err_static_not_bitfield)
2207 << Name << BitWidth->getSourceRange();
2208 } else if (isa<TypedefDecl>(Member)) {
2209 // "typedef member 'x' cannot be a bit-field"
2210 Diag(Loc, diag::err_typedef_not_bitfield)
2211 << Name << BitWidth->getSourceRange();
2212 } else {
2213 // A function typedef ("typedef int f(); f a;").
2214 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2215 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002216 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002217 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
Craig Topperc3ec1492014-05-26 06:22:03 +00002220 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002221 Member->setInvalidDecl();
2222 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002223
2224 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002225
Larisse Voufo39a1e502013-08-06 01:03:05 +00002226 // If we have declared a member function template or static data member
2227 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002228 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2229 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002230 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2231 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002232 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002233
Richard Smith18f07db2012-08-06 03:25:17 +00002234 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002235 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002236 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002237 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2238 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002239
Douglas Gregorf2f08062011-03-08 17:10:18 +00002240 if (VS.getLastLocation().isValid()) {
2241 // Update the end location of a method that has a virt-specifiers.
2242 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2243 MD->setRangeEnd(VS.getLastLocation());
2244 }
Richard Smith18f07db2012-08-06 03:25:17 +00002245
Anders Carlssonc87f8612011-01-20 06:29:02 +00002246 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002247
Douglas Gregor92751d42008-11-17 22:58:34 +00002248 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002249
Daniel Jasper0baec5492012-06-06 08:32:04 +00002250 if (isInstField) {
2251 FieldDecl *FD = cast<FieldDecl>(Member);
2252 FieldCollector->Add(FD);
2253
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002254 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002255 // Remember all explicit private FieldDecls that have a name, no side
2256 // effects and are not part of a dependent type declaration.
2257 if (!FD->isImplicit() && FD->getDeclName() &&
2258 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002259 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002260 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002261 !InitializationHasSideEffects(*FD))
2262 UnusedPrivateFields.insert(FD);
2263 }
2264 }
2265
John McCall48871652010-08-21 09:40:31 +00002266 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002267}
2268
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002269namespace {
2270 class UninitializedFieldVisitor
2271 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2272 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002273 // List of Decls to generate a warning on. Also remove Decls that become
2274 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002275 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002276 // List of base classes of the record. Classes are removed after their
2277 // initializers.
2278 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002279 // Vector of decls to be removed from the Decl set prior to visiting the
2280 // nodes. These Decls may have been initialized in the prior initializer.
2281 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002282 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002283 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002284 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002285 // InitList is true, special case initialization of FieldDecls matching
2286 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002287 bool InitList;
2288 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002289 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2290
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002291 public:
2292 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002293 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002294 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2295 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2296 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2297 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002298
Richard Trieufa1d0a72014-10-17 20:56:10 +00002299 // Returns true if the use of ME is not an uninitialized use.
2300 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2301 bool CheckReferenceOnly) {
2302 llvm::SmallVector<FieldDecl*, 4> Fields;
2303 bool ReferenceField = false;
2304 while (ME) {
2305 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2306 if (!FD)
2307 return false;
2308 Fields.push_back(FD);
2309 if (FD->getType()->isReferenceType())
2310 ReferenceField = true;
2311 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2312 }
2313
2314 // Binding a reference to an unintialized field is not an
2315 // uninitialized use.
2316 if (CheckReferenceOnly && !ReferenceField)
2317 return true;
2318
2319 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2320 // Discard the first field since it is the field decl that is being
2321 // initialized.
2322 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2323 UsedFieldIndex.push_back((*I)->getFieldIndex());
2324 }
2325
2326 for (auto UsedIter = UsedFieldIndex.begin(),
2327 UsedEnd = UsedFieldIndex.end(),
2328 OrigIter = InitFieldIndex.begin(),
2329 OrigEnd = InitFieldIndex.end();
2330 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2331 if (*UsedIter < *OrigIter)
2332 return true;
2333 if (*UsedIter > *OrigIter)
2334 break;
2335 }
2336
2337 return false;
2338 }
2339
Richard Trieu2d779b92014-10-01 03:44:58 +00002340 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2341 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002342 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2343 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002344
Richard Trieu1bc22c12013-09-13 03:20:53 +00002345 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2346 // or union.
2347 MemberExpr *FieldME = ME;
2348
Richard Trieu2d779b92014-10-01 03:44:58 +00002349 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2350
Richard Trieu1bc22c12013-09-13 03:20:53 +00002351 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002352 while (MemberExpr *SubME =
2353 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002354
Richard Trieufa1d0a72014-10-17 20:56:10 +00002355 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002356 return;
2357
Richard Trieufa1d0a72014-10-17 20:56:10 +00002358 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002359 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002360 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002361
Richard Trieu2d779b92014-10-01 03:44:58 +00002362 if (!FieldME->getType().isPODType(S.Context))
2363 AllPODFields = false;
2364
Richard Trieu3630c392014-11-21 03:10:30 +00002365 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002366 }
2367
Richard Trieu3630c392014-11-21 03:10:30 +00002368 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002369 return;
2370
Richard Trieu2d779b92014-10-01 03:44:58 +00002371 if (AddressOf && AllPODFields)
2372 return;
2373
Richard Trieu406e65c2013-09-20 03:03:06 +00002374 ValueDecl* FoundVD = FieldME->getMemberDecl();
2375
Richard Trieu3630c392014-11-21 03:10:30 +00002376 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2377 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2378 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2379 }
2380
2381 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2382 QualType T = BaseCast->getType();
2383 if (T->isPointerType() &&
2384 BaseClasses.count(T->getPointeeType())) {
2385 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2386 << T->getPointeeType() << FoundVD;
2387 }
2388 }
2389 }
2390
Richard Trieuef64e942013-10-25 00:56:00 +00002391 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002392 return;
2393
Richard Trieuef64e942013-10-25 00:56:00 +00002394 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002395
Richard Trieufa1d0a72014-10-17 20:56:10 +00002396 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2397 // Special checking for initializer lists.
2398 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2399 return;
2400 }
2401 } else {
2402 // Prevent double warnings on use of unbounded references.
2403 if (CheckReferenceOnly && !IsReference)
2404 return;
2405 }
Richard Trieuef64e942013-10-25 00:56:00 +00002406
2407 unsigned diag = IsReference
2408 ? diag::warn_reference_field_is_uninit
2409 : diag::warn_field_is_uninit;
2410 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2411 if (Constructor)
2412 S.Diag(Constructor->getLocation(),
2413 diag::note_uninit_in_this_constructor)
2414 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2415
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002416 }
2417
Richard Trieu2d779b92014-10-01 03:44:58 +00002418 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002419 E = E->IgnoreParens();
2420
2421 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002422 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2423 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002424 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002425 }
2426
2427 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002428 Visit(CO->getCond());
2429 HandleValue(CO->getTrueExpr(), AddressOf);
2430 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002431 return;
2432 }
2433
2434 if (BinaryConditionalOperator *BCO =
2435 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002436 Visit(BCO->getCond());
2437 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002438 return;
2439 }
2440
Richard Trieuabf6ec42014-08-27 22:15:10 +00002441 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002442 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002443 return;
2444 }
2445
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002446 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2447 switch (BO->getOpcode()) {
2448 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002449 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002450 case(BO_PtrMemD):
2451 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002452 HandleValue(BO->getLHS(), AddressOf);
2453 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002454 return;
2455 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002456 Visit(BO->getLHS());
2457 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002458 return;
2459 }
2460 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002461
2462 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002463 }
2464
Richard Trieufa1d0a72014-10-17 20:56:10 +00002465 void CheckInitListExpr(InitListExpr *ILE) {
2466 InitFieldIndex.push_back(0);
2467 for (auto Child : ILE->children()) {
2468 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2469 CheckInitListExpr(SubList);
2470 } else {
2471 Visit(Child);
2472 }
2473 ++InitFieldIndex.back();
2474 }
2475 InitFieldIndex.pop_back();
2476 }
2477
Richard Trieu8d08a272014-08-28 03:23:47 +00002478 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002479 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002480 // Remove Decls that may have been initialized in the previous
2481 // initializer.
2482 for (ValueDecl* VD : DeclsToRemove)
2483 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002484 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002485
Richard Trieu8d08a272014-08-28 03:23:47 +00002486 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002487 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2488
2489 if (ILE && Field) {
2490 InitList = true;
2491 InitListFieldDecl = Field;
2492 InitFieldIndex.clear();
2493 CheckInitListExpr(ILE);
2494 } else {
2495 InitList = false;
2496 Visit(E);
2497 }
2498
Richard Trieu8d08a272014-08-28 03:23:47 +00002499 if (Field)
2500 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002501 if (BaseClass)
2502 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002503 }
2504
Richard Trieu1bc22c12013-09-13 03:20:53 +00002505 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002506 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002507 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002508 }
2509
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002510 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002511 if (E->getCastKind() == CK_LValueToRValue) {
2512 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2513 return;
2514 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002515
2516 Inherited::VisitImplicitCastExpr(E);
2517 }
2518
Richard Trieu1bc22c12013-09-13 03:20:53 +00002519 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002520 if (E->getConstructor()->isCopyConstructor()) {
2521 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002522 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2523 if (ILE->getNumInits() == 1)
2524 ArgExpr = ILE->getInit(0);
2525 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2526 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002527 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002528 HandleValue(ArgExpr, false /*AddressOf*/);
2529 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002530 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002531 Inherited::VisitCXXConstructExpr(E);
2532 }
2533
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002534 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2535 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002536 if (isa<MemberExpr>(Callee)) {
2537 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002538 for (auto Arg : E->arguments())
2539 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002540 return;
2541 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002542
2543 Inherited::VisitCXXMemberCallExpr(E);
2544 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002545
Richard Trieu11fd0792014-08-26 04:30:55 +00002546 void VisitCallExpr(CallExpr *E) {
2547 // Treat std::move as a use.
2548 if (E->getNumArgs() == 1) {
2549 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002550 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2551 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002552 HandleValue(E->getArg(0), false /*AddressOf*/);
2553 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002554 }
2555 }
2556 }
2557
2558 Inherited::VisitCallExpr(E);
2559 }
2560
Richard Trieud4a01362014-10-31 21:10:22 +00002561 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2562 Expr *Callee = E->getCallee();
2563
2564 if (isa<UnresolvedLookupExpr>(Callee))
2565 return Inherited::VisitCXXOperatorCallExpr(E);
2566
2567 Visit(Callee);
2568 for (auto Arg : E->arguments())
2569 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2570 }
2571
Richard Trieu406e65c2013-09-20 03:03:06 +00002572 void VisitBinaryOperator(BinaryOperator *E) {
2573 // If a field assignment is detected, remove the field from the
2574 // uninitiailized field set.
2575 if (E->getOpcode() == BO_Assign)
2576 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2577 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002578 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002579 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002580
Richard Trieu52b8b602014-09-25 01:15:40 +00002581 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002582 HandleValue(E->getLHS(), false /*AddressOf*/);
2583 Visit(E->getRHS());
2584 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002585 }
2586
Richard Trieu406e65c2013-09-20 03:03:06 +00002587 Inherited::VisitBinaryOperator(E);
2588 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002589
2590 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002591 if (E->isIncrementDecrementOp()) {
2592 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2593 return;
2594 }
2595 if (E->getOpcode() == UO_AddrOf) {
2596 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2597 HandleValue(ME->getBase(), true /*AddressOf*/);
2598 return;
2599 }
2600 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002601
2602 Inherited::VisitUnaryOperator(E);
2603 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002604 };
Richard Trieuef64e942013-10-25 00:56:00 +00002605
2606 // Diagnose value-uses of fields to initialize themselves, e.g.
2607 // foo(foo)
2608 // where foo is not also a parameter to the constructor.
2609 // Also diagnose across field uninitialized use such as
2610 // x(y), y(x)
2611 // TODO: implement -Wuninitialized and fold this into that framework.
2612 static void DiagnoseUninitializedFields(
2613 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2614
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002615 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2616 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002617 return;
2618 }
2619
2620 if (Constructor->isInvalidDecl())
2621 return;
2622
2623 const CXXRecordDecl *RD = Constructor->getParent();
2624
Richard Trieu353a4b42014-10-22 05:21:59 +00002625 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002626 return;
2627
Richard Trieuef64e942013-10-25 00:56:00 +00002628 // Holds fields that are uninitialized.
2629 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2630
2631 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002632 for (auto *I : RD->decls()) {
2633 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002634 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002635 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002636 UninitializedFields.insert(IFD->getAnonField());
2637 }
2638 }
2639
Richard Trieu3630c392014-11-21 03:10:30 +00002640 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2641 for (auto I : RD->bases())
2642 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2643
2644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002645 return;
2646
2647 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002648 UninitializedFields,
2649 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002650
Aaron Ballman0ad78302014-03-13 17:34:31 +00002651 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002652 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002653 break;
2654
Aaron Ballman0ad78302014-03-13 17:34:31 +00002655 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002656 if (!InitExpr)
2657 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002658
Richard Trieu8d08a272014-08-28 03:23:47 +00002659 if (CXXDefaultInitExpr *Default =
2660 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2661 InitExpr = Default->getExpr();
2662 if (!InitExpr)
2663 continue;
2664 // In class initializers will point to the constructor.
2665 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002666 FieldInit->getAnyMember(),
2667 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002668 } else {
2669 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002670 FieldInit->getAnyMember(),
2671 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002672 }
Richard Trieuef64e942013-10-25 00:56:00 +00002673 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002674 }
2675} // namespace
2676
Richard Smith74108172014-01-17 03:11:34 +00002677/// \brief Enter a new C++ default initializer scope. After calling this, the
2678/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2679/// parsing or instantiating the initializer failed.
2680void Sema::ActOnStartCXXInClassMemberInitializer() {
2681 // Create a synthetic function scope to represent the call to the constructor
2682 // that notionally surrounds a use of this initializer.
2683 PushFunctionScope();
2684}
2685
2686/// \brief This is invoked after parsing an in-class initializer for a
2687/// non-static C++ class member, and after instantiating an in-class initializer
2688/// in a class template. Such actions are deferred until the class is complete.
2689void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2690 SourceLocation InitLoc,
2691 Expr *InitExpr) {
2692 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002693 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002694
David Majnemer87ff66c2014-12-13 11:34:16 +00002695 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2696 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002697 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002698
2699 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002700 D->setInvalidDecl();
2701 if (FD)
2702 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002703 return;
2704 }
2705
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002706 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2707 FD->setInvalidDecl();
2708 FD->removeInClassInitializer();
2709 return;
2710 }
2711
Richard Smith938f40b2011-06-11 17:19:42 +00002712 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002713 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002714 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002715 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002716 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002717 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002718 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2719 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002720 if (Init.isInvalid()) {
2721 FD->setInvalidDecl();
2722 return;
2723 }
Richard Smith938f40b2011-06-11 17:19:42 +00002724 }
2725
Richard Smith945f8d32013-01-14 22:39:08 +00002726 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002727 // The initialization of each base and member constitutes a
2728 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002729 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002730 if (Init.isInvalid()) {
2731 FD->setInvalidDecl();
2732 return;
2733 }
2734
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002735 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002736
2737 FD->setInClassInitializer(InitExpr);
2738}
2739
Douglas Gregor15e77a22009-12-31 09:10:24 +00002740/// \brief Find the direct and/or virtual base specifiers that
2741/// correspond to the given base type, for use in base initialization
2742/// within a constructor.
2743static bool FindBaseInitializer(Sema &SemaRef,
2744 CXXRecordDecl *ClassDecl,
2745 QualType BaseType,
2746 const CXXBaseSpecifier *&DirectBaseSpec,
2747 const CXXBaseSpecifier *&VirtualBaseSpec) {
2748 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002749 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002750 for (const auto &Base : ClassDecl->bases()) {
2751 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002752 // We found a direct base of this type. That's what we're
2753 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002754 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002755 break;
2756 }
2757 }
2758
2759 // Check for a virtual base class.
2760 // FIXME: We might be able to short-circuit this if we know in advance that
2761 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002762 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002763 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2764 // We haven't found a base yet; search the class hierarchy for a
2765 // virtual base class.
2766 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2767 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002768 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2769 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00002770 BaseType, Paths)) {
2771 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2772 Path != Paths.end(); ++Path) {
2773 if (Path->back().Base->isVirtual()) {
2774 VirtualBaseSpec = Path->back().Base;
2775 break;
2776 }
2777 }
2778 }
2779 }
2780
2781 return DirectBaseSpec || VirtualBaseSpec;
2782}
2783
Sebastian Redla74948d2011-09-24 17:48:25 +00002784/// \brief Handle a C++ member initializer using braced-init-list syntax.
2785MemInitResult
2786Sema::ActOnMemInitializer(Decl *ConstructorD,
2787 Scope *S,
2788 CXXScopeSpec &SS,
2789 IdentifierInfo *MemberOrBase,
2790 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002791 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002792 SourceLocation IdLoc,
2793 Expr *InitList,
2794 SourceLocation EllipsisLoc) {
2795 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002796 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002797 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002798}
2799
2800/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002801MemInitResult
John McCall48871652010-08-21 09:40:31 +00002802Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002803 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002804 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002805 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002806 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002807 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002808 SourceLocation IdLoc,
2809 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002810 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002811 SourceLocation RParenLoc,
2812 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002813 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002814 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002815 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002816 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002817}
2818
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002819namespace {
2820
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002821// Callback to only accept typo corrections that can be a valid C++ member
2822// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002823class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002824public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002825 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2826 : ClassDecl(ClassDecl) {}
2827
Craig Toppera798a9d2014-03-02 09:32:10 +00002828 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002829 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2830 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2831 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002832 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002833 }
2834 return false;
2835 }
2836
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002837private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002838 CXXRecordDecl *ClassDecl;
2839};
2840
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002841}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002842
Sebastian Redla74948d2011-09-24 17:48:25 +00002843/// \brief Handle a C++ member initializer.
2844MemInitResult
2845Sema::BuildMemInitializer(Decl *ConstructorD,
2846 Scope *S,
2847 CXXScopeSpec &SS,
2848 IdentifierInfo *MemberOrBase,
2849 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002850 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002851 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002852 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002853 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002854 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2855 if (!Res.isUsable())
2856 return true;
2857 Init = Res.get();
2858
Douglas Gregor71a57182009-06-22 23:20:33 +00002859 if (!ConstructorD)
2860 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002861
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002862 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002863
2864 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002865 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002866 if (!Constructor) {
2867 // The user wrote a constructor initializer on a function that is
2868 // not a C++ constructor. Ignore the error for now, because we may
2869 // have more member initializers coming; we'll diagnose it just
2870 // once in ActOnMemInitializers.
2871 return true;
2872 }
2873
2874 CXXRecordDecl *ClassDecl = Constructor->getParent();
2875
2876 // C++ [class.base.init]p2:
2877 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002878 // constructor's class and, if not found in that scope, are looked
2879 // up in the scope containing the constructor's definition.
2880 // [Note: if the constructor's class contains a member with the
2881 // same name as a direct or virtual base class of the class, a
2882 // mem-initializer-id naming the member or base class and composed
2883 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002884 // mem-initializer-id for the hidden base class may be specified
2885 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002886 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002887 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002888 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002889 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002890 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002891 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2892 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002893 if (EllipsisLoc.isValid())
2894 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002895 << MemberOrBase
2896 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002897
Sebastian Redla9351792012-02-11 23:51:47 +00002898 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002899 }
Francois Pichetd583da02010-12-04 09:14:42 +00002900 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002901 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002902 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002903 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002904 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002905
2906 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002907 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002908 } else if (DS.getTypeSpecType() == TST_decltype) {
2909 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002910 } else {
2911 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2912 LookupParsedName(R, S, &SS);
2913
2914 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2915 if (!TyD) {
2916 if (R.isAmbiguous()) return true;
2917
John McCallda6841b2010-04-09 19:01:14 +00002918 // We don't want access-control diagnostics here.
2919 R.suppressDiagnostics();
2920
Douglas Gregora3b624a2010-01-19 06:46:48 +00002921 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2922 bool NotUnknownSpecialization = false;
2923 DeclContext *DC = computeDeclContext(SS, false);
2924 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2925 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2926
2927 if (!NotUnknownSpecialization) {
2928 // When the scope specifier can refer to a member of an unknown
2929 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002930 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2931 SS.getWithLocInContext(Context),
2932 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002933 if (BaseType.isNull())
2934 return true;
2935
Douglas Gregora3b624a2010-01-19 06:46:48 +00002936 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002937 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002938 }
2939 }
2940
Douglas Gregor15e77a22009-12-31 09:10:24 +00002941 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002942 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002943 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002944 (Corr = CorrectTypo(
2945 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2946 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2947 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002948 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002949 // We have found a non-static data member with a similar
2950 // name to what was typed; complain and initialize that
2951 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002952 diagnoseTypo(Corr,
2953 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2954 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002955 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002956 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002957 const CXXBaseSpecifier *DirectBaseSpec;
2958 const CXXBaseSpecifier *VirtualBaseSpec;
2959 if (FindBaseInitializer(*this, ClassDecl,
2960 Context.getTypeDeclType(Type),
2961 DirectBaseSpec, VirtualBaseSpec)) {
2962 // We have found a direct or virtual base class with a
2963 // similar name to what was typed; complain and initialize
2964 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002965 diagnoseTypo(Corr,
2966 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2967 << MemberOrBase << false,
2968 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002969
Richard Smithf9b15102013-08-17 00:46:16 +00002970 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2971 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002972 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002973 diag::note_base_class_specified_here)
2974 << BaseSpec->getType()
2975 << BaseSpec->getSourceRange();
2976
Douglas Gregor15e77a22009-12-31 09:10:24 +00002977 TyD = Type;
2978 }
2979 }
2980 }
2981
Douglas Gregora3b624a2010-01-19 06:46:48 +00002982 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002983 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002984 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002985 return true;
2986 }
John McCallb5a0d312009-12-21 10:41:20 +00002987 }
2988
Douglas Gregora3b624a2010-01-19 06:46:48 +00002989 if (BaseType.isNull()) {
2990 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00002991 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00002992 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00002993 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2994 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00002995 TInfo = Context.CreateTypeSourceInfo(BaseType);
2996 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
2997 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
2998 TL.setElaboratedKeywordLoc(SourceLocation());
2999 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3000 }
John McCallb5a0d312009-12-21 10:41:20 +00003001 }
3002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
John McCallbcd03502009-12-07 02:54:59 +00003004 if (!TInfo)
3005 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003006
Sebastian Redla9351792012-02-11 23:51:47 +00003007 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003008}
3009
Chandler Carruth599deef2011-09-03 01:14:15 +00003010/// Checks a member initializer expression for cases where reference (or
3011/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003012static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3013 Expr *Init,
3014 SourceLocation IdLoc) {
3015 QualType MemberTy = Member->getType();
3016
3017 // We only handle pointers and references currently.
3018 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3019 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3020 return;
3021
3022 const bool IsPointer = MemberTy->isPointerType();
3023 if (IsPointer) {
3024 if (const UnaryOperator *Op
3025 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3026 // The only case we're worried about with pointers requires taking the
3027 // address.
3028 if (Op->getOpcode() != UO_AddrOf)
3029 return;
3030
3031 Init = Op->getSubExpr();
3032 } else {
3033 // We only handle address-of expression initializers for pointers.
3034 return;
3035 }
3036 }
3037
Richard Smithe3b28bc2013-06-12 21:51:50 +00003038 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003039 // We only warn when referring to a non-reference parameter declaration.
3040 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3041 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003042 return;
3043
3044 S.Diag(Init->getExprLoc(),
3045 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3046 : diag::warn_bind_ref_member_to_parameter)
3047 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003048 } else {
3049 // Other initializers are fine.
3050 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003051 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003052
3053 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3054 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003055}
3056
John McCallfaf5fb42010-08-26 23:41:50 +00003057MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003058Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003059 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003060 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3061 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3062 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003063 "Member must be a FieldDecl or IndirectFieldDecl");
3064
Sebastian Redla9351792012-02-11 23:51:47 +00003065 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003066 return true;
3067
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003068 if (Member->isInvalidDecl())
3069 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003070
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003071 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003072 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003073 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003074 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003075 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003076 } else {
3077 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003078 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003079 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003080
Sebastian Redla9351792012-02-11 23:51:47 +00003081 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003082
Sebastian Redla9351792012-02-11 23:51:47 +00003083 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003084 // Can't check initialization for a member of dependent type or when
3085 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003086 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003087 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003088 bool InitList = false;
3089 if (isa<InitListExpr>(Init)) {
3090 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003091 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003092 }
3093
Chandler Carruthd44c3102010-12-06 09:23:57 +00003094 // Initialize the member.
3095 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003096 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3097 : InitializedEntity::InitializeMember(IndirectMember,
3098 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003099 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003100 InitList ? InitializationKind::CreateDirectList(IdLoc)
3101 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3102 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003103
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003104 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003105 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3106 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003107 if (MemberInit.isInvalid())
3108 return true;
3109
Richard Smith736a9472013-06-12 20:42:33 +00003110 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3111
Richard Smith945f8d32013-01-14 22:39:08 +00003112 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003113 // The initialization of each base and member constitutes a
3114 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003115 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003116 if (MemberInit.isInvalid())
3117 return true;
3118
Richard Smithd59b8322012-12-19 01:39:02 +00003119 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003120 }
3121
Chandler Carruthd44c3102010-12-06 09:23:57 +00003122 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003123 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3124 InitRange.getBegin(), Init,
3125 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003126 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003127 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3128 InitRange.getBegin(), Init,
3129 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003130 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003131}
3132
John McCallfaf5fb42010-08-26 23:41:50 +00003133MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003134Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003135 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003136 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003137 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003138 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003139 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003140 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003141
Sebastian Redl0501c632012-02-12 16:37:36 +00003142 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003143 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003144 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3145 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003146 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003147 }
3148
Sebastian Redla9351792012-02-11 23:51:47 +00003149 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003150 // Initialize the object.
3151 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3152 QualType(ClassDecl->getTypeForDecl(), 0));
3153 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003154 InitList ? InitializationKind::CreateDirectList(NameLoc)
3155 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3156 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003157 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003158 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003159 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003160 if (DelegationInit.isInvalid())
3161 return true;
3162
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003163 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3164 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003165
Richard Smith945f8d32013-01-14 22:39:08 +00003166 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003167 // The initialization of each base and member constitutes a
3168 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003169 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3170 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003171 if (DelegationInit.isInvalid())
3172 return true;
3173
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003174 // If we are in a dependent context, template instantiation will
3175 // perform this type-checking again. Just save the arguments that we
3176 // received in a ParenListExpr.
3177 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3178 // of the information that we have about the base
3179 // initializer. However, deconstructing the ASTs is a dicey process,
3180 // and this approach is far more likely to get the corner cases right.
3181 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003182 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003183
Sebastian Redla9351792012-02-11 23:51:47 +00003184 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003185 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003186 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003187}
3188
3189MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003190Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003191 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003192 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003193 SourceLocation BaseLoc
3194 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003195
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003196 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3197 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3198 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3199
3200 // C++ [class.base.init]p2:
3201 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003202 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003203 // of that class, the mem-initializer is ill-formed. A
3204 // mem-initializer-list can initialize a base class using any
3205 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003206 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003207
Sebastian Redla9351792012-02-11 23:51:47 +00003208 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003209 if (EllipsisLoc.isValid()) {
3210 // This is a pack expansion.
3211 if (!BaseType->containsUnexpandedParameterPack()) {
3212 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003213 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003214
Douglas Gregor44e7df62011-01-04 00:32:56 +00003215 EllipsisLoc = SourceLocation();
3216 }
3217 } else {
3218 // Check for any unexpanded parameter packs.
3219 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3220 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003221
Sebastian Redla9351792012-02-11 23:51:47 +00003222 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003223 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003224 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003225
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003226 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003227 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3228 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003229 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003230 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3231 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003232 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003233
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003234 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3235 VirtualBaseSpec);
3236
3237 // C++ [base.class.init]p2:
3238 // Unless the mem-initializer-id names a nonstatic data member of the
3239 // constructor's class or a direct or virtual base of that class, the
3240 // mem-initializer is ill-formed.
3241 if (!DirectBaseSpec && !VirtualBaseSpec) {
3242 // If the class has any dependent bases, then it's possible that
3243 // one of those types will resolve to the same type as
3244 // BaseType. Therefore, just treat this as a dependent base
3245 // class initialization. FIXME: Should we try to check the
3246 // initialization anyway? It seems odd.
3247 if (ClassDecl->hasAnyDependentBases())
3248 Dependent = true;
3249 else
3250 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3251 << BaseType << Context.getTypeDeclType(ClassDecl)
3252 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3253 }
3254 }
3255
3256 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003257 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003258
Sebastian Redla74948d2011-09-24 17:48:25 +00003259 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3260 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003261 InitRange.getBegin(), Init,
3262 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003263 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003264
3265 // C++ [base.class.init]p2:
3266 // If a mem-initializer-id is ambiguous because it designates both
3267 // a direct non-virtual base class and an inherited virtual base
3268 // class, the mem-initializer is ill-formed.
3269 if (DirectBaseSpec && VirtualBaseSpec)
3270 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003271 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003272
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003274 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003275 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003276
3277 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003278 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003279 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003280 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003281 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003282 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003283 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003284
3285 InitializedEntity BaseEntity =
3286 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3287 InitializationKind Kind =
3288 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3289 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3290 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003291 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003292 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003293 if (BaseInit.isInvalid())
3294 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003295
Richard Smith945f8d32013-01-14 22:39:08 +00003296 // C++11 [class.base.init]p7:
3297 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003298 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003299 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003300 if (BaseInit.isInvalid())
3301 return true;
3302
3303 // If we are in a dependent context, template instantiation will
3304 // perform this type-checking again. Just save the arguments that we
3305 // received in a ParenListExpr.
3306 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3307 // of the information that we have about the base
3308 // initializer. However, deconstructing the ASTs is a dicey process,
3309 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003310 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003311 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003312
Alexis Hunt1d792652011-01-08 20:30:50 +00003313 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003314 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003315 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003316 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003317 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003318}
3319
Sebastian Redl22653ba2011-08-30 19:58:05 +00003320// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003321static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3322 if (T.isNull()) T = E->getType();
3323 QualType TargetType = SemaRef.BuildReferenceType(
3324 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003325 SourceLocation ExprLoc = E->getLocStart();
3326 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3327 TargetType, ExprLoc);
3328
3329 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3330 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003331 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003332}
3333
Anders Carlsson1b00e242010-04-23 03:10:23 +00003334/// ImplicitInitializerKind - How an implicit base or member initializer should
3335/// initialize its base or member.
3336enum ImplicitInitializerKind {
3337 IIK_Default,
3338 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003339 IIK_Move,
3340 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003341};
3342
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003343static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003344BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003345 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003346 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003347 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003348 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003349 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003350 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3351 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003352
John McCalldadc5752010-08-24 06:29:42 +00003353 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003354
3355 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003356 case IIK_Inherit: {
3357 const CXXRecordDecl *Inherited =
3358 Constructor->getInheritedConstructor()->getParent();
3359 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3360 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3361 // C++11 [class.inhctor]p8:
3362 // Each expression in the expression-list is of the form
3363 // static_cast<T&&>(p), where p is the name of the corresponding
3364 // constructor parameter and T is the declared type of p.
3365 SmallVector<Expr*, 16> Args;
3366 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3367 ParmVarDecl *PD = Constructor->getParamDecl(I);
3368 ExprResult ArgExpr =
3369 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3370 VK_LValue, SourceLocation());
3371 if (ArgExpr.isInvalid())
3372 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003373 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003374 }
3375
3376 InitializationKind InitKind = InitializationKind::CreateDirect(
3377 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003378 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003379 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3380 break;
3381 }
3382 }
3383 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003384 case IIK_Default: {
3385 InitializationKind InitKind
3386 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003387 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3388 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003389 break;
3390 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003391
Sebastian Redl22653ba2011-08-30 19:58:05 +00003392 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003393 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003394 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003395 ParmVarDecl *Param = Constructor->getParamDecl(0);
3396 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003397
Anders Carlsson1b00e242010-04-23 03:10:23 +00003398 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003399 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003400 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003401 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003402 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003403
Eli Friedmanfa0df832012-02-02 03:46:19 +00003404 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3405
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003406 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003407 QualType ArgTy =
3408 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3409 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003410
Sebastian Redl22653ba2011-08-30 19:58:05 +00003411 if (Moving) {
3412 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3413 }
3414
John McCallcf142162010-08-07 06:22:56 +00003415 CXXCastPath BasePath;
3416 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003417 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3418 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003419 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003420 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003421
Anders Carlsson1b00e242010-04-23 03:10:23 +00003422 InitializationKind InitKind
3423 = InitializationKind::CreateDirect(Constructor->getLocation(),
3424 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003425 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3426 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003427 break;
3428 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003429 }
John McCallb268a282010-08-23 23:25:46 +00003430
Douglas Gregora40433a2010-12-07 00:41:46 +00003431 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003432 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003433 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003434
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003435 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003436 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003437 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3438 SourceLocation()),
3439 BaseSpec->isVirtual(),
3440 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003441 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003442 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003443 SourceLocation());
3444
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003445 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003446}
3447
Sebastian Redl22653ba2011-08-30 19:58:05 +00003448static bool RefersToRValueRef(Expr *MemRef) {
3449 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3450 return Referenced->getType()->isRValueReferenceType();
3451}
3452
Anders Carlsson3c1db572010-04-23 02:15:47 +00003453static bool
3454BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003455 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003456 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003457 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003458 if (Field->isInvalidDecl())
3459 return true;
3460
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003461 SourceLocation Loc = Constructor->getLocation();
3462
Sebastian Redl22653ba2011-08-30 19:58:05 +00003463 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3464 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003465 ParmVarDecl *Param = Constructor->getParamDecl(0);
3466 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003467
3468 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003469 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3470 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003471
Anders Carlsson423f5d82010-04-23 16:04:08 +00003472 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003473 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003474 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003475 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003476
Eli Friedmanfa0df832012-02-02 03:46:19 +00003477 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3478
Sebastian Redl22653ba2011-08-30 19:58:05 +00003479 if (Moving) {
3480 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3481 }
3482
Douglas Gregor94f9a482010-05-05 05:51:00 +00003483 // Build a reference to this field within the parameter.
3484 CXXScopeSpec SS;
3485 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3486 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003487 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3488 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003489 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003490 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003491 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003492 ParamType, Loc,
3493 /*IsArrow=*/false,
3494 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003495 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003496 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003497 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00003498 /*TemplateArgs=*/nullptr,
3499 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003500 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003501 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003502
3503 // C++11 [class.copy]p15:
3504 // - if a member m has rvalue reference type T&&, it is direct-initialized
3505 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003506 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003507 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003508 }
3509
Douglas Gregor94f9a482010-05-05 05:51:00 +00003510 // When the field we are copying is an array, create index variables for
3511 // each dimension of the array. We use these index variables to subscript
3512 // the source array, and other clients (e.g., CodeGen) will perform the
3513 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003514 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003515 QualType BaseType = Field->getType();
3516 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003517 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003518 while (const ConstantArrayType *Array
3519 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003520 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003521 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003522 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003523 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003524 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003525 llvm::raw_svector_ostream OS(Str);
3526 OS << "__i" << IndexVariables.size();
3527 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3528 }
3529 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003530 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003531 IterationVarName, SizeType,
3532 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003533 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003534 IndexVariables.push_back(IterationVar);
3535
3536 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003537 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003538 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003539 assert(!IterationVarRef.isInvalid() &&
3540 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003541 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003542 assert(!IterationVarRef.isInvalid() &&
3543 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003544
Douglas Gregor94f9a482010-05-05 05:51:00 +00003545 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003546 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3547 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003548 Loc);
3549 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003550 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003551
Douglas Gregor94f9a482010-05-05 05:51:00 +00003552 BaseType = Array->getElementType();
3553 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003554
3555 // The array subscript expression is an lvalue, which is wrong for moving.
3556 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003557 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003558
Douglas Gregor94f9a482010-05-05 05:51:00 +00003559 // Construct the entity that we will be initializing. For an array, this
3560 // will be first element in the array, which may require several levels
3561 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003562 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003563 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003564 if (Indirect)
3565 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3566 else
3567 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003568 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3569 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3570 0,
3571 Entities.back()));
3572
3573 // Direct-initialize to use the copy constructor.
3574 InitializationKind InitKind =
3575 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3576
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003577 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00003578 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3579 CtorArgE);
3580
John McCalldadc5752010-08-24 06:29:42 +00003581 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003582 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003583 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003584 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003585 if (MemberInit.isInvalid())
3586 return true;
3587
Douglas Gregor493627b2011-08-10 15:22:55 +00003588 if (Indirect) {
3589 assert(IndexVariables.size() == 0 &&
3590 "Indirect field improperly initialized");
3591 CXXMemberInit
3592 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3593 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003594 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003595 Loc);
3596 } else
3597 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003598 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003599 Loc,
3600 IndexVariables.data(),
3601 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003602 return false;
3603 }
3604
Richard Smithc2bc61b2013-03-18 21:12:30 +00003605 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3606 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003607
Anders Carlsson3c1db572010-04-23 02:15:47 +00003608 QualType FieldBaseElementType =
3609 SemaRef.Context.getBaseElementType(Field->getType());
3610
Anders Carlsson3c1db572010-04-23 02:15:47 +00003611 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003612 InitializedEntity InitEntity
3613 = Indirect? InitializedEntity::InitializeMember(Indirect)
3614 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003615 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003616 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003617
3618 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3619 ExprResult MemberInit =
3620 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003621
Douglas Gregora40433a2010-12-07 00:41:46 +00003622 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003623 if (MemberInit.isInvalid())
3624 return true;
3625
Douglas Gregor493627b2011-08-10 15:22:55 +00003626 if (Indirect)
3627 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3628 Indirect, Loc,
3629 Loc,
3630 MemberInit.get(),
3631 Loc);
3632 else
3633 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3634 Field, Loc, Loc,
3635 MemberInit.get(),
3636 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003637 return false;
3638 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003639
Alexis Hunt8b455182011-05-17 00:19:05 +00003640 if (!Field->getParent()->isUnion()) {
3641 if (FieldBaseElementType->isReferenceType()) {
3642 SemaRef.Diag(Constructor->getLocation(),
3643 diag::err_uninitialized_member_in_ctor)
3644 << (int)Constructor->isImplicit()
3645 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3646 << 0 << Field->getDeclName();
3647 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3648 return true;
3649 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003650
Alexis Hunt8b455182011-05-17 00:19:05 +00003651 if (FieldBaseElementType.isConstQualified()) {
3652 SemaRef.Diag(Constructor->getLocation(),
3653 diag::err_uninitialized_member_in_ctor)
3654 << (int)Constructor->isImplicit()
3655 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3656 << 1 << Field->getDeclName();
3657 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3658 return true;
3659 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003660 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003661
David Blaikiebbafb8a2012-03-11 07:00:24 +00003662 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003663 FieldBaseElementType->isObjCRetainableType() &&
3664 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3665 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003666 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003667 // Default-initialize Objective-C pointers to NULL.
3668 CXXMemberInit
3669 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3670 Loc, Loc,
3671 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3672 Loc);
3673 return false;
3674 }
3675
Anders Carlsson3c1db572010-04-23 02:15:47 +00003676 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003677 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003678 return false;
3679}
John McCallbc83b3f2010-05-20 23:23:51 +00003680
3681namespace {
3682struct BaseAndFieldInfo {
3683 Sema &S;
3684 CXXConstructorDecl *Ctor;
3685 bool AnyErrorsInInits;
3686 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003687 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003688 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003689 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003690
3691 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3692 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003693 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3694 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003695 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003696 else if (Generated && Ctor->isMoveConstructor())
3697 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003698 else if (Ctor->getInheritedConstructor())
3699 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003700 else
3701 IIK = IIK_Default;
3702 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003703
3704 bool isImplicitCopyOrMove() const {
3705 switch (IIK) {
3706 case IIK_Copy:
3707 case IIK_Move:
3708 return true;
3709
3710 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003711 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003712 return false;
3713 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003714
3715 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003716 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003717
3718 bool addFieldInitializer(CXXCtorInitializer *Init) {
3719 AllToInit.push_back(Init);
3720
3721 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003722 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003723 S.UnusedPrivateFields.remove(Init->getAnyMember());
3724
3725 return false;
3726 }
John McCallbc83b3f2010-05-20 23:23:51 +00003727
Richard Smithab44d5b2013-12-10 08:25:00 +00003728 bool isInactiveUnionMember(FieldDecl *Field) {
3729 RecordDecl *Record = Field->getParent();
3730 if (!Record->isUnion())
3731 return false;
3732
Richard Smith8d183852013-12-10 20:56:03 +00003733 if (FieldDecl *Active =
3734 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003735 return Active != Field->getCanonicalDecl();
3736
3737 // In an implicit copy or move constructor, ignore any in-class initializer.
3738 if (isImplicitCopyOrMove())
3739 return true;
3740
3741 // If there's no explicit initialization, the field is active only if it
3742 // has an in-class initializer...
3743 if (Field->hasInClassInitializer())
3744 return false;
3745 // ... or it's an anonymous struct or union whose class has an in-class
3746 // initializer.
3747 if (!Field->isAnonymousStructOrUnion())
3748 return true;
3749 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3750 return !FieldRD->hasInClassInitializer();
3751 }
3752
3753 /// \brief Determine whether the given field is, or is within, a union member
3754 /// that is inactive (because there was an initializer given for a different
3755 /// member of the union, or because the union was not initialized at all).
3756 bool isWithinInactiveUnionMember(FieldDecl *Field,
3757 IndirectFieldDecl *Indirect) {
3758 if (!Indirect)
3759 return isInactiveUnionMember(Field);
3760
Aaron Ballman29c94602014-03-07 18:36:15 +00003761 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003762 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003763 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003764 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003765 }
3766 return false;
3767 }
3768};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003769}
Richard Smithc94ec842011-09-19 13:34:43 +00003770
Douglas Gregor10f939c2011-11-02 23:04:16 +00003771/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3772/// array type.
3773static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3774 if (T->isIncompleteArrayType())
3775 return true;
3776
3777 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3778 if (!ArrayT->getSize())
3779 return true;
3780
3781 T = ArrayT->getElementType();
3782 }
3783
3784 return false;
3785}
3786
Richard Smith938f40b2011-06-11 17:19:42 +00003787static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003788 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003789 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003790 if (Field->isInvalidDecl())
3791 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003792
Chandler Carruth139e9622010-06-30 02:59:29 +00003793 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003794 if (CXXCtorInitializer *Init =
3795 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003796 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003797
Richard Smithab44d5b2013-12-10 08:25:00 +00003798 // C++11 [class.base.init]p8:
3799 // if the entity is a non-static data member that has a
3800 // brace-or-equal-initializer and either
3801 // -- the constructor's class is a union and no other variant member of that
3802 // union is designated by a mem-initializer-id or
3803 // -- the constructor's class is not a union, and, if the entity is a member
3804 // of an anonymous union, no other member of that union is designated by
3805 // a mem-initializer-id,
3806 // the entity is initialized as specified in [dcl.init].
3807 //
3808 // We also apply the same rules to handle anonymous structs within anonymous
3809 // unions.
3810 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3811 return false;
3812
Douglas Gregor7db3e952011-11-28 20:03:15 +00003813 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003814 ExprResult DIE =
3815 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3816 if (DIE.isInvalid())
3817 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003818 CXXCtorInitializer *Init;
3819 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003820 Init = new (SemaRef.Context)
3821 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3822 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003823 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003824 Init = new (SemaRef.Context)
3825 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3826 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003827 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003828 }
3829
Douglas Gregor10f939c2011-11-02 23:04:16 +00003830 // Don't initialize incomplete or zero-length arrays.
3831 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3832 return false;
3833
John McCallbc83b3f2010-05-20 23:23:51 +00003834 // Don't try to build an implicit initializer if there were semantic
3835 // errors in any of the initializers (and therefore we might be
3836 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003837 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003838 return false;
3839
Craig Topperc3ec1492014-05-26 06:22:03 +00003840 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003841 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3842 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003843 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003844
Richard Smith0a8cfc72012-08-07 21:30:42 +00003845 if (!Init)
3846 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003847
Richard Smith0a8cfc72012-08-07 21:30:42 +00003848 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003849}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003850
3851bool
3852Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3853 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003854 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003855 Constructor->setNumCtorInitializers(1);
3856 CXXCtorInitializer **initializer =
3857 new (Context) CXXCtorInitializer*[1];
3858 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3859 Constructor->setCtorInitializers(initializer);
3860
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003861 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003862 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003863 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3864 }
3865
Alexis Hunte2622992011-05-05 00:05:47 +00003866 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003867
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003868 DiagnoseUninitializedFields(*this, Constructor);
3869
Alexis Hunt61bc1732011-05-01 07:04:31 +00003870 return false;
3871}
Douglas Gregor493627b2011-08-10 15:22:55 +00003872
David Blaikie3fc2f912013-01-17 05:26:25 +00003873bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3874 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003875 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003876 // Just store the initializers as written, they will be checked during
3877 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003878 if (!Initializers.empty()) {
3879 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003880 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003881 new (Context) CXXCtorInitializer*[Initializers.size()];
3882 memcpy(baseOrMemberInitializers, Initializers.data(),
3883 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003884 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003885 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003886
3887 // Let template instantiation know whether we had errors.
3888 if (AnyErrors)
3889 Constructor->setInvalidDecl();
3890
Anders Carlssondb0a9652010-04-02 06:26:44 +00003891 return false;
3892 }
3893
John McCallbc83b3f2010-05-20 23:23:51 +00003894 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003895
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003896 // We need to build the initializer AST according to order of construction
3897 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003898 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003899 if (!ClassDecl)
3900 return true;
3901
Eli Friedman9cf6b592009-11-09 19:20:36 +00003902 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003903
David Blaikie3fc2f912013-01-17 05:26:25 +00003904 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003905 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003906
Anders Carlssondb0a9652010-04-02 06:26:44 +00003907 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003908 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003909 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003910 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003911
3912 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003913 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003914 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003915 if (FD && FD->getParent()->isUnion())
3916 Info.ActiveUnionMember.insert(std::make_pair(
3917 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3918 }
3919 } else if (FieldDecl *FD = Member->getMember()) {
3920 if (FD->getParent()->isUnion())
3921 Info.ActiveUnionMember.insert(std::make_pair(
3922 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3923 }
3924 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003925 }
3926
Anders Carlsson43c64af2010-04-21 19:52:01 +00003927 // Keep track of the direct virtual bases.
3928 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003929 for (auto &I : ClassDecl->bases()) {
3930 if (I.isVirtual())
3931 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003932 }
3933
Anders Carlssondb0a9652010-04-02 06:26:44 +00003934 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003935 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003936 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003937 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003938 // [class.base.init]p7, per DR257:
3939 // A mem-initializer where the mem-initializer-id names a virtual base
3940 // class is ignored during execution of a constructor of any class that
3941 // is not the most derived class.
3942 if (ClassDecl->isAbstract()) {
3943 // FIXME: Provide a fixit to remove the base specifier. This requires
3944 // tracking the location of the associated comma for a base specifier.
3945 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003946 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003947 DiagnoseAbstractType(ClassDecl);
3948 }
3949
John McCallbc83b3f2010-05-20 23:23:51 +00003950 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003951 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3952 // [class.base.init]p8, per DR257:
3953 // If a given [...] base class is not named by a mem-initializer-id
3954 // [...] and the entity is not a virtual base class of an abstract
3955 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003956 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003957 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003958 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003959 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003960 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003961 HadError = true;
3962 continue;
3963 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003964
John McCallbc83b3f2010-05-20 23:23:51 +00003965 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003966 }
3967 }
Mike Stump11289f42009-09-09 15:08:12 +00003968
John McCallbc83b3f2010-05-20 23:23:51 +00003969 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003970 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003971 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003972 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003973 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003974
Alexis Hunt1d792652011-01-08 20:30:50 +00003975 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003976 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003977 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003978 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003979 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003981 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003982 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003983 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003984 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003985 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003986
John McCallbc83b3f2010-05-20 23:23:51 +00003987 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003988 }
3989 }
Mike Stump11289f42009-09-09 15:08:12 +00003990
John McCallbc83b3f2010-05-20 23:23:51 +00003991 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003992 for (auto *Mem : ClassDecl->decls()) {
3993 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003994 // C++ [class.bit]p2:
3995 // A declaration for a bit-field that omits the identifier declares an
3996 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3997 // initialized.
3998 if (F->isUnnamedBitfield())
3999 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004000
Sebastian Redl22653ba2011-08-30 19:58:05 +00004001 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004002 // handle anonymous struct/union fields based on their individual
4003 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004004 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004005 continue;
4006
4007 if (CollectFieldInitializer(*this, Info, F))
4008 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004009 continue;
4010 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004011
4012 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004013 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004014 continue;
4015
Aaron Ballman629afae2014-03-07 19:56:05 +00004016 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004017 if (F->getType()->isIncompleteArrayType()) {
4018 assert(ClassDecl->hasFlexibleArrayMember() &&
4019 "Incomplete array type is not valid");
4020 continue;
4021 }
4022
Douglas Gregor493627b2011-08-10 15:22:55 +00004023 // Initialize each field of an anonymous struct individually.
4024 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4025 HadError = true;
4026
4027 continue;
4028 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004029 }
Mike Stump11289f42009-09-09 15:08:12 +00004030
David Blaikie3fc2f912013-01-17 05:26:25 +00004031 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004032 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004033 Constructor->setNumCtorInitializers(NumInitializers);
4034 CXXCtorInitializer **baseOrMemberInitializers =
4035 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004036 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004037 NumInitializers * sizeof(CXXCtorInitializer*));
4038 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004039
John McCalla6309952010-03-16 21:39:52 +00004040 // Constructors implicitly reference the base and member
4041 // destructors.
4042 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4043 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004044 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004045
4046 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004047}
4048
David Blaikieb61b8152013-01-17 08:49:22 +00004049static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004050 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004051 const RecordDecl *RD = RT->getDecl();
4052 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004053 for (auto *Field : RD->fields())
4054 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004055 return;
4056 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004057 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004058 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004059}
4060
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004061static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4062 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004063}
4064
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004065static const void *GetKeyForMember(ASTContext &Context,
4066 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004067 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004068 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004069
Richard Smithcd45dbc2014-04-19 03:48:30 +00004070 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004071}
4072
David Blaikie3fc2f912013-01-17 05:26:25 +00004073static void DiagnoseBaseOrMemInitializerOrder(
4074 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4075 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004076 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004077 return;
Mike Stump11289f42009-09-09 15:08:12 +00004078
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004079 // Don't check initializers order unless the warning is enabled at the
4080 // location of at least one initializer.
4081 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004082 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004083 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004084 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4085 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004086 ShouldCheckOrder = true;
4087 break;
4088 }
4089 }
4090 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004091 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004092
John McCallbb7b6582010-04-10 07:37:23 +00004093 // Build the list of bases and members in the order that they'll
4094 // actually be initialized. The explicit initializers should be in
4095 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004096 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004097
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004098 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4099
John McCallbb7b6582010-04-10 07:37:23 +00004100 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004101 for (const auto &VBase : ClassDecl->vbases())
4102 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004103
John McCallbb7b6582010-04-10 07:37:23 +00004104 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004105 for (const auto &Base : ClassDecl->bases()) {
4106 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004107 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004108 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004109 }
Mike Stump11289f42009-09-09 15:08:12 +00004110
John McCallbb7b6582010-04-10 07:37:23 +00004111 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004112 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004113 if (Field->isUnnamedBitfield())
4114 continue;
4115
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004116 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004117 }
4118
John McCallbb7b6582010-04-10 07:37:23 +00004119 unsigned NumIdealInits = IdealInitKeys.size();
4120 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004121
Craig Topperc3ec1492014-05-26 06:22:03 +00004122 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004123 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004124 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004125 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004126
4127 // Scan forward to try to find this initializer in the idealized
4128 // initializers list.
4129 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4130 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004131 break;
John McCallbb7b6582010-04-10 07:37:23 +00004132
4133 // If we didn't find this initializer, it must be because we
4134 // scanned past it on a previous iteration. That can only
4135 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004136 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004137 Sema::SemaDiagnosticBuilder D =
4138 SemaRef.Diag(PrevInit->getSourceLocation(),
4139 diag::warn_initializer_out_of_order);
4140
Francois Pichetd583da02010-12-04 09:14:42 +00004141 if (PrevInit->isAnyMemberInitializer())
4142 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004143 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004144 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004145
Francois Pichetd583da02010-12-04 09:14:42 +00004146 if (Init->isAnyMemberInitializer())
4147 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004148 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004149 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004150
4151 // Move back to the initializer's location in the ideal list.
4152 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4153 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004154 break;
John McCallbb7b6582010-04-10 07:37:23 +00004155
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004156 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004157 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004158 }
John McCallbb7b6582010-04-10 07:37:23 +00004159
4160 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004161 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004162}
4163
John McCall23eebd92010-04-10 09:28:51 +00004164namespace {
4165bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004166 CXXCtorInitializer *Init,
4167 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004168 if (!PrevInit) {
4169 PrevInit = Init;
4170 return false;
4171 }
4172
Douglas Gregorea306a12013-03-25 23:28:23 +00004173 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004174 S.Diag(Init->getSourceLocation(),
4175 diag::err_multiple_mem_initialization)
4176 << Field->getDeclName()
4177 << Init->getSourceRange();
4178 else {
John McCall424cec92011-01-19 06:33:43 +00004179 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004180 assert(BaseClass && "neither field nor base");
4181 S.Diag(Init->getSourceLocation(),
4182 diag::err_multiple_base_initialization)
4183 << QualType(BaseClass, 0)
4184 << Init->getSourceRange();
4185 }
4186 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4187 << 0 << PrevInit->getSourceRange();
4188
4189 return true;
4190}
4191
Alexis Hunt1d792652011-01-08 20:30:50 +00004192typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004193typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4194
4195bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004196 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004197 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004198 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004199 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004200 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004201
4202 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004203 if (Parent->isUnion()) {
4204 UnionEntry &En = Unions[Parent];
4205 if (En.first && En.first != Child) {
4206 S.Diag(Init->getSourceLocation(),
4207 diag::err_multiple_mem_union_initialization)
4208 << Field->getDeclName()
4209 << Init->getSourceRange();
4210 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4211 << 0 << En.second->getSourceRange();
4212 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004213 }
4214 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004215 En.first = Child;
4216 En.second = Init;
4217 }
David Blaikie0f65d592011-11-17 06:01:57 +00004218 if (!Parent->isAnonymousStructOrUnion())
4219 return false;
John McCall23eebd92010-04-10 09:28:51 +00004220 }
4221
4222 Child = Parent;
4223 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004224 }
John McCall23eebd92010-04-10 09:28:51 +00004225
4226 return false;
4227}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004228}
John McCall23eebd92010-04-10 09:28:51 +00004229
Anders Carlssone857b292010-04-02 03:37:03 +00004230/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004231void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004232 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004233 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004234 bool AnyErrors) {
4235 if (!ConstructorDecl)
4236 return;
4237
4238 AdjustDeclIfTemplate(ConstructorDecl);
4239
4240 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004241 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004242
4243 if (!Constructor) {
4244 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4245 return;
4246 }
4247
John McCall23eebd92010-04-10 09:28:51 +00004248 // Mapping for the duplicate initializers check.
4249 // For member initializers, this is keyed with a FieldDecl*.
4250 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004251 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004252
4253 // Mapping for the inconsistent anonymous-union initializers check.
4254 RedundantUnionMap MemberUnions;
4255
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004256 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004257 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004258 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004259
Abramo Bagnara341d7832010-05-26 18:09:23 +00004260 // Set the source order index.
4261 Init->setSourceOrder(i);
4262
Francois Pichetd583da02010-12-04 09:14:42 +00004263 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004264 const void *Key = GetKeyForMember(Context, Init);
4265 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004266 CheckRedundantUnionInit(*this, Init, MemberUnions))
4267 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004268 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004269 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004270 if (CheckRedundantInit(*this, Init, Members[Key]))
4271 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004272 } else {
4273 assert(Init->isDelegatingInitializer());
4274 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004275 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004276 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004277 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004278 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004279 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004280 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004281 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004282 // Return immediately as the initializer is set.
4283 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004284 }
Anders Carlssone857b292010-04-02 03:37:03 +00004285 }
4286
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004287 if (HadError)
4288 return;
4289
David Blaikie3fc2f912013-01-17 05:26:25 +00004290 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004291
David Blaikie3fc2f912013-01-17 05:26:25 +00004292 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004293
Richard Trieuef64e942013-10-25 00:56:00 +00004294 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004295}
4296
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004297void
John McCalla6309952010-03-16 21:39:52 +00004298Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4299 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004300 // Ignore dependent contexts. Also ignore unions, since their members never
4301 // have destructors implicitly called.
4302 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004303 return;
John McCall1064d7e2010-03-16 05:22:47 +00004304
4305 // FIXME: all the access-control diagnostics are positioned on the
4306 // field/base declaration. That's probably good; that said, the
4307 // user might reasonably want to know why the destructor is being
4308 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004309
Anders Carlssondee9a302009-11-17 04:44:12 +00004310 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004311 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004312 if (Field->isInvalidDecl())
4313 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004314
4315 // Don't destroy incomplete or zero-length arrays.
4316 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4317 continue;
4318
Anders Carlssondee9a302009-11-17 04:44:12 +00004319 QualType FieldType = Context.getBaseElementType(Field->getType());
4320
4321 const RecordType* RT = FieldType->getAs<RecordType>();
4322 if (!RT)
4323 continue;
4324
4325 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004326 if (FieldClassDecl->isInvalidDecl())
4327 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004328 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004329 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004330 // The destructor for an implicit anonymous union member is never invoked.
4331 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4332 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004333
Douglas Gregore71edda2010-07-01 22:47:18 +00004334 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004335 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004336 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004337 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004338 << Field->getDeclName()
4339 << FieldType);
4340
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004341 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004342 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004343 }
4344
John McCall1064d7e2010-03-16 05:22:47 +00004345 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4346
Anders Carlssondee9a302009-11-17 04:44:12 +00004347 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004348 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004349 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004350 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004351
4352 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004353 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004354 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004355
John McCall1064d7e2010-03-16 05:22:47 +00004356 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004357 // If our base class is invalid, we probably can't get its dtor anyway.
4358 if (BaseClassDecl->isInvalidDecl())
4359 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004360 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004361 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004362
Douglas Gregore71edda2010-07-01 22:47:18 +00004363 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004364 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004365
4366 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004367 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004368 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004369 << Base.getType()
4370 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004371 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004372
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004373 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004374 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004375 }
4376
4377 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004378 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004379 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004380 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004381
4382 // Ignore direct virtual bases.
4383 if (DirectVirtualBases.count(RT))
4384 continue;
4385
John McCall1064d7e2010-03-16 05:22:47 +00004386 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004387 // If our base class is invalid, we probably can't get its dtor anyway.
4388 if (BaseClassDecl->isInvalidDecl())
4389 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004390 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004391 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004392
Douglas Gregore71edda2010-07-01 22:47:18 +00004393 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004394 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004395 if (CheckDestructorAccess(
4396 ClassDecl->getLocation(), Dtor,
4397 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004398 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004399 Context.getTypeDeclType(ClassDecl)) ==
4400 AR_accessible) {
4401 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004402 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004403 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004404 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004405 }
John McCall1064d7e2010-03-16 05:22:47 +00004406
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004407 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004408 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004409 }
4410}
4411
John McCall48871652010-08-21 09:40:31 +00004412void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004413 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004414 return;
Mike Stump11289f42009-09-09 15:08:12 +00004415
Mike Stump11289f42009-09-09 15:08:12 +00004416 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004417 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004418 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004419 DiagnoseUninitializedFields(*this, Constructor);
4420 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004421}
4422
Mike Stump11289f42009-09-09 15:08:12 +00004423bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004424 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004425 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4426 unsigned DiagID;
4427 AbstractDiagSelID SelID;
4428
4429 public:
4430 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4431 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004432
Craig Toppera798a9d2014-03-02 09:32:10 +00004433 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004434 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004435 if (SelID == -1)
4436 S.Diag(Loc, DiagID) << T;
4437 else
4438 S.Diag(Loc, DiagID) << SelID << T;
4439 }
4440 } Diagnoser(DiagID, SelID);
4441
4442 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004443}
4444
Anders Carlssoneabf7702009-08-27 00:13:57 +00004445bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004446 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004447 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004448 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004449
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004450 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004451 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004452
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004453 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004454 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004455 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004456 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004457
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004458 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004459 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004460 }
Mike Stump11289f42009-09-09 15:08:12 +00004461
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004462 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004463 if (!RT)
4464 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004465
John McCall67da35c2010-02-04 22:26:26 +00004466 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004467
John McCall02db245d2010-08-18 09:41:07 +00004468 // We can't answer whether something is abstract until it has a
4469 // definition. If it's currently being defined, we'll walk back
4470 // over all the declarations when we have a full definition.
4471 const CXXRecordDecl *Def = RD->getDefinition();
4472 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004473 return false;
4474
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004475 if (!RD->isAbstract())
4476 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004477
Douglas Gregorae298422012-05-04 17:09:59 +00004478 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004479 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004480
John McCall02db245d2010-08-18 09:41:07 +00004481 return true;
4482}
4483
4484void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4485 // Check if we've already emitted the list of pure virtual functions
4486 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004487 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004488 return;
Mike Stump11289f42009-09-09 15:08:12 +00004489
Richard Smithbc46e432013-07-22 02:56:56 +00004490 // If the diagnostic is suppressed, don't emit the notes. We're only
4491 // going to emit them once, so try to attach them to a diagnostic we're
4492 // actually going to show.
4493 if (Diags.isLastDiagnosticIgnored())
4494 return;
4495
Douglas Gregor4165bd62010-03-23 23:47:56 +00004496 CXXFinalOverriderMap FinalOverriders;
4497 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004498
Anders Carlssona2f74f32010-06-03 01:00:02 +00004499 // Keep a set of seen pure methods so we won't diagnose the same method
4500 // more than once.
4501 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4502
Douglas Gregor4165bd62010-03-23 23:47:56 +00004503 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4504 MEnd = FinalOverriders.end();
4505 M != MEnd;
4506 ++M) {
4507 for (OverridingMethods::iterator SO = M->second.begin(),
4508 SOEnd = M->second.end();
4509 SO != SOEnd; ++SO) {
4510 // C++ [class.abstract]p4:
4511 // A class is abstract if it contains or inherits at least one
4512 // pure virtual function for which the final overrider is pure
4513 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004514
Douglas Gregor4165bd62010-03-23 23:47:56 +00004515 //
4516 if (SO->second.size() != 1)
4517 continue;
4518
4519 if (!SO->second.front().Method->isPure())
4520 continue;
4521
David Blaikie82e95a32014-11-19 07:49:47 +00004522 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004523 continue;
4524
Douglas Gregor4165bd62010-03-23 23:47:56 +00004525 Diag(SO->second.front().Method->getLocation(),
4526 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004527 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004528 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004529 }
4530
4531 if (!PureVirtualClassDiagSet)
4532 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4533 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004534}
4535
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004536namespace {
John McCall02db245d2010-08-18 09:41:07 +00004537struct AbstractUsageInfo {
4538 Sema &S;
4539 CXXRecordDecl *Record;
4540 CanQualType AbstractType;
4541 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004542
John McCall02db245d2010-08-18 09:41:07 +00004543 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4544 : S(S), Record(Record),
4545 AbstractType(S.Context.getCanonicalType(
4546 S.Context.getTypeDeclType(Record))),
4547 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004548
John McCall02db245d2010-08-18 09:41:07 +00004549 void DiagnoseAbstractType() {
4550 if (Invalid) return;
4551 S.DiagnoseAbstractType(Record);
4552 Invalid = true;
4553 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004554
John McCall02db245d2010-08-18 09:41:07 +00004555 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4556};
4557
4558struct CheckAbstractUsage {
4559 AbstractUsageInfo &Info;
4560 const NamedDecl *Ctx;
4561
4562 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4563 : Info(Info), Ctx(Ctx) {}
4564
4565 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4566 switch (TL.getTypeLocClass()) {
4567#define ABSTRACT_TYPELOC(CLASS, PARENT)
4568#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004569 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004570#include "clang/AST/TypeLocNodes.def"
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 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004575 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004576 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4577 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004578 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004579
4580 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004581 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004582 }
John McCall02db245d2010-08-18 09:41:07 +00004583 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004584
John McCall02db245d2010-08-18 09:41:07 +00004585 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4586 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4587 }
Mike Stump11289f42009-09-09 15:08:12 +00004588
John McCall02db245d2010-08-18 09:41:07 +00004589 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4590 // Visit the type parameters from a permissive context.
4591 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4592 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4593 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4594 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4595 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4596 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004597 }
John McCall02db245d2010-08-18 09:41:07 +00004598 }
Mike Stump11289f42009-09-09 15:08:12 +00004599
John McCall02db245d2010-08-18 09:41:07 +00004600 // Visit pointee types from a permissive context.
4601#define CheckPolymorphic(Type) \
4602 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4603 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4604 }
4605 CheckPolymorphic(PointerTypeLoc)
4606 CheckPolymorphic(ReferenceTypeLoc)
4607 CheckPolymorphic(MemberPointerTypeLoc)
4608 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004609 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004610
John McCall02db245d2010-08-18 09:41:07 +00004611 /// Handle all the types we haven't given a more specific
4612 /// implementation for above.
4613 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4614 // Every other kind of type that we haven't called out already
4615 // that has an inner type is either (1) sugar or (2) contains that
4616 // inner type in some way as a subobject.
4617 if (TypeLoc Next = TL.getNextTypeLoc())
4618 return Visit(Next, Sel);
4619
4620 // If there's no inner type and we're in a permissive context,
4621 // don't diagnose.
4622 if (Sel == Sema::AbstractNone) return;
4623
4624 // Check whether the type matches the abstract type.
4625 QualType T = TL.getType();
4626 if (T->isArrayType()) {
4627 Sel = Sema::AbstractArrayType;
4628 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004629 }
John McCall02db245d2010-08-18 09:41:07 +00004630 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4631 if (CT != Info.AbstractType) return;
4632
4633 // It matched; do some magic.
4634 if (Sel == Sema::AbstractArrayType) {
4635 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4636 << T << TL.getSourceRange();
4637 } else {
4638 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4639 << Sel << T << TL.getSourceRange();
4640 }
4641 Info.DiagnoseAbstractType();
4642 }
4643};
4644
4645void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4646 Sema::AbstractDiagSelID Sel) {
4647 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4648}
4649
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004650}
John McCall02db245d2010-08-18 09:41:07 +00004651
4652/// Check for invalid uses of an abstract type in a method declaration.
4653static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4654 CXXMethodDecl *MD) {
4655 // No need to do the check on definitions, which require that
4656 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004657 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004658 return;
4659
4660 // For safety's sake, just ignore it if we don't have type source
4661 // information. This should never happen for non-implicit methods,
4662 // but...
4663 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4664 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4665}
4666
4667/// Check for invalid uses of an abstract type within a class definition.
4668static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4669 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004670 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004671 if (D->isImplicit()) continue;
4672
4673 // Methods and method templates.
4674 if (isa<CXXMethodDecl>(D)) {
4675 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4676 } else if (isa<FunctionTemplateDecl>(D)) {
4677 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4678 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4679
4680 // Fields and static variables.
4681 } else if (isa<FieldDecl>(D)) {
4682 FieldDecl *FD = cast<FieldDecl>(D);
4683 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4684 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4685 } else if (isa<VarDecl>(D)) {
4686 VarDecl *VD = cast<VarDecl>(D);
4687 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4688 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4689
4690 // Nested classes and class templates.
4691 } else if (isa<CXXRecordDecl>(D)) {
4692 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4693 } else if (isa<ClassTemplateDecl>(D)) {
4694 CheckAbstractClassUsage(Info,
4695 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4696 }
4697 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004698}
4699
Hans Wennborg99000c22015-08-15 01:18:16 +00004700static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4701 Attr *ClassAttr = getDLLAttr(Class);
4702 if (!ClassAttr)
4703 return;
4704
4705 assert(ClassAttr->getKind() == attr::DLLExport);
4706
4707 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4708
4709 if (TSK == TSK_ExplicitInstantiationDeclaration)
4710 // Don't go any further if this is just an explicit instantiation
4711 // declaration.
4712 return;
4713
4714 for (Decl *Member : Class->decls()) {
4715 auto *MD = dyn_cast<CXXMethodDecl>(Member);
4716 if (!MD)
4717 continue;
4718
4719 if (Member->getAttr<DLLExportAttr>()) {
4720 if (MD->isUserProvided()) {
4721 // Instantiate non-default class member functions ...
4722
4723 // .. except for certain kinds of template specializations.
4724 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4725 continue;
4726
4727 S.MarkFunctionReferenced(Class->getLocation(), MD);
4728
4729 // The function will be passed to the consumer when its definition is
4730 // encountered.
4731 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4732 MD->isCopyAssignmentOperator() ||
4733 MD->isMoveAssignmentOperator()) {
4734 // Synthesize and instantiate non-trivial implicit methods, explicitly
4735 // defaulted methods, and the copy and move assignment operators. The
4736 // latter are exported even if they are trivial, because the address of
4737 // an operator can be taken and should compare equal accross libraries.
4738 DiagnosticErrorTrap Trap(S.Diags);
4739 S.MarkFunctionReferenced(Class->getLocation(), MD);
4740 if (Trap.hasErrorOccurred()) {
4741 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4742 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4743 break;
4744 }
4745
4746 // There is no later point when we will see the definition of this
4747 // function, so pass it to the consumer now.
4748 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4749 }
4750 }
4751 }
4752}
4753
Hans Wennborg853ae942014-05-30 16:59:42 +00004754/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004755void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004756 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004757
4758 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004759 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00004760 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4761 if (Attr *TemplateAttr =
4762 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004763 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00004764 A->setInherited(true);
4765 ClassAttr = A;
4766 }
4767 }
4768 }
4769
Hans Wennborg853ae942014-05-30 16:59:42 +00004770 if (!ClassAttr)
4771 return;
4772
Hans Wennborg8313c762014-11-03 16:09:16 +00004773 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004774 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00004775 << Class << ClassAttr;
4776 return;
4777 }
4778
Hans Wennborg17f9b442015-05-27 00:06:45 +00004779 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004780 !ClassAttr->isInherited()) {
4781 // Diagnose dll attributes on members of class with dll attribute.
4782 for (Decl *Member : Class->decls()) {
4783 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4784 continue;
4785 InheritableAttr *MemberAttr = getDLLAttr(Member);
4786 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4787 continue;
4788
Hans Wennborg17f9b442015-05-27 00:06:45 +00004789 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004790 diag::err_attribute_dll_member_of_dll_class)
4791 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00004792 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004793 Member->setInvalidDecl();
4794 }
4795 }
4796
4797 if (Class->getDescribedClassTemplate())
4798 // Don't inherit dll attribute until the template is instantiated.
4799 return;
4800
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004801 // The class is either imported or exported.
4802 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4803 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004804
Hans Wennborgfd76d912015-01-15 21:18:30 +00004805 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4806
Hans Wennborgbb1983c2015-06-09 00:39:03 +00004807 // Ignore explicit dllexport on explicit class template instantiation declarations.
4808 if (ClassExported && !ClassAttr->isInherited() &&
4809 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00004810 Class->dropAttr<DLLExportAttr>();
4811 return;
4812 }
4813
Hans Wennborg853ae942014-05-30 16:59:42 +00004814 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004815 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00004816
4817 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4818 // seem to be true in practice?
4819
Hans Wennborg853ae942014-05-30 16:59:42 +00004820 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004821 VarDecl *VD = dyn_cast<VarDecl>(Member);
4822 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4823
4824 // Only methods and static fields inherit the attributes.
4825 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004826 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004827
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004828 if (MD) {
4829 // Don't process deleted methods.
4830 if (MD->isDeleted())
4831 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004832
David Majnemer30f058a2015-05-11 03:00:22 +00004833 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00004834 // MinGW does not import or export inline methods.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004835 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemer30f058a2015-05-11 03:00:22 +00004836 continue;
4837
4838 // MSVC versions before 2015 don't export the move assignment operators,
4839 // so don't attempt to import them if we have a definition.
4840 if (ClassImported && MD->isMoveAssignmentOperator() &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00004841 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00004842 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004843 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004844 }
4845
Hans Wennborg287231c2015-04-22 04:05:17 +00004846 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4847 continue;
4848
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004849 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004850 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00004851 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00004852 NewAttr->setInherited(true);
4853 Member->addAttr(NewAttr);
4854 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004855 }
Hans Wennborg99000c22015-08-15 01:18:16 +00004856
4857 if (ClassExported)
4858 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00004859}
4860
Hans Wennborgfce87ca2015-06-09 00:39:09 +00004861/// \brief Perform propagation of DLL attributes from a derived class to a
4862/// templated base class for MS compatibility.
4863void Sema::propagateDLLAttrToBaseClassTemplate(
4864 CXXRecordDecl *Class, Attr *ClassAttr,
4865 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4866 if (getDLLAttr(
4867 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4868 // If the base class template has a DLL attribute, don't try to change it.
4869 return;
4870 }
4871
4872 auto TSK = BaseTemplateSpec->getSpecializationKind();
4873 if (!getDLLAttr(BaseTemplateSpec) &&
4874 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4875 TSK == TSK_ImplicitInstantiation)) {
4876 // The template hasn't been instantiated yet (or it has, but only as an
4877 // explicit instantiation declaration or implicit instantiation, which means
4878 // we haven't codegenned any members yet), so propagate the attribute.
4879 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4880 NewAttr->setInherited(true);
4881 BaseTemplateSpec->addAttr(NewAttr);
4882
4883 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4884 // needs to be run again to work see the new attribute. Otherwise this will
4885 // get run whenever the template is instantiated.
4886 if (TSK != TSK_Undeclared)
4887 checkClassLevelDLLAttribute(BaseTemplateSpec);
4888
4889 return;
4890 }
4891
4892 if (getDLLAttr(BaseTemplateSpec)) {
4893 // The template has already been specialized or instantiated with an
4894 // attribute, explicitly or through propagation. We should not try to change
4895 // it.
4896 return;
4897 }
4898
4899 // The template was previously instantiated or explicitly specialized without
4900 // a dll attribute, It's too late for us to add an attribute, so warn that
4901 // this is unsupported.
4902 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4903 << BaseTemplateSpec->isExplicitSpecialization();
4904 Diag(ClassAttr->getLocation(), diag::note_attribute);
4905 if (BaseTemplateSpec->isExplicitSpecialization()) {
4906 Diag(BaseTemplateSpec->getLocation(),
4907 diag::note_template_class_explicit_specialization_was_here)
4908 << BaseTemplateSpec;
4909 } else {
4910 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4911 diag::note_template_class_instantiation_was_here)
4912 << BaseTemplateSpec;
4913 }
4914}
4915
Douglas Gregorc99f1552009-12-03 18:33:45 +00004916/// \brief Perform semantic checks on a class definition that has been
4917/// completing, introducing implicitly-declared members, checking for
4918/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004919void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004920 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004921 return;
4922
John McCall02db245d2010-08-18 09:41:07 +00004923 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4924 AbstractUsageInfo Info(*this, Record);
4925 CheckAbstractClassUsage(Info, Record);
4926 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004927
4928 // If this is not an aggregate type and has no user-declared constructor,
4929 // complain about any non-static data members of reference or const scalar
4930 // type, since they will never get initializers.
4931 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004932 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4933 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004934 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004935 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004936 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004937 continue;
4938
Douglas Gregor454a5b62010-04-15 00:00:53 +00004939 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004940 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004941 if (!Complained) {
4942 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4943 << Record->getTagKind() << Record;
4944 Complained = true;
4945 }
4946
4947 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4948 << F->getType()->isReferenceType()
4949 << F->getDeclName();
4950 }
4951 }
4952 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004953
Douglas Gregor36c22a22010-10-15 13:21:21 +00004954 if (Record->getIdentifier()) {
4955 // C++ [class.mem]p13:
4956 // If T is the name of a class, then each of the following shall have a
4957 // name different from T:
4958 // - every member of every anonymous union that is a member of class T.
4959 //
4960 // C++ [class.mem]p14:
4961 // In addition, if class T has a user-declared constructor (12.1), every
4962 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004963 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4964 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4965 ++I) {
4966 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004967 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4968 isa<IndirectFieldDecl>(D)) {
4969 Diag(D->getLocation(), diag::err_member_name_of_class)
4970 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004971 break;
4972 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004973 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004974 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004975
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004976 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004977 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004978 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004979 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4980 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004981 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4982 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4983 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004984
David Majnemera5433082013-10-18 00:33:31 +00004985 if (Record->isAbstract()) {
4986 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4987 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4988 << FA->isSpelledAsSealed();
4989 DiagnoseAbstractType(Record);
4990 }
David Blaikie348df502012-09-21 03:21:07 +00004991 }
4992
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004993 bool HasMethodWithOverrideControl = false,
4994 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004995 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004996 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004997 // See if a method overloads virtual methods in a base
4998 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004999 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005000 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005001 if (M->hasAttr<OverrideAttr>())
5002 HasMethodWithOverrideControl = true;
5003 else if (M->size_overridden_methods() > 0)
5004 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005005 // Check whether the explicitly-defaulted special members are valid.
5006 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005007 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005008
5009 // For an explicitly defaulted or deleted special member, we defer
5010 // determining triviality until the class is complete. That time is now!
5011 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005012 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005013 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005014 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005015
5016 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005017 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005018 }
5019 }
5020 }
5021 }
5022
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005023 if (HasMethodWithOverrideControl &&
5024 HasOverridingMethodWithoutOverrideControl) {
5025 // At least one method has the 'override' control declared.
5026 // Diagnose all other overridden methods which do not have 'override' specified on them.
5027 for (auto *M : Record->methods())
5028 DiagnoseAbsenceOfOverrideControl(M);
5029 }
Sebastian Redl08905022011-02-05 19:23:19 +00005030
John McCall95833f32014-02-27 20:30:49 +00005031 // ms_struct is a request to use the same ABI rules as MSVC. Check
5032 // whether this class uses any C++ features that are implemented
5033 // completely differently in MSVC, and if so, emit a diagnostic.
5034 // That diagnostic defaults to an error, but we allow projects to
5035 // map it down to a warning (or ignore it). It's a fairly common
5036 // practice among users of the ms_struct pragma to mass-annotate
5037 // headers, sweeping up a bunch of types that the project doesn't
5038 // really rely on MSVC-compatible layout for. We must therefore
5039 // support "ms_struct except for C++ stuff" as a secondary ABI.
5040 if (Record->isMsStruct(Context) &&
5041 (Record->isPolymorphic() || Record->getNumBases())) {
5042 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005043 }
5044
Richard Smithc2bc61b2013-03-18 21:12:30 +00005045 // Declare inheriting constructors. We do this eagerly here because:
5046 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00005047 // constructors from different classes.
5048 // - The lazy declaration of the other implicit constructors is so as to not
5049 // waste space and performance on classes that are not meant to be
5050 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00005051 // have inheriting constructors.
5052 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00005053
Hans Wennborg17f9b442015-05-27 00:06:45 +00005054 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005055}
5056
Richard Smith41c35d62013-11-27 03:39:20 +00005057/// Look up the special member function that would be called by a special
5058/// member function for a subobject of class type.
5059///
5060/// \param Class The class type of the subobject.
5061/// \param CSM The kind of special member function.
5062/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5063/// \param ConstRHS True if this is a copy operation with a const object
5064/// on its RHS, that is, if the argument to the outer special member
5065/// function is 'const' and this is not a field marked 'mutable'.
5066static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5067 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5068 unsigned FieldQuals, bool ConstRHS) {
5069 unsigned LHSQuals = 0;
5070 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5071 LHSQuals = FieldQuals;
5072
5073 unsigned RHSQuals = FieldQuals;
5074 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5075 RHSQuals = 0;
5076 else if (ConstRHS)
5077 RHSQuals |= Qualifiers::Const;
5078
5079 return S.LookupSpecialMember(Class, CSM,
5080 RHSQuals & Qualifiers::Const,
5081 RHSQuals & Qualifiers::Volatile,
5082 false,
5083 LHSQuals & Qualifiers::Const,
5084 LHSQuals & Qualifiers::Volatile);
5085}
5086
Richard Smithb5800092012-06-10 05:43:50 +00005087/// Is the special member function which would be selected to perform the
5088/// specified operation on the specified class type a constexpr constructor?
5089static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5090 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005091 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005092 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005093 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005094 if (!SMOR || !SMOR->getMethod())
5095 // A constructor we wouldn't select can't be "involved in initializing"
5096 // anything.
5097 return true;
5098 return SMOR->getMethod()->isConstexpr();
5099}
5100
5101/// Determine whether the specified special member function would be constexpr
5102/// if it were implicitly defined.
5103static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5104 Sema::CXXSpecialMember CSM,
5105 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005106 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005107 return false;
5108
5109 // C++11 [dcl.constexpr]p4:
5110 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005111 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005112 switch (CSM) {
5113 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005114 // Since default constructor lookup is essentially trivial (and cannot
5115 // involve, for instance, template instantiation), we compute whether a
5116 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5117 //
5118 // This is important for performance; we need to know whether the default
5119 // constructor is constexpr to determine whether the type is a literal type.
5120 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5121
Richard Smithb5800092012-06-10 05:43:50 +00005122 case Sema::CXXCopyConstructor:
5123 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005124 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005125 break;
5126
5127 case Sema::CXXCopyAssignment:
5128 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005129 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005130 return false;
5131 // In C++1y, we need to perform overload resolution.
5132 Ctor = false;
5133 break;
5134
Richard Smithb5800092012-06-10 05:43:50 +00005135 case Sema::CXXDestructor:
5136 case Sema::CXXInvalid:
5137 return false;
5138 }
5139
5140 // -- if the class is a non-empty union, or for each non-empty anonymous
5141 // union member of a non-union class, exactly one non-static data member
5142 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005143 //
5144 // If we squint, this is guaranteed, since exactly one non-static data member
5145 // will be initialized (if the constructor isn't deleted), we just don't know
5146 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005147 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005148 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005149
5150 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005151 if (Ctor && ClassDecl->getNumVBases())
5152 return false;
5153
5154 // C++1y [class.copy]p26:
5155 // -- [the class] is a literal type, and
5156 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005157 return false;
5158
5159 // -- every constructor involved in initializing [...] base class
5160 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005161 // -- the assignment operator selected to copy/move each direct base
5162 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005163 for (const auto &B : ClassDecl->bases()) {
5164 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005165 if (!BaseType) continue;
5166
5167 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005168 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005169 return false;
5170 }
5171
5172 // -- every constructor involved in initializing non-static data members
5173 // [...] shall be a constexpr constructor;
5174 // -- every non-static data member and base class sub-object shall be
5175 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005176 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005177 // thereof), the assignment operator selected to copy/move that member is
5178 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005179 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005180 if (F->isInvalidDecl())
5181 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005182 QualType BaseType = S.Context.getBaseElementType(F->getType());
5183 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005184 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005185 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5186 BaseType.getCVRQualifiers(),
5187 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005188 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005189 }
5190 }
5191
5192 // All OK, it's constexpr!
5193 return true;
5194}
5195
Richard Smithd3b5c9082012-07-27 04:22:15 +00005196static Sema::ImplicitExceptionSpecification
5197computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5198 switch (S.getSpecialMember(MD)) {
5199 case Sema::CXXDefaultConstructor:
5200 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5201 case Sema::CXXCopyConstructor:
5202 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5203 case Sema::CXXCopyAssignment:
5204 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5205 case Sema::CXXMoveConstructor:
5206 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5207 case Sema::CXXMoveAssignment:
5208 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5209 case Sema::CXXDestructor:
5210 return S.ComputeDefaultedDtorExceptionSpec(MD);
5211 case Sema::CXXInvalid:
5212 break;
5213 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005214 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5215 "only special members have implicit exception specs");
5216 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005217}
5218
Reid Kleckner78af0702013-08-27 23:08:25 +00005219static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5220 CXXMethodDecl *MD) {
5221 FunctionProtoType::ExtProtoInfo EPI;
5222
5223 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005224 EPI.ExceptionSpec.Type = EST_Unevaluated;
5225 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005226
5227 // Set the calling convention to the default for C++ instance methods.
5228 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5229 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5230 /*IsCXXMethod=*/true));
5231 return EPI;
5232}
5233
Richard Smithd3b5c9082012-07-27 04:22:15 +00005234void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5235 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5236 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5237 return;
5238
Richard Smith7f782272012-07-30 23:48:14 +00005239 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005240 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005241
Richard Smith7f782272012-07-30 23:48:14 +00005242 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005243 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005244
5245 // A user-provided destructor can be defined outside the class. When that
5246 // happens, be sure to update the exception specification on both
5247 // declarations.
5248 const FunctionProtoType *CanonicalFPT =
5249 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5250 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005251 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005252}
5253
Richard Smithb9e90b12012-05-15 04:39:51 +00005254void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5255 CXXRecordDecl *RD = MD->getParent();
5256 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005257
Richard Smithb9e90b12012-05-15 04:39:51 +00005258 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5259 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005260
5261 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005262 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005263 bool First = MD == MD->getCanonicalDecl();
5264
5265 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005266
5267 // C++11 [dcl.fct.def.default]p1:
5268 // A function that is explicitly defaulted shall
5269 // -- be a special member function (checked elsewhere),
5270 // -- have the same type (except for ref-qualifiers, and except that a
5271 // copy operation can take a non-const reference) as an implicit
5272 // declaration, and
5273 // -- not have default arguments.
5274 unsigned ExpectedParams = 1;
5275 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5276 ExpectedParams = 0;
5277 if (MD->getNumParams() != ExpectedParams) {
5278 // This also checks for default arguments: a copy or move constructor with a
5279 // default argument is classified as a default constructor, and assignment
5280 // operations and destructors can't have default arguments.
5281 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5282 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005283 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005284 } else if (MD->isVariadic()) {
5285 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5286 << CSM << MD->getSourceRange();
5287 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005288 }
5289
Richard Smithb9e90b12012-05-15 04:39:51 +00005290 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005291
Richard Smithb5800092012-06-10 05:43:50 +00005292 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005293 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005294 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005295 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005296 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005297
Richard Smithb9e90b12012-05-15 04:39:51 +00005298 QualType ReturnType = Context.VoidTy;
5299 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5300 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005301 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005302 QualType ExpectedReturnType =
5303 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5304 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5305 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5306 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5307 HadError = true;
5308 }
5309
5310 // A defaulted special member cannot have cv-qualifiers.
5311 if (Type->getTypeQuals()) {
5312 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005313 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005314 HadError = true;
5315 }
5316 }
5317
5318 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005319 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005320 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005321 if (ExpectedParams && ArgType->isReferenceType()) {
5322 // Argument must be reference to possibly-const T.
5323 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005324 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005325
5326 if (ReferentType.isVolatileQualified()) {
5327 Diag(MD->getLocation(),
5328 diag::err_defaulted_special_member_volatile_param) << CSM;
5329 HadError = true;
5330 }
5331
Richard Smithb5800092012-06-10 05:43:50 +00005332 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005333 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5334 Diag(MD->getLocation(),
5335 diag::err_defaulted_special_member_copy_const_param)
5336 << (CSM == CXXCopyAssignment);
5337 // FIXME: Explain why this special member can't be const.
5338 } else {
5339 Diag(MD->getLocation(),
5340 diag::err_defaulted_special_member_move_const_param)
5341 << (CSM == CXXMoveAssignment);
5342 }
5343 HadError = true;
5344 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005345 } else if (ExpectedParams) {
5346 // A copy assignment operator can take its argument by value, but a
5347 // defaulted one cannot.
5348 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005349 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005350 HadError = true;
5351 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005352
Richard Smithcc36f692011-12-22 02:22:31 +00005353 // C++11 [dcl.fct.def.default]p2:
5354 // An explicitly-defaulted function may be declared constexpr only if it
5355 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005356 // Do not apply this rule to members of class templates, since core issue 1358
5357 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005358 // functions which cannot be constexpr (for non-constructors in C++11 and for
5359 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005360 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5361 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005362 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005363 : isa<CXXConstructorDecl>(MD)) &&
5364 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005365 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5366 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005367 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005368 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005369 }
Richard Smithbd305122012-12-11 01:14:52 +00005370
Richard Smithcc36f692011-12-22 02:22:31 +00005371 // and may have an explicit exception-specification only if it is compatible
5372 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005373 if (Type->hasExceptionSpec()) {
5374 // Delay the check if this is the first declaration of the special member,
5375 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005376 if (First) {
5377 // If the exception specification needs to be instantiated, do so now,
5378 // before we clobber it with an EST_Unevaluated specification below.
5379 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5380 InstantiateExceptionSpec(MD->getLocStart(), MD);
5381 Type = MD->getType()->getAs<FunctionProtoType>();
5382 }
Richard Smithbd305122012-12-11 01:14:52 +00005383 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005384 } else
Richard Smithbd305122012-12-11 01:14:52 +00005385 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5386 }
Richard Smithcc36f692011-12-22 02:22:31 +00005387
5388 // If a function is explicitly defaulted on its first declaration,
5389 if (First) {
5390 // -- it is implicitly considered to be constexpr if the implicit
5391 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005392 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005393
Richard Smithb9e90b12012-05-15 04:39:51 +00005394 // -- it is implicitly considered to have the same exception-specification
5395 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005396 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005397 EPI.ExceptionSpec.Type = EST_Unevaluated;
5398 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005399 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005400 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005401 ExpectedParams),
5402 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005403 }
5404
Richard Smithb9e90b12012-05-15 04:39:51 +00005405 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005406 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005407 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005408 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005409 // C++11 [dcl.fct.def.default]p4:
5410 // [For a] user-provided explicitly-defaulted function [...] if such a
5411 // function is implicitly defined as deleted, the program is ill-formed.
5412 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005413 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005414 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005415 }
5416 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005417
Richard Smithb9e90b12012-05-15 04:39:51 +00005418 if (HadError)
5419 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005420}
5421
Richard Smithbd305122012-12-11 01:14:52 +00005422/// Check whether the exception specification provided for an
5423/// explicitly-defaulted special member matches the exception specification
5424/// that would have been generated for an implicit special member, per
5425/// C++11 [dcl.fct.def.default]p2.
5426void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5427 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005428 // If the exception specification was explicitly specified but hadn't been
5429 // parsed when the method was defaulted, grab it now.
5430 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5431 SpecifiedType =
5432 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5433
Richard Smithbd305122012-12-11 01:14:52 +00005434 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005435 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5436 /*IsCXXMethod=*/true);
5437 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005438 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5439 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005440 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005441 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005442
5443 // Ensure that it matches.
5444 CheckEquivalentExceptionSpec(
5445 PDiag(diag::err_incorrect_defaulted_exception_spec)
5446 << getSpecialMember(MD), PDiag(),
5447 ImplicitType, SourceLocation(),
5448 SpecifiedType, MD->getLocation());
5449}
5450
Alp Tokerae3a9442013-10-18 05:54:19 +00005451void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005452 decltype(DelayedExceptionSpecChecks) Checks;
5453 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005454
Richard Smith88f45492014-11-22 03:09:05 +00005455 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005456 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5457
5458 // Perform any deferred checking of exception specifications for virtual
5459 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005460 for (auto &Check : Checks)
5461 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005462
5463 // Check that any explicitly-defaulted methods have exception specifications
5464 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005465 for (auto &Spec : Specs)
5466 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005467}
5468
Richard Smithd951a1d2012-02-18 02:02:13 +00005469namespace {
5470struct SpecialMemberDeletionInfo {
5471 Sema &S;
5472 CXXMethodDecl *MD;
5473 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005474 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005475
5476 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005477 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005478 SourceLocation Loc;
5479
5480 bool AllFieldsAreConst;
5481
5482 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005483 Sema::CXXSpecialMember CSM, bool Diagnose)
5484 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005485 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005486 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005487 AllFieldsAreConst(true) {
5488 switch (CSM) {
5489 case Sema::CXXDefaultConstructor:
5490 case Sema::CXXCopyConstructor:
5491 IsConstructor = true;
5492 break;
5493 case Sema::CXXMoveConstructor:
5494 IsConstructor = true;
5495 IsMove = true;
5496 break;
5497 case Sema::CXXCopyAssignment:
5498 IsAssignment = true;
5499 break;
5500 case Sema::CXXMoveAssignment:
5501 IsAssignment = true;
5502 IsMove = true;
5503 break;
5504 case Sema::CXXDestructor:
5505 break;
5506 case Sema::CXXInvalid:
5507 llvm_unreachable("invalid special member kind");
5508 }
5509
5510 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005511 if (const ReferenceType *RT =
5512 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5513 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005514 }
5515 }
5516
5517 bool inUnion() const { return MD->getParent()->isUnion(); }
5518
5519 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005520 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005521 unsigned Quals, bool IsMutable) {
5522 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5523 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005524 }
5525
Richard Smith852265f2012-03-30 20:53:28 +00005526 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005527
Richard Smith852265f2012-03-30 20:53:28 +00005528 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005529 bool shouldDeleteForField(FieldDecl *FD);
5530 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005531
Richard Smithaf136f82012-07-18 03:51:16 +00005532 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5533 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005534 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5535 Sema::SpecialMemberOverloadResult *SMOR,
5536 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005537
5538 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005539};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005540}
Richard Smithd951a1d2012-02-18 02:02:13 +00005541
John McCalld4274212012-04-09 20:53:23 +00005542/// Is the given special member inaccessible when used on the given
5543/// sub-object.
5544bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5545 CXXMethodDecl *target) {
5546 /// If we're operating on a base class, the object type is the
5547 /// type of this special member.
5548 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005549 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005550 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5551 objectTy = S.Context.getTypeDeclType(MD->getParent());
5552 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5553
5554 // If we're operating on a field, the object type is the type of the field.
5555 } else {
5556 objectTy = S.Context.getTypeDeclType(target->getParent());
5557 }
5558
5559 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5560}
5561
Richard Smith852265f2012-03-30 20:53:28 +00005562/// Check whether we should delete a special member due to the implicit
5563/// definition containing a call to a special member of a subobject.
5564bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5565 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5566 bool IsDtorCallInCtor) {
5567 CXXMethodDecl *Decl = SMOR->getMethod();
5568 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5569
5570 int DiagKind = -1;
5571
5572 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5573 DiagKind = !Decl ? 0 : 1;
5574 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5575 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005576 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005577 DiagKind = 3;
5578 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5579 !Decl->isTrivial()) {
5580 // A member of a union must have a trivial corresponding special member.
5581 // As a weird special case, a destructor call from a union's constructor
5582 // must be accessible and non-deleted, but need not be trivial. Such a
5583 // destructor is never actually called, but is semantically checked as
5584 // if it were.
5585 DiagKind = 4;
5586 }
5587
5588 if (DiagKind == -1)
5589 return false;
5590
5591 if (Diagnose) {
5592 if (Field) {
5593 S.Diag(Field->getLocation(),
5594 diag::note_deleted_special_member_class_subobject)
5595 << CSM << MD->getParent() << /*IsField*/true
5596 << Field << DiagKind << IsDtorCallInCtor;
5597 } else {
5598 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5599 S.Diag(Base->getLocStart(),
5600 diag::note_deleted_special_member_class_subobject)
5601 << CSM << MD->getParent() << /*IsField*/false
5602 << Base->getType() << DiagKind << IsDtorCallInCtor;
5603 }
5604
5605 if (DiagKind == 1)
5606 S.NoteDeletedFunction(Decl);
5607 // FIXME: Explain inaccessibility if DiagKind == 3.
5608 }
5609
5610 return true;
5611}
5612
Richard Smith921bd202012-02-26 09:11:52 +00005613/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005614/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005615bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005616 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005617 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005618 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005619
5620 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005621 // -- any direct or virtual base class, or non-static data member with no
5622 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005623 // either M has no default constructor or overload resolution as applied
5624 // to M's default constructor results in an ambiguity or in a function
5625 // that is deleted or inaccessible
5626 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5627 // -- a direct or virtual base class B that cannot be copied/moved because
5628 // overload resolution, as applied to B's corresponding special member,
5629 // results in an ambiguity or a function that is deleted or inaccessible
5630 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005631 // C++11 [class.dtor]p5:
5632 // -- any direct or virtual base class [...] has a type with a destructor
5633 // that is deleted or inaccessible
5634 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005635 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005636 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5637 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005638 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005639
Richard Smith852265f2012-03-30 20:53:28 +00005640 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5641 // -- any direct or virtual base class or non-static data member has a
5642 // type with a destructor that is deleted or inaccessible
5643 if (IsConstructor) {
5644 Sema::SpecialMemberOverloadResult *SMOR =
5645 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5646 false, false, false, false, false);
5647 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5648 return true;
5649 }
5650
Richard Smith921bd202012-02-26 09:11:52 +00005651 return false;
5652}
5653
5654/// Check whether we should delete a special member function due to the class
5655/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005656bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005657 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005658 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005659}
5660
5661/// Check whether we should delete a special member function due to the class
5662/// having a particular non-static data member.
5663bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5664 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5665 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5666
5667 if (CSM == Sema::CXXDefaultConstructor) {
5668 // For a default constructor, all references must be initialized in-class
5669 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005670 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5671 if (Diagnose)
5672 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5673 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005674 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005675 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005676 // C++11 [class.ctor]p5: any non-variant non-static data member of
5677 // const-qualified type (or array thereof) with no
5678 // brace-or-equal-initializer does not have a user-provided default
5679 // constructor.
5680 if (!inUnion() && FieldType.isConstQualified() &&
5681 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005682 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5683 if (Diagnose)
5684 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005685 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005686 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005687 }
5688
5689 if (inUnion() && !FieldType.isConstQualified())
5690 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005691 } else if (CSM == Sema::CXXCopyConstructor) {
5692 // For a copy constructor, data members must not be of rvalue reference
5693 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005694 if (FieldType->isRValueReferenceType()) {
5695 if (Diagnose)
5696 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5697 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005698 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005699 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005700 } else if (IsAssignment) {
5701 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005702 if (FieldType->isReferenceType()) {
5703 if (Diagnose)
5704 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5705 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005706 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005707 }
5708 if (!FieldRecord && FieldType.isConstQualified()) {
5709 // C++11 [class.copy]p23:
5710 // -- a non-static data member of const non-class type (or array thereof)
5711 if (Diagnose)
5712 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005713 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005714 return true;
5715 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005716 }
5717
5718 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005719 // Some additional restrictions exist on the variant members.
5720 if (!inUnion() && FieldRecord->isUnion() &&
5721 FieldRecord->isAnonymousStructOrUnion()) {
5722 bool AllVariantFieldsAreConst = true;
5723
Richard Smith5704fe82012-03-29 19:00:10 +00005724 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005725 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005726 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005727
5728 if (!UnionFieldType.isConstQualified())
5729 AllVariantFieldsAreConst = false;
5730
Richard Smith921bd202012-02-26 09:11:52 +00005731 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5732 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005733 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005734 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005735 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005736 }
5737
5738 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005739 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005740 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005741 if (Diagnose)
5742 S.Diag(FieldRecord->getLocation(),
5743 diag::note_deleted_default_ctor_all_const)
5744 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005745 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005746 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005747
Richard Smith5704fe82012-03-29 19:00:10 +00005748 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005749 // This is technically non-conformant, but sanity demands it.
5750 return false;
5751 }
5752
Richard Smithaf136f82012-07-18 03:51:16 +00005753 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5754 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005755 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005756 }
5757
5758 return false;
5759}
5760
5761/// C++11 [class.ctor] p5:
5762/// A defaulted default constructor for a class X is defined as deleted if
5763/// X is a union and all of its variant members are of const-qualified type.
5764bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005765 // This is a silly definition, because it gives an empty union a deleted
5766 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005767 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005768 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005769 if (Diagnose)
5770 S.Diag(MD->getParent()->getLocation(),
5771 diag::note_deleted_default_ctor_all_const)
5772 << MD->getParent() << /*not anonymous union*/0;
5773 return true;
5774 }
5775 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005776}
5777
5778/// Determine whether a defaulted special member function should be defined as
5779/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5780/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005781bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5782 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005783 if (MD->isInvalidDecl())
5784 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005785 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005786 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005787 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005788 return false;
5789
Richard Smithd951a1d2012-02-18 02:02:13 +00005790 // C++11 [expr.lambda.prim]p19:
5791 // The closure type associated with a lambda-expression has a
5792 // deleted (8.4.3) default constructor and a deleted copy
5793 // assignment operator.
5794 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005795 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5796 if (Diagnose)
5797 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005798 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005799 }
5800
Richard Smith6f1e2c62012-04-02 20:59:25 +00005801 // For an anonymous struct or union, the copy and assignment special members
5802 // will never be used, so skip the check. For an anonymous union declared at
5803 // namespace scope, the constructor and destructor are used.
5804 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5805 RD->isAnonymousStructOrUnion())
5806 return false;
5807
Richard Smith852265f2012-03-30 20:53:28 +00005808 // C++11 [class.copy]p7, p18:
5809 // If the class definition declares a move constructor or move assignment
5810 // operator, an implicitly declared copy constructor or copy assignment
5811 // operator is defined as deleted.
5812 if (MD->isImplicit() &&
5813 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005814 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005815
5816 // In Microsoft mode, a user-declared move only causes the deletion of the
5817 // corresponding copy operation, not both copy operations.
5818 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005819 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005820 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005821
5822 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005823 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005824 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005825 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005826 break;
5827 }
5828 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005829 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005830 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005831 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005832 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005833
5834 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005835 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005836 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005837 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005838 break;
5839 }
5840 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005841 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005842 }
5843
5844 if (UserDeclaredMove) {
5845 Diag(UserDeclaredMove->getLocation(),
5846 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005847 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005848 << UserDeclaredMove->isMoveAssignmentOperator();
5849 return true;
5850 }
5851 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005852
Richard Smith6f1e2c62012-04-02 20:59:25 +00005853 // Do access control from the special member function
5854 ContextRAII MethodContext(*this, MD);
5855
Richard Smith921bd202012-02-26 09:11:52 +00005856 // C++11 [class.dtor]p5:
5857 // -- for a virtual destructor, lookup of the non-array deallocation function
5858 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005859 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005860 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005861 DeclarationName Name =
5862 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5863 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005864 OperatorDelete, false)) {
5865 if (Diagnose)
5866 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005867 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005868 }
Richard Smith921bd202012-02-26 09:11:52 +00005869 }
5870
Richard Smith852265f2012-03-30 20:53:28 +00005871 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005872
Aaron Ballman574705e2014-03-13 15:41:46 +00005873 for (auto &BI : RD->bases())
5874 if (!BI.isVirtual() &&
5875 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005876 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005877
Richard Smithd1627032013-07-22 18:06:23 +00005878 // Per DR1611, do not consider virtual bases of constructors of abstract
5879 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005880 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005881 for (auto &BI : RD->vbases())
5882 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005883 return true;
5884 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005885
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005886 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005887 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005888 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005889 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005890
Richard Smithd951a1d2012-02-18 02:02:13 +00005891 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005892 return true;
5893
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005894 if (getLangOpts().CUDA) {
5895 // We should delete the special member in CUDA mode if target inference
5896 // failed.
5897 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5898 Diagnose);
5899 }
5900
Alexis Huntea6f0322011-05-11 22:34:38 +00005901 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005902}
5903
Richard Smith92f241f2012-12-08 02:53:02 +00005904/// Perform lookup for a special member of the specified kind, and determine
5905/// whether it is trivial. If the triviality can be determined without the
5906/// lookup, skip it. This is intended for use when determining whether a
5907/// special member of a containing object is trivial, and thus does not ever
5908/// perform overload resolution for default constructors.
5909///
5910/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5911/// member that was most likely to be intended to be trivial, if any.
5912static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5913 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005914 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005915 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005916 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005917
5918 switch (CSM) {
5919 case Sema::CXXInvalid:
5920 llvm_unreachable("not a special member");
5921
5922 case Sema::CXXDefaultConstructor:
5923 // C++11 [class.ctor]p5:
5924 // A default constructor is trivial if:
5925 // - all the [direct subobjects] have trivial default constructors
5926 //
5927 // Note, no overload resolution is performed in this case.
5928 if (RD->hasTrivialDefaultConstructor())
5929 return true;
5930
5931 if (Selected) {
5932 // If there's a default constructor which could have been trivial, dig it
5933 // out. Otherwise, if there's any user-provided default constructor, point
5934 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005935 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005936 if (RD->needsImplicitDefaultConstructor())
5937 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005938 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005939 if (!CI->isDefaultConstructor())
5940 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005941 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005942 if (!DefCtor->isUserProvided())
5943 break;
5944 }
5945
5946 *Selected = DefCtor;
5947 }
5948
5949 return false;
5950
5951 case Sema::CXXDestructor:
5952 // C++11 [class.dtor]p5:
5953 // A destructor is trivial if:
5954 // - all the direct [subobjects] have trivial destructors
5955 if (RD->hasTrivialDestructor())
5956 return true;
5957
5958 if (Selected) {
5959 if (RD->needsImplicitDestructor())
5960 S.DeclareImplicitDestructor(RD);
5961 *Selected = RD->getDestructor();
5962 }
5963
5964 return false;
5965
5966 case Sema::CXXCopyConstructor:
5967 // C++11 [class.copy]p12:
5968 // A copy constructor is trivial if:
5969 // - the constructor selected to copy each direct [subobject] is trivial
5970 if (RD->hasTrivialCopyConstructor()) {
5971 if (Quals == Qualifiers::Const)
5972 // We must either select the trivial copy constructor or reach an
5973 // ambiguity; no need to actually perform overload resolution.
5974 return true;
5975 } else if (!Selected) {
5976 return false;
5977 }
5978 // In C++98, we are not supposed to perform overload resolution here, but we
5979 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5980 // cases like B as having a non-trivial copy constructor:
5981 // struct A { template<typename T> A(T&); };
5982 // struct B { mutable A a; };
5983 goto NeedOverloadResolution;
5984
5985 case Sema::CXXCopyAssignment:
5986 // C++11 [class.copy]p25:
5987 // A copy assignment operator is trivial if:
5988 // - the assignment operator selected to copy each direct [subobject] is
5989 // trivial
5990 if (RD->hasTrivialCopyAssignment()) {
5991 if (Quals == Qualifiers::Const)
5992 return true;
5993 } else if (!Selected) {
5994 return false;
5995 }
5996 // In C++98, we are not supposed to perform overload resolution here, but we
5997 // treat that as a language defect.
5998 goto NeedOverloadResolution;
5999
6000 case Sema::CXXMoveConstructor:
6001 case Sema::CXXMoveAssignment:
6002 NeedOverloadResolution:
6003 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006004 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00006005
6006 // The standard doesn't describe how to behave if the lookup is ambiguous.
6007 // We treat it as not making the member non-trivial, just like the standard
6008 // mandates for the default constructor. This should rarely matter, because
6009 // the member will also be deleted.
6010 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6011 return true;
6012
6013 if (!SMOR->getMethod()) {
6014 assert(SMOR->getKind() ==
6015 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6016 return false;
6017 }
6018
6019 // We deliberately don't check if we found a deleted special member. We're
6020 // not supposed to!
6021 if (Selected)
6022 *Selected = SMOR->getMethod();
6023 return SMOR->getMethod()->isTrivial();
6024 }
6025
6026 llvm_unreachable("unknown special method kind");
6027}
6028
Benjamin Kramer3e350262013-02-15 12:30:38 +00006029static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006030 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006031 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006032 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006033
6034 // Look for constructor templates.
6035 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6036 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6037 if (CXXConstructorDecl *CD =
6038 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6039 return CD;
6040 }
6041
Craig Topperc3ec1492014-05-26 06:22:03 +00006042 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006043}
6044
6045/// The kind of subobject we are checking for triviality. The values of this
6046/// enumeration are used in diagnostics.
6047enum TrivialSubobjectKind {
6048 /// The subobject is a base class.
6049 TSK_BaseClass,
6050 /// The subobject is a non-static data member.
6051 TSK_Field,
6052 /// The object is actually the complete object.
6053 TSK_CompleteObject
6054};
6055
6056/// Check whether the special member selected for a given type would be trivial.
6057static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006058 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006059 Sema::CXXSpecialMember CSM,
6060 TrivialSubobjectKind Kind,
6061 bool Diagnose) {
6062 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6063 if (!SubRD)
6064 return true;
6065
6066 CXXMethodDecl *Selected;
6067 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006068 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006069 return true;
6070
6071 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006072 if (ConstRHS)
6073 SubType.addConst();
6074
Richard Smith92f241f2012-12-08 02:53:02 +00006075 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6076 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6077 << Kind << SubType.getUnqualifiedType();
6078 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6079 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6080 } else if (!Selected)
6081 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6082 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6083 else if (Selected->isUserProvided()) {
6084 if (Kind == TSK_CompleteObject)
6085 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6086 << Kind << SubType.getUnqualifiedType() << CSM;
6087 else {
6088 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6089 << Kind << SubType.getUnqualifiedType() << CSM;
6090 S.Diag(Selected->getLocation(), diag::note_declared_at);
6091 }
6092 } else {
6093 if (Kind != TSK_CompleteObject)
6094 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6095 << Kind << SubType.getUnqualifiedType() << CSM;
6096
6097 // Explain why the defaulted or deleted special member isn't trivial.
6098 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6099 }
6100 }
6101
6102 return false;
6103}
6104
6105/// Check whether the members of a class type allow a special member to be
6106/// trivial.
6107static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6108 Sema::CXXSpecialMember CSM,
6109 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006110 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006111 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6112 continue;
6113
6114 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6115
6116 // Pretend anonymous struct or union members are members of this class.
6117 if (FI->isAnonymousStructOrUnion()) {
6118 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6119 CSM, ConstArg, Diagnose))
6120 return false;
6121 continue;
6122 }
6123
6124 // C++11 [class.ctor]p5:
6125 // A default constructor is trivial if [...]
6126 // -- no non-static data member of its class has a
6127 // brace-or-equal-initializer
6128 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6129 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006130 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006131 return false;
6132 }
6133
6134 // Objective C ARC 4.3.5:
6135 // [...] nontrivally ownership-qualified types are [...] not trivially
6136 // default constructible, copy constructible, move constructible, copy
6137 // assignable, move assignable, or destructible [...]
6138 if (S.getLangOpts().ObjCAutoRefCount &&
6139 FieldType.hasNonTrivialObjCLifetime()) {
6140 if (Diagnose)
6141 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6142 << RD << FieldType.getObjCLifetime();
6143 return false;
6144 }
6145
Richard Smith41c35d62013-11-27 03:39:20 +00006146 bool ConstRHS = ConstArg && !FI->isMutable();
6147 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6148 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006149 return false;
6150 }
6151
6152 return true;
6153}
6154
6155/// Diagnose why the specified class does not have a trivial special member of
6156/// the given kind.
6157void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6158 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006159
Richard Smith41c35d62013-11-27 03:39:20 +00006160 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6161 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006162 TSK_CompleteObject, /*Diagnose*/true);
6163}
6164
6165/// Determine whether a defaulted or deleted special member function is trivial,
6166/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6167/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6168bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6169 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006170 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6171
6172 CXXRecordDecl *RD = MD->getParent();
6173
6174 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006175
Richard Smith2002bfe2013-11-04 02:02:27 +00006176 // C++11 [class.copy]p12, p25: [DR1593]
6177 // A [special member] is trivial if [...] its parameter-type-list is
6178 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006179 switch (CSM) {
6180 case CXXDefaultConstructor:
6181 case CXXDestructor:
6182 // Trivial default constructors and destructors cannot have parameters.
6183 break;
6184
6185 case CXXCopyConstructor:
6186 case CXXCopyAssignment: {
6187 // Trivial copy operations always have const, non-volatile parameter types.
6188 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006189 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006190 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6191 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6192 if (Diagnose)
6193 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6194 << Param0->getSourceRange() << Param0->getType()
6195 << Context.getLValueReferenceType(
6196 Context.getRecordType(RD).withConst());
6197 return false;
6198 }
6199 break;
6200 }
6201
6202 case CXXMoveConstructor:
6203 case CXXMoveAssignment: {
6204 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006205 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006206 const RValueReferenceType *RT =
6207 Param0->getType()->getAs<RValueReferenceType>();
6208 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6209 if (Diagnose)
6210 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6211 << Param0->getSourceRange() << Param0->getType()
6212 << Context.getRValueReferenceType(Context.getRecordType(RD));
6213 return false;
6214 }
6215 break;
6216 }
6217
6218 case CXXInvalid:
6219 llvm_unreachable("not a special member");
6220 }
6221
Richard Smith92f241f2012-12-08 02:53:02 +00006222 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6223 if (Diagnose)
6224 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6225 diag::note_nontrivial_default_arg)
6226 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6227 return false;
6228 }
6229 if (MD->isVariadic()) {
6230 if (Diagnose)
6231 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6232 return false;
6233 }
6234
6235 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6236 // A copy/move [constructor or assignment operator] is trivial if
6237 // -- the [member] selected to copy/move each direct base class subobject
6238 // is trivial
6239 //
6240 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6241 // A [default constructor or destructor] is trivial if
6242 // -- all the direct base classes have trivial [default constructors or
6243 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006244 for (const auto &BI : RD->bases())
6245 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006246 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006247 return false;
6248
6249 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6250 // A copy/move [constructor or assignment operator] for a class X is
6251 // trivial if
6252 // -- for each non-static data member of X that is of class type (or array
6253 // thereof), the constructor selected to copy/move that member is
6254 // trivial
6255 //
6256 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6257 // A [default constructor or destructor] is trivial if
6258 // -- for all of the non-static data members of its class that are of class
6259 // type (or array thereof), each such class has a trivial [default
6260 // constructor or destructor]
6261 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6262 return false;
6263
6264 // C++11 [class.dtor]p5:
6265 // A destructor is trivial if [...]
6266 // -- the destructor is not virtual
6267 if (CSM == CXXDestructor && MD->isVirtual()) {
6268 if (Diagnose)
6269 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6270 return false;
6271 }
6272
6273 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6274 // A [special member] for class X is trivial if [...]
6275 // -- class X has no virtual functions and no virtual base classes
6276 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6277 if (!Diagnose)
6278 return false;
6279
6280 if (RD->getNumVBases()) {
6281 // Check for virtual bases. We already know that the corresponding
6282 // member in all bases is trivial, so vbases must all be direct.
6283 CXXBaseSpecifier &BS = *RD->vbases_begin();
6284 assert(BS.isVirtual());
6285 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6286 return false;
6287 }
6288
6289 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006290 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006291 if (MI->isVirtual()) {
6292 SourceLocation MLoc = MI->getLocStart();
6293 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6294 return false;
6295 }
6296 }
6297
6298 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6299 }
6300
6301 // Looks like it's trivial!
6302 return true;
6303}
6304
Benjamin Kramer024e6192011-03-04 13:12:48 +00006305namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006306struct FindHiddenVirtualMethod {
6307 Sema *S;
6308 CXXMethodDecl *Method;
6309 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6310 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006311
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006312private:
6313 /// Check whether any most overriden method from MD in Methods
6314 static bool CheckMostOverridenMethods(
6315 const CXXMethodDecl *MD,
6316 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6317 if (MD->size_overridden_methods() == 0)
6318 return Methods.count(MD->getCanonicalDecl());
6319 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6320 E = MD->end_overridden_methods();
6321 I != E; ++I)
6322 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006323 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006324 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006325 }
6326
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006327public:
6328 /// Member lookup function that determines whether a given C++
6329 /// method overloads virtual methods in a base class without overriding any,
6330 /// to be used with CXXRecordDecl::lookupInBases().
6331 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6332 RecordDecl *BaseRecord =
6333 Specifier->getType()->getAs<RecordType>()->getDecl();
6334
6335 DeclarationName Name = Method->getDeclName();
6336 assert(Name.getNameKind() == DeclarationName::Identifier);
6337
6338 bool foundSameNameMethod = false;
6339 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6340 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6341 Path.Decls = Path.Decls.slice(1)) {
6342 NamedDecl *D = Path.Decls.front();
6343 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6344 MD = MD->getCanonicalDecl();
6345 foundSameNameMethod = true;
6346 // Interested only in hidden virtual methods.
6347 if (!MD->isVirtual())
6348 continue;
6349 // If the method we are checking overrides a method from its base
6350 // don't warn about the other overloaded methods. Clang deviates from
6351 // GCC by only diagnosing overloads of inherited virtual functions that
6352 // do not override any other virtual functions in the base. GCC's
6353 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6354 // function from a base class. These cases may be better served by a
6355 // warning (not specific to virtual functions) on call sites when the
6356 // call would select a different function from the base class, were it
6357 // visible.
6358 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6359 if (!S->IsOverload(Method, MD, false))
6360 return true;
6361 // Collect the overload only if its hidden.
6362 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6363 overloadedMethods.push_back(MD);
6364 }
6365 }
6366
6367 if (foundSameNameMethod)
6368 OverloadedMethods.append(overloadedMethods.begin(),
6369 overloadedMethods.end());
6370 return foundSameNameMethod;
6371 }
6372};
6373} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006374
David Blaikie282c92a2012-10-19 00:53:08 +00006375/// \brief Add the most overriden methods from MD to Methods
6376static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006377 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006378 if (MD->size_overridden_methods() == 0)
6379 Methods.insert(MD->getCanonicalDecl());
6380 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6381 E = MD->end_overridden_methods();
6382 I != E; ++I)
6383 AddMostOverridenMethods(*I, Methods);
6384}
6385
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006386/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006387/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006388void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6389 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006390 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006391 return;
6392
6393 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6394 /*bool RecordPaths=*/false,
6395 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006396 FindHiddenVirtualMethod FHVM;
6397 FHVM.Method = MD;
6398 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006399
6400 // Keep the base methods that were overriden or introduced in the subclass
6401 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006402 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006403 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6404 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6405 NamedDecl *ND = *I;
6406 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006407 ND = shad->getTargetDecl();
6408 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006409 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006410 }
6411
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00006412 if (DC->lookupInBases(FHVM, Paths))
6413 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006414}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006415
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006416void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6417 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6418 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6419 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6420 PartialDiagnostic PD = PDiag(
6421 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6422 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6423 Diag(overloadedMD->getLocation(), PD);
6424 }
6425}
6426
6427/// \brief Diagnose methods which overload virtual methods in a base class
6428/// without overriding any.
6429void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6430 if (MD->isInvalidDecl())
6431 return;
6432
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006433 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006434 return;
6435
6436 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6437 FindHiddenVirtualMethods(MD, OverloadedMethods);
6438 if (!OverloadedMethods.empty()) {
6439 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6440 << MD << (OverloadedMethods.size() > 1);
6441
6442 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006443 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006444}
6445
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006446void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006447 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006448 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006449 SourceLocation RBrac,
6450 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006451 if (!TagDecl)
6452 return;
Mike Stump11289f42009-09-09 15:08:12 +00006453
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006454 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006455
Rafael Espindola06e1b132012-07-12 04:32:30 +00006456 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6457 if (l->getKind() != AttributeList::AT_Visibility)
6458 continue;
6459 l->setInvalid();
6460 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6461 l->getName();
6462 }
6463
David Blaikie751c5582011-09-22 02:58:26 +00006464 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006465 // strict aliasing violation!
6466 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006467 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006468
Douglas Gregor0be31a22010-07-02 17:43:08 +00006469 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006470 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006471}
6472
Douglas Gregor05379422008-11-03 17:51:48 +00006473/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6474/// special functions, such as the default constructor, copy
6475/// constructor, or destructor, to the given C++ class (C++
6476/// [special]p1). This routine can only be executed just before the
6477/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006478void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006479 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006480 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006481
Richard Smith6b02d462012-12-08 08:32:28 +00006482 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006483 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006484
Richard Smith6b02d462012-12-08 08:32:28 +00006485 // If the properties or semantics of the copy constructor couldn't be
6486 // determined while the class was being declared, force a declaration
6487 // of it now.
6488 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6489 DeclareImplicitCopyConstructor(ClassDecl);
6490 }
6491
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006492 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006493 ++ASTContext::NumImplicitMoveConstructors;
6494
Richard Smith6b02d462012-12-08 08:32:28 +00006495 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6496 DeclareImplicitMoveConstructor(ClassDecl);
6497 }
6498
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006499 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6500 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006501
6502 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006503 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006504 // it shows up in the right place in the vtable and that we diagnose
6505 // problems with the implicit exception specification.
6506 if (ClassDecl->isDynamicClass() ||
6507 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006508 DeclareImplicitCopyAssignment(ClassDecl);
6509 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006510
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006511 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006512 ++ASTContext::NumImplicitMoveAssignmentOperators;
6513
6514 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006515 if (ClassDecl->isDynamicClass() ||
6516 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006517 DeclareImplicitMoveAssignment(ClassDecl);
6518 }
6519
Douglas Gregor7454c562010-07-02 20:37:36 +00006520 if (!ClassDecl->hasUserDeclaredDestructor()) {
6521 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006522
6523 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006524 // have to declare the destructor immediately. This ensures that, e.g., it
6525 // shows up in the right place in the vtable and that we diagnose problems
6526 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006527 if (ClassDecl->isDynamicClass() ||
6528 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006529 DeclareImplicitDestructor(ClassDecl);
6530 }
Douglas Gregor05379422008-11-03 17:51:48 +00006531}
6532
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006533unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006534 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006535 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006536
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006537 // The order of template parameters is not important here. All names
6538 // get added to the same scope.
6539 SmallVector<TemplateParameterList *, 4> ParameterLists;
6540
6541 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6542 D = TD->getTemplatedDecl();
6543
6544 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6545 ParameterLists.push_back(PSD->getTemplateParameters());
6546
6547 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6548 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6549 ParameterLists.push_back(DD->getTemplateParameterList(i));
6550
6551 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6552 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6553 ParameterLists.push_back(FTD->getTemplateParameters());
6554 }
6555 }
6556
6557 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6558 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6559 ParameterLists.push_back(TD->getTemplateParameterList(i));
6560
6561 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6562 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6563 ParameterLists.push_back(CTD->getTemplateParameters());
6564 }
6565 }
6566
6567 unsigned Count = 0;
6568 for (TemplateParameterList *Params : ParameterLists) {
6569 if (Params->size() > 0)
6570 // Ignore explicit specializations; they don't contribute to the template
6571 // depth.
6572 ++Count;
6573 for (NamedDecl *Param : *Params) {
6574 if (Param->getDeclName()) {
6575 S->AddDecl(Param);
6576 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006577 }
6578 }
6579 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006580
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006581 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006582}
6583
John McCall48871652010-08-21 09:40:31 +00006584void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006585 if (!RecordD) return;
6586 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006587 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006588 PushDeclContext(S, Record);
6589}
6590
John McCall48871652010-08-21 09:40:31 +00006591void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006592 if (!RecordD) return;
6593 PopDeclContext();
6594}
6595
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006596/// This is used to implement the constant expression evaluation part of the
6597/// attribute enable_if extension. There is nothing in standard C++ which would
6598/// require reentering parameters.
6599void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6600 if (!Param)
6601 return;
6602
6603 S->AddDecl(Param);
6604 if (Param->getDeclName())
6605 IdResolver.AddDecl(Param);
6606}
6607
Douglas Gregor4d87df52008-12-16 21:30:33 +00006608/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6609/// parsing a top-level (non-nested) C++ class, and we are now
6610/// parsing those parts of the given Method declaration that could
6611/// not be parsed earlier (C++ [class.mem]p2), such as default
6612/// arguments. This action should enter the scope of the given
6613/// Method declaration as if we had just parsed the qualified method
6614/// name. However, it should not bring the parameters into scope;
6615/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006616void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006617}
6618
6619/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6620/// C++ method declaration. We're (re-)introducing the given
6621/// function parameter into scope for use in parsing later parts of
6622/// the method declaration. For example, we could see an
6623/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006624void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006625 if (!ParamD)
6626 return;
Mike Stump11289f42009-09-09 15:08:12 +00006627
John McCall48871652010-08-21 09:40:31 +00006628 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006629
6630 // If this parameter has an unparsed default argument, clear it out
6631 // to make way for the parsed default argument.
6632 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006633 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006634
John McCall48871652010-08-21 09:40:31 +00006635 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006636 if (Param->getDeclName())
6637 IdResolver.AddDecl(Param);
6638}
6639
6640/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6641/// processing the delayed method declaration for Method. The method
6642/// declaration is now considered finished. There may be a separate
6643/// ActOnStartOfFunctionDef action later (not necessarily
6644/// immediately!) for this method, if it was also defined inside the
6645/// class body.
John McCall48871652010-08-21 09:40:31 +00006646void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006647 if (!MethodD)
6648 return;
Mike Stump11289f42009-09-09 15:08:12 +00006649
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006650 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006651
John McCall48871652010-08-21 09:40:31 +00006652 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006653
6654 // Now that we have our default arguments, check the constructor
6655 // again. It could produce additional diagnostics or affect whether
6656 // the class has implicitly-declared destructors, among other
6657 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006658 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6659 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006660
6661 // Check the default arguments, which we may have added.
6662 if (!Method->isInvalidDecl())
6663 CheckCXXDefaultArguments(Method);
6664}
6665
Douglas Gregor831c93f2008-11-05 20:51:48 +00006666/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006667/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006668/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006669/// emit diagnostics and set the invalid bit to true. In any case, the type
6670/// will be updated to reflect a well-formed type for the constructor and
6671/// returned.
6672QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006673 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006674 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006675
6676 // C++ [class.ctor]p3:
6677 // A constructor shall not be virtual (10.3) or static (9.4). A
6678 // constructor can be invoked for a const, volatile or const
6679 // volatile object. A constructor shall not be declared const,
6680 // volatile, or const volatile (9.3.2).
6681 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006682 if (!D.isInvalidType())
6683 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6684 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6685 << SourceRange(D.getIdentifierLoc());
6686 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006687 }
John McCall8e7d6562010-08-26 03:08:43 +00006688 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006689 if (!D.isInvalidType())
6690 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6691 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6692 << SourceRange(D.getIdentifierLoc());
6693 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006694 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006695 }
Mike Stump11289f42009-09-09 15:08:12 +00006696
David Majnemer03f705f2014-07-08 18:18:04 +00006697 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6698 diagnoseIgnoredQualifiers(
6699 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6700 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6701 D.getDeclSpec().getRestrictSpecLoc(),
6702 D.getDeclSpec().getAtomicSpecLoc());
6703 D.setInvalidType();
6704 }
6705
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006706 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006707 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006708 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006709 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6710 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006711 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006712 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6713 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006714 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006715 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6716 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006717 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006718 }
Mike Stump11289f42009-09-09 15:08:12 +00006719
Douglas Gregordb9d6642011-01-26 05:01:58 +00006720 // C++0x [class.ctor]p4:
6721 // A constructor shall not be declared with a ref-qualifier.
6722 if (FTI.hasRefQualifier()) {
6723 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6724 << FTI.RefQualifierIsLValueRef
6725 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6726 D.setInvalidType();
6727 }
6728
Douglas Gregor831c93f2008-11-05 20:51:48 +00006729 // Rebuild the function type "R" without any type qualifiers (in
6730 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006731 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006732 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006733 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006734 return R;
6735
6736 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6737 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006738 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006739
6740 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006741}
6742
Douglas Gregor4d87df52008-12-16 21:30:33 +00006743/// CheckConstructor - Checks a fully-formed constructor for
6744/// well-formedness, issuing any diagnostics required. Returns true if
6745/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006746void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006747 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006748 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6749 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006750 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006751
6752 // C++ [class.copy]p3:
6753 // A declaration of a constructor for a class X is ill-formed if
6754 // its first parameter is of type (optionally cv-qualified) X and
6755 // either there are no other parameters or else all other
6756 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006757 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006758 ((Constructor->getNumParams() == 1) ||
6759 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006760 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6761 Constructor->getTemplateSpecializationKind()
6762 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006763 QualType ParamType = Constructor->getParamDecl(0)->getType();
6764 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6765 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006766 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006767 const char *ConstRef
6768 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6769 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006770 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006771 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006772
6773 // FIXME: Rather that making the constructor invalid, we should endeavor
6774 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006775 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006776 }
6777 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006778}
6779
John McCalldeb646e2010-08-04 01:04:25 +00006780/// CheckDestructor - Checks a fully-formed destructor definition for
6781/// well-formedness, issuing any diagnostics required. Returns true
6782/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006783bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006784 CXXRecordDecl *RD = Destructor->getParent();
6785
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006786 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006787 SourceLocation Loc;
6788
6789 if (!Destructor->isImplicit())
6790 Loc = Destructor->getLocation();
6791 else
6792 Loc = RD->getLocation();
6793
6794 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006795 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006796 DeclarationName Name =
6797 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006798 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006799 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006800 // If there's no class-specific operator delete, look up the global
6801 // non-array delete.
6802 if (!OperatorDelete)
6803 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006804
Eli Friedmanfa0df832012-02-02 03:46:19 +00006805 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006806
6807 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006808 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006809
6810 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006811}
6812
Douglas Gregor831c93f2008-11-05 20:51:48 +00006813/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6814/// the well-formednes of the destructor declarator @p D with type @p
6815/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006816/// emit diagnostics and set the declarator to invalid. Even if this happens,
6817/// will be updated to reflect a well-formed type for the destructor and
6818/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006819QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006820 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006821 // C++ [class.dtor]p1:
6822 // [...] A typedef-name that names a class is a class-name
6823 // (7.1.3); however, a typedef-name that names a class shall not
6824 // be used as the identifier in the declarator for a destructor
6825 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006826 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006827 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006828 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006829 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006830 else if (const TemplateSpecializationType *TST =
6831 DeclaratorType->getAs<TemplateSpecializationType>())
6832 if (TST->isTypeAlias())
6833 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6834 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006835
6836 // C++ [class.dtor]p2:
6837 // A destructor is used to destroy objects of its class type. A
6838 // destructor takes no parameters, and no return type can be
6839 // specified for it (not even void). The address of a destructor
6840 // shall not be taken. A destructor shall not be static. A
6841 // destructor can be invoked for a const, volatile or const
6842 // volatile object. A destructor shall not be declared const,
6843 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006844 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006845 if (!D.isInvalidType())
6846 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6847 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006848 << SourceRange(D.getIdentifierLoc())
6849 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6850
John McCall8e7d6562010-08-26 03:08:43 +00006851 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006852 }
David Majnemer03f705f2014-07-08 18:18:04 +00006853 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006854 // Destructors don't have return types, but the parser will
6855 // happily parse something like:
6856 //
6857 // class X {
6858 // float ~X();
6859 // };
6860 //
6861 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006862 if (D.getDeclSpec().hasTypeSpecifier())
6863 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6864 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6865 << SourceRange(D.getIdentifierLoc());
6866 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6867 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6868 SourceLocation(),
6869 D.getDeclSpec().getConstSpecLoc(),
6870 D.getDeclSpec().getVolatileSpecLoc(),
6871 D.getDeclSpec().getRestrictSpecLoc(),
6872 D.getDeclSpec().getAtomicSpecLoc());
6873 D.setInvalidType();
6874 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006875 }
Mike Stump11289f42009-09-09 15:08:12 +00006876
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006877 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006878 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006879 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006880 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6881 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006882 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006883 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6884 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006885 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006886 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6887 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006888 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006889 }
6890
Douglas Gregordb9d6642011-01-26 05:01:58 +00006891 // C++0x [class.dtor]p2:
6892 // A destructor shall not be declared with a ref-qualifier.
6893 if (FTI.hasRefQualifier()) {
6894 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6895 << FTI.RefQualifierIsLValueRef
6896 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6897 D.setInvalidType();
6898 }
6899
Douglas Gregor831c93f2008-11-05 20:51:48 +00006900 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006901 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006902 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6903
6904 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006905 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006906 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006907 }
6908
Mike Stump11289f42009-09-09 15:08:12 +00006909 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006910 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006911 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006912 D.setInvalidType();
6913 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006914
6915 // Rebuild the function type "R" without any type qualifiers or
6916 // parameters (in case any of the errors above fired) and with
6917 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006918 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006919 if (!D.isInvalidType())
6920 return R;
6921
Douglas Gregor95755162010-07-01 05:10:53 +00006922 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006923 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6924 EPI.Variadic = false;
6925 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006926 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006927 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006928}
6929
Craig Toppere335f252015-10-04 04:53:55 +00006930static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00006931 if (Before.isInvalid())
6932 return;
6933 R.setBegin(Before.getBegin());
6934 if (R.getEnd().isInvalid())
6935 R.setEnd(Before.getEnd());
6936}
6937
Craig Toppere335f252015-10-04 04:53:55 +00006938static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00006939 if (After.isInvalid())
6940 return;
6941 if (R.getBegin().isInvalid())
6942 R.setBegin(After.getBegin());
6943 R.setEnd(After.getEnd());
6944}
6945
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006946/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6947/// well-formednes of the conversion function declarator @p D with
6948/// type @p R. If there are any errors in the declarator, this routine
6949/// will emit diagnostics and return true. Otherwise, it will return
6950/// false. Either way, the type @p R will be updated to reflect a
6951/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006952void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006953 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006954 // C++ [class.conv.fct]p1:
6955 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006956 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006957 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006958 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006959 if (!D.isInvalidType())
6960 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006961 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6962 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006963 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006964 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006965 }
John McCall212fa2e2010-04-13 00:04:31 +00006966
Richard Smitha865a162014-12-19 02:07:47 +00006967 TypeSourceInfo *ConvTSI = nullptr;
6968 QualType ConvType =
6969 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006970
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006971 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006972 // Conversion functions don't have return types, but the parser will
6973 // happily parse something like:
6974 //
6975 // class X {
6976 // float operator bool();
6977 // };
6978 //
6979 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006980 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6981 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6982 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006983 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006984 }
6985
John McCall212fa2e2010-04-13 00:04:31 +00006986 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6987
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006988 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006989 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006990 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6991
6992 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006993 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006994 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006995 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006996 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006997 D.setInvalidType();
6998 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006999
John McCall212fa2e2010-04-13 00:04:31 +00007000 // Diagnose "&operator bool()" and other such nonsense. This
7001 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00007002 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00007003 bool NeedsTypedef = false;
7004 SourceRange Before, After;
7005
7006 // Walk the chunks and extract information on them for our diagnostic.
7007 bool PastFunctionChunk = false;
7008 for (auto &Chunk : D.type_objects()) {
7009 switch (Chunk.Kind) {
7010 case DeclaratorChunk::Function:
7011 if (!PastFunctionChunk) {
7012 if (Chunk.Fun.HasTrailingReturnType) {
7013 TypeSourceInfo *TRT = nullptr;
7014 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7015 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7016 }
7017 PastFunctionChunk = true;
7018 break;
7019 }
7020 // Fall through.
7021 case DeclaratorChunk::Array:
7022 NeedsTypedef = true;
7023 extendRight(After, Chunk.getSourceRange());
7024 break;
7025
7026 case DeclaratorChunk::Pointer:
7027 case DeclaratorChunk::BlockPointer:
7028 case DeclaratorChunk::Reference:
7029 case DeclaratorChunk::MemberPointer:
7030 extendLeft(Before, Chunk.getSourceRange());
7031 break;
7032
7033 case DeclaratorChunk::Paren:
7034 extendLeft(Before, Chunk.Loc);
7035 extendRight(After, Chunk.EndLoc);
7036 break;
7037 }
7038 }
7039
7040 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7041 After.isValid() ? After.getBegin() :
7042 D.getIdentifierLoc();
7043 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7044 DB << Before << After;
7045
7046 if (!NeedsTypedef) {
7047 DB << /*don't need a typedef*/0;
7048
7049 // If we can provide a correct fix-it hint, do so.
7050 if (After.isInvalid() && ConvTSI) {
7051 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00007052 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00007053 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7054 << FixItHint::CreateInsertionFromRange(
7055 InsertLoc, CharSourceRange::getTokenRange(Before))
7056 << FixItHint::CreateRemoval(Before);
7057 }
7058 } else if (!Proto->getReturnType()->isDependentType()) {
7059 DB << /*typedef*/1 << Proto->getReturnType();
7060 } else if (getLangOpts().CPlusPlus11) {
7061 DB << /*alias template*/2 << Proto->getReturnType();
7062 } else {
7063 DB << /*might not be fixable*/3;
7064 }
7065
7066 // Recover by incorporating the other type chunks into the result type.
7067 // Note, this does *not* change the name of the function. This is compatible
7068 // with the GCC extension:
7069 // struct S { &operator int(); } s;
7070 // int &r = s.operator int(); // ok in GCC
7071 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007072 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007073 }
7074
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007075 // C++ [class.conv.fct]p4:
7076 // The conversion-type-id shall not represent a function type nor
7077 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007078 if (ConvType->isArrayType()) {
7079 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7080 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007081 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007082 } else if (ConvType->isFunctionType()) {
7083 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7084 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007085 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007086 }
7087
7088 // Rebuild the function type "R" without any parameters (in case any
7089 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007090 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007091 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007092 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007093
Douglas Gregor5fb53972009-01-14 15:45:31 +00007094 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007095 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007096 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007097 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007098 diag::warn_cxx98_compat_explicit_conversion_functions :
7099 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007100 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007101}
7102
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007103/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7104/// the declaration of the given C++ conversion function. This routine
7105/// is responsible for recording the conversion function in the C++
7106/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007107Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007108 assert(Conversion && "Expected to receive a conversion function declaration");
7109
Douglas Gregor4287b372008-12-12 08:25:50 +00007110 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007111
7112 // Make sure we aren't redeclaring the conversion function.
7113 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007114
7115 // C++ [class.conv.fct]p1:
7116 // [...] A conversion function is never used to convert a
7117 // (possibly cv-qualified) object to the (possibly cv-qualified)
7118 // same object type (or a reference to it), to a (possibly
7119 // cv-qualified) base class of that type (or a reference to it),
7120 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007121 // FIXME: Suppress this warning if the conversion function ends up being a
7122 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007123 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007124 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007125 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007126 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007127 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7128 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007129 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007130 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007131 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7132 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007133 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007134 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00007135 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007136 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007137 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007138 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007139 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007140 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007141 }
7142
Douglas Gregor457104e2010-09-29 04:25:11 +00007143 if (FunctionTemplateDecl *ConversionTemplate
7144 = Conversion->getDescribedFunctionTemplate())
7145 return ConversionTemplate;
7146
John McCall48871652010-08-21 09:40:31 +00007147 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007148}
7149
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007150//===----------------------------------------------------------------------===//
7151// Namespace Handling
7152//===----------------------------------------------------------------------===//
7153
Richard Smith45bb8852012-10-04 22:13:39 +00007154/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7155/// reopened.
7156static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7157 SourceLocation Loc,
7158 IdentifierInfo *II, bool *IsInline,
7159 NamespaceDecl *PrevNS) {
7160 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007161
Richard Smithf501cc32012-10-05 01:46:25 +00007162 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7163 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7164 // inline namespaces, with the intention of bringing names into namespace std.
7165 //
7166 // We support this just well enough to get that case working; this is not
7167 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007168 if (*IsInline && II && II->getName().startswith("__atomic") &&
7169 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007170 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007171 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7172 NS = NS->getPreviousDecl())
7173 NS->setInline(*IsInline);
7174 // Patch up the lookup table for the containing namespace. This isn't really
7175 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007176 for (auto *I : PrevNS->decls())
7177 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007178 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7179 return;
7180 }
7181
7182 if (PrevNS->isInline())
7183 // The user probably just forgot the 'inline', so suggest that it
7184 // be added back.
7185 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7186 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7187 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007188 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007189
7190 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7191 *IsInline = PrevNS->isInline();
7192}
John McCallb1be5232010-08-26 09:15:37 +00007193
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007194/// ActOnStartNamespaceDef - This is called at the start of a namespace
7195/// definition.
John McCall48871652010-08-21 09:40:31 +00007196Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007197 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007198 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007199 SourceLocation IdentLoc,
7200 IdentifierInfo *II,
7201 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00007202 AttributeList *AttrList,
7203 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007204 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7205 // For anonymous namespace, take the location of the left brace.
7206 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007207 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007208 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007209 bool IsStd = false;
7210 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007211 Scope *DeclRegionScope = NamespcScope->getParent();
7212
Craig Topperc3ec1492014-05-26 06:22:03 +00007213 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007214 if (II) {
7215 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007216 // The identifier in an original-namespace-definition shall not
7217 // have been previously defined in the declarative region in
7218 // which the original-namespace-definition appears. The
7219 // identifier in an original-namespace-definition is the name of
7220 // the namespace. Subsequently in that declarative region, it is
7221 // treated as an original-namespace-name.
7222 //
7223 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00007224 // look through using directives, just look for any ordinary names
7225 // as if by qualified name lookup.
7226 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7227 LookupQualifiedName(R, CurContext->getRedeclContext());
7228 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
Douglas Gregore57e7522012-01-07 09:11:48 +00007229 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00007230
Douglas Gregore57e7522012-01-07 09:11:48 +00007231 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007232 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007233 if (IsInline != PrevNS->isInline())
7234 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7235 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007236 } else if (PrevDecl) {
7237 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007238 Diag(Loc, diag::err_redefinition_different_kind)
7239 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007240 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007241 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007242 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007243 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007244 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007245 // This is the first "real" definition of the namespace "std", so update
7246 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007247 PrevNS = getStdNamespace();
7248 IsStd = true;
7249 AddToKnown = !IsInline;
7250 } else {
7251 // We've seen this namespace for the first time.
7252 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007253 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007254 } else {
John McCall4fa53422009-10-01 00:25:31 +00007255 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007256
7257 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007258 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007259 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007260 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007261 } else {
7262 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007263 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007264 }
7265
Richard Smith45bb8852012-10-04 22:13:39 +00007266 if (PrevNS && IsInline != PrevNS->isInline())
7267 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7268 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007269 }
7270
7271 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7272 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007273 if (IsInvalid)
7274 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007275
7276 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007277
Douglas Gregore57e7522012-01-07 09:11:48 +00007278 // FIXME: Should we be merging attributes?
7279 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007280 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007281
7282 if (IsStd)
7283 StdNamespace = Namespc;
7284 if (AddToKnown)
7285 KnownNamespaces[Namespc] = false;
7286
7287 if (II) {
7288 PushOnScopeChains(Namespc, DeclRegionScope);
7289 } else {
7290 // Link the anonymous namespace into its parent.
7291 DeclContext *Parent = CurContext->getRedeclContext();
7292 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7293 TU->setAnonymousNamespace(Namespc);
7294 } else {
7295 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007296 }
John McCall4fa53422009-10-01 00:25:31 +00007297
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007298 CurContext->addDecl(Namespc);
7299
John McCall4fa53422009-10-01 00:25:31 +00007300 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7301 // behaves as if it were replaced by
7302 // namespace unique { /* empty body */ }
7303 // using namespace unique;
7304 // namespace unique { namespace-body }
7305 // where all occurrences of 'unique' in a translation unit are
7306 // replaced by the same identifier and this identifier differs
7307 // from all other identifiers in the entire program.
7308
7309 // We just create the namespace with an empty name and then add an
7310 // implicit using declaration, just like the standard suggests.
7311 //
7312 // CodeGen enforces the "universally unique" aspect by giving all
7313 // declarations semantically contained within an anonymous
7314 // namespace internal linkage.
7315
Douglas Gregore57e7522012-01-07 09:11:48 +00007316 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00007317 UD = UsingDirectiveDecl::Create(Context, Parent,
7318 /* 'using' */ LBrace,
7319 /* 'namespace' */ SourceLocation(),
7320 /* qualifier */ NestedNameSpecifierLoc(),
7321 /* identifier */ SourceLocation(),
7322 Namespc,
7323 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007324 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007325 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007326 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007327 }
7328
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007329 ActOnDocumentableDecl(Namespc);
7330
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007331 // Although we could have an invalid decl (i.e. the namespace name is a
7332 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007333 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7334 // for the namespace has the declarations that showed up in that particular
7335 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007336 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007337 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007338}
7339
Sebastian Redla6602e92009-11-23 15:34:23 +00007340/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7341/// is a namespace alias, returns the namespace it points to.
7342static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7343 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7344 return AD->getNamespace();
7345 return dyn_cast_or_null<NamespaceDecl>(D);
7346}
7347
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007348/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7349/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007350void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007351 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7352 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007353 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007354 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007355 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007356 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007357}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007358
John McCall28a0cf72010-08-25 07:42:41 +00007359CXXRecordDecl *Sema::getStdBadAlloc() const {
7360 return cast_or_null<CXXRecordDecl>(
7361 StdBadAlloc.get(Context.getExternalSource()));
7362}
7363
7364NamespaceDecl *Sema::getStdNamespace() const {
7365 return cast_or_null<NamespaceDecl>(
7366 StdNamespace.get(Context.getExternalSource()));
7367}
7368
Douglas Gregorcdf87022010-06-29 17:53:46 +00007369/// \brief Retrieve the special "std" namespace, which may require us to
7370/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007371NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007372 if (!StdNamespace) {
7373 // The "std" namespace has not yet been defined, so build one implicitly.
7374 StdNamespace = NamespaceDecl::Create(Context,
7375 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007376 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007377 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007378 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007379 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007380 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007381 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007382
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007383 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007384}
7385
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007386bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007387 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007388 "Looking for std::initializer_list outside of C++.");
7389
7390 // We're looking for implicit instantiations of
7391 // template <typename E> class std::initializer_list.
7392
7393 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7394 return false;
7395
Craig Topperc3ec1492014-05-26 06:22:03 +00007396 ClassTemplateDecl *Template = nullptr;
7397 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007398
Sebastian Redl43144e72012-01-17 22:49:58 +00007399 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007400
Sebastian Redl43144e72012-01-17 22:49:58 +00007401 ClassTemplateSpecializationDecl *Specialization =
7402 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7403 if (!Specialization)
7404 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007405
Sebastian Redl43144e72012-01-17 22:49:58 +00007406 Template = Specialization->getSpecializedTemplate();
7407 Arguments = Specialization->getTemplateArgs().data();
7408 } else if (const TemplateSpecializationType *TST =
7409 Ty->getAs<TemplateSpecializationType>()) {
7410 Template = dyn_cast_or_null<ClassTemplateDecl>(
7411 TST->getTemplateName().getAsTemplateDecl());
7412 Arguments = TST->getArgs();
7413 }
7414 if (!Template)
7415 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007416
7417 if (!StdInitializerList) {
7418 // Haven't recognized std::initializer_list yet, maybe this is it.
7419 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7420 if (TemplateClass->getIdentifier() !=
7421 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007422 !getStdNamespace()->InEnclosingNamespaceSetOf(
7423 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007424 return false;
7425 // This is a template called std::initializer_list, but is it the right
7426 // template?
7427 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007428 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007429 return false;
7430 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7431 return false;
7432
7433 // It's the right template.
7434 StdInitializerList = Template;
7435 }
7436
Richard Smith7d7dee72015-02-24 03:30:14 +00007437 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007438 return false;
7439
7440 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007441 if (Element)
7442 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007443 return true;
7444}
7445
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007446static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7447 NamespaceDecl *Std = S.getStdNamespace();
7448 if (!Std) {
7449 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007450 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007451 }
7452
7453 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7454 Loc, Sema::LookupOrdinaryName);
7455 if (!S.LookupQualifiedName(Result, Std)) {
7456 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007457 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007458 }
7459 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7460 if (!Template) {
7461 Result.suppressDiagnostics();
7462 // We found something weird. Complain about the first thing we found.
7463 NamedDecl *Found = *Result.begin();
7464 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007465 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007466 }
7467
7468 // We found some template called std::initializer_list. Now verify that it's
7469 // correct.
7470 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007471 if (Params->getMinRequiredArguments() != 1 ||
7472 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007473 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007474 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007475 }
7476
7477 return Template;
7478}
7479
7480QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7481 if (!StdInitializerList) {
7482 StdInitializerList = LookupStdInitializerList(*this, Loc);
7483 if (!StdInitializerList)
7484 return QualType();
7485 }
7486
7487 TemplateArgumentListInfo Args(Loc, Loc);
7488 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7489 Context.getTrivialTypeSourceInfo(Element,
7490 Loc)));
7491 return Context.getCanonicalType(
7492 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7493}
7494
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007495bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7496 // C++ [dcl.init.list]p2:
7497 // A constructor is an initializer-list constructor if its first parameter
7498 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7499 // std::initializer_list<E> for some type E, and either there are no other
7500 // parameters or else all other parameters have default arguments.
7501 if (Ctor->getNumParams() < 1 ||
7502 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7503 return false;
7504
7505 QualType ArgType = Ctor->getParamDecl(0)->getType();
7506 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7507 ArgType = RT->getPointeeType().getUnqualifiedType();
7508
Craig Topperc3ec1492014-05-26 06:22:03 +00007509 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007510}
7511
Douglas Gregora172e082011-03-26 22:25:30 +00007512/// \brief Determine whether a using statement is in a context where it will be
7513/// apply in all contexts.
7514static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7515 switch (CurContext->getDeclKind()) {
7516 case Decl::TranslationUnit:
7517 return true;
7518 case Decl::LinkageSpec:
7519 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7520 default:
7521 return false;
7522 }
7523}
7524
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007525namespace {
7526
7527// Callback to only accept typo corrections that are namespaces.
7528class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007529public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007530 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007531 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007532 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007533 return false;
7534 }
7535};
7536
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007537}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007538
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007539static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7540 CXXScopeSpec &SS,
7541 SourceLocation IdentLoc,
7542 IdentifierInfo *Ident) {
7543 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007544 if (TypoCorrection Corrected =
7545 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7546 llvm::make_unique<NamespaceValidatorCCC>(),
7547 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007548 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007549 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7550 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007551 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007552 S.diagnoseTypo(Corrected,
7553 S.PDiag(diag::err_using_directive_member_suggest)
7554 << Ident << DC << DroppedSpecifier << SS.getRange(),
7555 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007556 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007557 S.diagnoseTypo(Corrected,
7558 S.PDiag(diag::err_using_directive_suggest) << Ident,
7559 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007560 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007561 R.addDecl(Corrected.getCorrectionDecl());
7562 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007563 }
7564 return false;
7565}
7566
John McCall48871652010-08-21 09:40:31 +00007567Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007568 SourceLocation UsingLoc,
7569 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007570 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007571 SourceLocation IdentLoc,
7572 IdentifierInfo *NamespcName,
7573 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007574 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7575 assert(NamespcName && "Invalid NamespcName.");
7576 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007577
7578 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00007579 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00007580 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007581 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007582
Craig Topperc3ec1492014-05-26 06:22:03 +00007583 UsingDirectiveDecl *UDir = nullptr;
7584 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007585 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007586 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007587
Douglas Gregor34074322009-01-14 22:20:51 +00007588 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007589 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7590 LookupParsedName(R, S, &SS);
7591 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007592 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007593
Douglas Gregorcdf87022010-06-29 17:53:46 +00007594 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007595 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007596 // Allow "using namespace std;" or "using namespace ::std;" even if
7597 // "std" hasn't been defined yet, for GCC compatibility.
7598 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7599 NamespcName->isStr("std")) {
7600 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007601 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007602 R.resolveKind();
7603 }
7604 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007605 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007606 }
7607
John McCall9f3059a2009-10-09 21:13:30 +00007608 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007609 NamedDecl *Named = R.getFoundDecl();
7610 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7611 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007612
Nico Riecke50e59a2014-11-24 17:29:52 +00007613 // The use of a nested name specifier may trigger deprecation warnings.
7614 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007615
Douglas Gregor889ceb72009-02-03 19:21:40 +00007616 // C++ [namespace.udir]p1:
7617 // A using-directive specifies that the names in the nominated
7618 // namespace can be used in the scope in which the
7619 // using-directive appears after the using-directive. During
7620 // unqualified name lookup (3.4.1), the names appear as if they
7621 // were declared in the nearest enclosing namespace which
7622 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007623 // namespace. [Note: in this context, "contains" means "contains
7624 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007625
7626 // Find enclosing context containing both using-directive and
7627 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007628 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007629 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7630 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7631 CommonAncestor = CommonAncestor->getParent();
7632
Sebastian Redla6602e92009-11-23 15:34:23 +00007633 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007634 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007635 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007636
Douglas Gregora172e082011-03-26 22:25:30 +00007637 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007638 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007639 Diag(IdentLoc, diag::warn_using_directive_in_header);
7640 }
7641
Douglas Gregor889ceb72009-02-03 19:21:40 +00007642 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007643 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007644 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007645 }
7646
Richard Smith54ecd982013-02-20 19:22:51 +00007647 if (UDir)
7648 ProcessDeclAttributeList(S, UDir, AttrList);
7649
John McCall48871652010-08-21 09:40:31 +00007650 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007651}
7652
7653void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007654 // If the scope has an associated entity and the using directive is at
7655 // namespace or translation unit scope, add the UsingDirectiveDecl into
7656 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007657 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007658 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007659 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007660 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007661 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007662 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007663 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007664}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007665
Douglas Gregorfec52632009-06-20 00:51:54 +00007666
John McCall48871652010-08-21 09:40:31 +00007667Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007668 AccessSpecifier AS,
7669 bool HasUsingKeyword,
7670 SourceLocation UsingLoc,
7671 CXXScopeSpec &SS,
7672 UnqualifiedId &Name,
7673 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007674 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007675 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007676 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007677
Douglas Gregor220f4272009-11-04 16:30:06 +00007678 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007679 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007680 case UnqualifiedId::IK_Identifier:
7681 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007682 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007683 case UnqualifiedId::IK_ConversionFunctionId:
7684 break;
7685
7686 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007687 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007688 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007689 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007690 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007691 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007692 diag::err_using_decl_constructor)
7693 << SS.getRange();
7694
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007695 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007696
Craig Topperc3ec1492014-05-26 06:22:03 +00007697 return nullptr;
7698
Douglas Gregor220f4272009-11-04 16:30:06 +00007699 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007700 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007701 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007702 return nullptr;
7703
Douglas Gregor220f4272009-11-04 16:30:06 +00007704 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007705 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007706 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007707 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007708 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007709
7710 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7711 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007712 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007713 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007714
Richard Smithc2bc61b2013-03-18 21:12:30 +00007715 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007716 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007717 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007718 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7719 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007720 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007721 }
7722
Douglas Gregorc4356532010-12-16 00:46:58 +00007723 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7724 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007725 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007726
John McCall3f746822009-11-17 05:59:44 +00007727 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007728 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007729 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007730 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007731 if (UD)
7732 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007733
John McCall48871652010-08-21 09:40:31 +00007734 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007735}
7736
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007737/// \brief Determine whether a using declaration considers the given
7738/// declarations as "equivalent", e.g., if they are redeclarations of
7739/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007740static bool
7741IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7742 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007743 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007744
Richard Smithdda56e42011-04-15 14:24:37 +00007745 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007746 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007747 return Context.hasSameType(TD1->getUnderlyingType(),
7748 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007749
7750 return false;
7751}
7752
7753
John McCall84d87672009-12-10 09:41:52 +00007754/// Determines whether to create a using shadow decl for a particular
7755/// decl, given the set of decls existing prior to this using lookup.
7756bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007757 const LookupResult &Previous,
7758 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007759 // Diagnose finding a decl which is not from a base class of the
7760 // current class. We do this now because there are cases where this
7761 // function will silently decide not to build a shadow decl, which
7762 // will pre-empt further diagnostics.
7763 //
7764 // We don't need to do this in C++0x because we do the check once on
7765 // the qualifier.
7766 //
7767 // FIXME: diagnose the following if we care enough:
7768 // struct A { int foo; };
7769 // struct B : A { using A::foo; };
7770 // template <class T> struct C : A {};
7771 // template <class T> struct D : C<T> { using B::foo; } // <---
7772 // This is invalid (during instantiation) in C++03 because B::foo
7773 // resolves to the using decl in B, which is not a base class of D<T>.
7774 // We can't diagnose it immediately because C<T> is an unknown
7775 // specialization. The UsingShadowDecl in D<T> then points directly
7776 // to A::foo, which will look well-formed when we instantiate.
7777 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007778 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007779 DeclContext *OrigDC = Orig->getDeclContext();
7780
7781 // Handle enums and anonymous structs.
7782 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7783 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7784 while (OrigRec->isAnonymousStructOrUnion())
7785 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7786
7787 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7788 if (OrigDC == CurContext) {
7789 Diag(Using->getLocation(),
7790 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007791 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007792 Diag(Orig->getLocation(), diag::note_using_decl_target);
7793 return true;
7794 }
7795
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007796 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007797 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007798 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007799 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007800 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007801 Diag(Orig->getLocation(), diag::note_using_decl_target);
7802 return true;
7803 }
7804 }
7805
7806 if (Previous.empty()) return false;
7807
7808 NamedDecl *Target = Orig;
7809 if (isa<UsingShadowDecl>(Target))
7810 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7811
John McCalla17e83e2009-12-11 02:33:26 +00007812 // If the target happens to be one of the previous declarations, we
7813 // don't have a conflict.
7814 //
7815 // FIXME: but we might be increasing its access, in which case we
7816 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007817 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007818 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007819 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7820 I != E; ++I) {
7821 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007822 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7823 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7824 PrevShadow = Shadow;
7825 FoundEquivalentDecl = true;
7826 }
John McCalla17e83e2009-12-11 02:33:26 +00007827
Richard Smithf091e122015-09-15 01:28:55 +00007828 if (isVisible(D))
7829 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00007830 }
7831
Richard Smithfd8634a2013-10-23 02:17:46 +00007832 if (FoundEquivalentDecl)
7833 return false;
7834
Alp Tokera2794f92014-01-22 07:29:52 +00007835 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007836 NamedDecl *OldDecl = nullptr;
7837 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7838 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007839 case Ovl_Overload:
7840 return false;
7841
7842 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007843 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007844 break;
Richard Smith18819302014-02-06 01:31:33 +00007845
John McCall84d87672009-12-10 09:41:52 +00007846 // We found a decl with the exact signature.
7847 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007848 // If we're in a record, we want to hide the target, so we
7849 // return true (without a diagnostic) to tell the caller not to
7850 // build a shadow decl.
7851 if (CurContext->isRecord())
7852 return true;
7853
7854 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007855 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007856 break;
7857 }
7858
7859 Diag(Target->getLocation(), diag::note_using_decl_target);
7860 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7861 return true;
7862 }
7863
7864 // Target is not a function.
7865
John McCall84d87672009-12-10 09:41:52 +00007866 if (isa<TagDecl>(Target)) {
7867 // No conflict between a tag and a non-tag.
7868 if (!Tag) return false;
7869
John McCalle29c5cd2009-12-10 19:51:03 +00007870 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007871 Diag(Target->getLocation(), diag::note_using_decl_target);
7872 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7873 return true;
7874 }
7875
7876 // No conflict between a tag and a non-tag.
7877 if (!NonTag) return false;
7878
John McCalle29c5cd2009-12-10 19:51:03 +00007879 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007880 Diag(Target->getLocation(), diag::note_using_decl_target);
7881 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7882 return true;
7883}
7884
John McCall3f746822009-11-17 05:59:44 +00007885/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007886UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007887 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007888 NamedDecl *Orig,
7889 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007890
7891 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007892 NamedDecl *Target = Orig;
7893 if (isa<UsingShadowDecl>(Target)) {
7894 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7895 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007896 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007897
John McCall3f746822009-11-17 05:59:44 +00007898 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007899 = UsingShadowDecl::Create(Context, CurContext,
7900 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007901 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007902
Douglas Gregor457104e2010-09-29 04:25:11 +00007903 Shadow->setAccess(UD->getAccess());
7904 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7905 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007906
7907 Shadow->setPreviousDecl(PrevDecl);
7908
John McCall3f746822009-11-17 05:59:44 +00007909 if (S)
John McCall3969e302009-12-08 07:46:18 +00007910 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007911 else
John McCall3969e302009-12-08 07:46:18 +00007912 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007913
John McCall3969e302009-12-08 07:46:18 +00007914
John McCall84d87672009-12-10 09:41:52 +00007915 return Shadow;
7916}
John McCall3969e302009-12-08 07:46:18 +00007917
John McCall84d87672009-12-10 09:41:52 +00007918/// Hides a using shadow declaration. This is required by the current
7919/// using-decl implementation when a resolvable using declaration in a
7920/// class is followed by a declaration which would hide or override
7921/// one or more of the using decl's targets; for example:
7922///
7923/// struct Base { void foo(int); };
7924/// struct Derived : Base {
7925/// using Base::foo;
7926/// void foo(int);
7927/// };
7928///
7929/// The governing language is C++03 [namespace.udecl]p12:
7930///
7931/// When a using-declaration brings names from a base class into a
7932/// derived class scope, member functions in the derived class
7933/// override and/or hide member functions with the same name and
7934/// parameter types in a base class (rather than conflicting).
7935///
7936/// There are two ways to implement this:
7937/// (1) optimistically create shadow decls when they're not hidden
7938/// by existing declarations, or
7939/// (2) don't create any shadow decls (or at least don't make them
7940/// visible) until we've fully parsed/instantiated the class.
7941/// The problem with (1) is that we might have to retroactively remove
7942/// a shadow decl, which requires several O(n) operations because the
7943/// decl structures are (very reasonably) not designed for removal.
7944/// (2) avoids this but is very fiddly and phase-dependent.
7945void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007946 if (Shadow->getDeclName().getNameKind() ==
7947 DeclarationName::CXXConversionFunctionName)
7948 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7949
John McCall84d87672009-12-10 09:41:52 +00007950 // Remove it from the DeclContext...
7951 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007952
John McCall84d87672009-12-10 09:41:52 +00007953 // ...and the scope, if applicable...
7954 if (S) {
John McCall48871652010-08-21 09:40:31 +00007955 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007956 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007957 }
7958
John McCall84d87672009-12-10 09:41:52 +00007959 // ...and the using decl.
7960 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7961
7962 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007963 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007964}
7965
Richard Smith09d5b3a2014-05-01 00:35:04 +00007966/// Find the base specifier for a base class with the given type.
7967static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7968 QualType DesiredBase,
7969 bool &AnyDependentBases) {
7970 // Check whether the named type is a direct base class.
7971 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7972 for (auto &Base : Derived->bases()) {
7973 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7974 if (CanonicalDesiredBase == BaseType)
7975 return &Base;
7976 if (BaseType->isDependentType())
7977 AnyDependentBases = true;
7978 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007979 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007980}
7981
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007982namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007983class UsingValidatorCCC : public CorrectionCandidateCallback {
7984public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007985 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007986 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007987 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007988 IsInstantiation(IsInstantiation), OldNNS(NNS),
7989 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007990
Craig Toppera798a9d2014-03-02 09:32:10 +00007991 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007992 NamedDecl *ND = Candidate.getCorrectionDecl();
7993
7994 // Keywords are not valid here.
7995 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007996 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007997
7998 // Completely unqualified names are invalid for a 'using' declaration.
7999 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8000 return false;
8001
Richard Smith09d5b3a2014-05-01 00:35:04 +00008002 if (RequireMemberOf) {
8003 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8004 if (FoundRecord && FoundRecord->isInjectedClassName()) {
8005 // No-one ever wants a using-declaration to name an injected-class-name
8006 // of a base class, unless they're declaring an inheriting constructor.
8007 ASTContext &Ctx = ND->getASTContext();
8008 if (!Ctx.getLangOpts().CPlusPlus11)
8009 return false;
8010 QualType FoundType = Ctx.getRecordType(FoundRecord);
8011
8012 // Check that the injected-class-name is named as a member of its own
8013 // type; we don't want to suggest 'using Derived::Base;', since that
8014 // means something else.
8015 NestedNameSpecifier *Specifier =
8016 Candidate.WillReplaceSpecifier()
8017 ? Candidate.getCorrectionSpecifier()
8018 : OldNNS;
8019 if (!Specifier->getAsType() ||
8020 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8021 return false;
8022
8023 // Check that this inheriting constructor declaration actually names a
8024 // direct base class of the current class.
8025 bool AnyDependentBases = false;
8026 if (!findDirectBaseWithType(RequireMemberOf,
8027 Ctx.getRecordType(FoundRecord),
8028 AnyDependentBases) &&
8029 !AnyDependentBases)
8030 return false;
8031 } else {
8032 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8033 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8034 return false;
8035
8036 // FIXME: Check that the base class member is accessible?
8037 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00008038 } else {
8039 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8040 if (FoundRecord && FoundRecord->isInjectedClassName())
8041 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008042 }
8043
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008044 if (isa<TypeDecl>(ND))
8045 return HasTypenameKeyword || !IsInstantiation;
8046
8047 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008048 }
8049
8050private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008051 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008052 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008053 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00008054 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008055};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008056} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008057
John McCalle61f2ba2009-11-18 02:36:19 +00008058/// Builds a using declaration.
8059///
8060/// \param IsInstantiation - Whether this call arises from an
8061/// instantiation of an unresolved using declaration. We treat
8062/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008063NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8064 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008065 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008066 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008067 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008068 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008069 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008070 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008071 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008072 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008073 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008074
Anders Carlssonf038fc22009-08-28 05:49:21 +00008075 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008076
Anders Carlsson59140b32009-08-28 03:16:11 +00008077 if (SS.isEmpty()) {
8078 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008079 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008080 }
Mike Stump11289f42009-09-09 15:08:12 +00008081
John McCall84d87672009-12-10 09:41:52 +00008082 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008083 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008084 ForRedeclaration);
8085 Previous.setHideTags(false);
8086 if (S) {
8087 LookupName(Previous, S);
8088
8089 // It is really dumb that we have to do this.
8090 LookupResult::Filter F = Previous.makeFilter();
8091 while (F.hasNext()) {
8092 NamedDecl *D = F.next();
8093 if (!isDeclInScope(D, CurContext, S))
8094 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008095 // If we found a local extern declaration that's not ordinarily visible,
8096 // and this declaration is being added to a non-block scope, ignore it.
8097 // We're only checking for scope conflicts here, not also for violations
8098 // of the linkage rules.
8099 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8100 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8101 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008102 }
8103 F.done();
8104 } else {
8105 assert(IsInstantiation && "no scope in non-instantiation");
8106 assert(CurContext->isRecord() && "scope not record in instantiation");
8107 LookupQualifiedName(Previous, CurContext);
8108 }
8109
John McCall84d87672009-12-10 09:41:52 +00008110 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008111 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8112 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008113 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008114
8115 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008116 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008117 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008118
John McCall84c16cf2009-11-12 03:15:40 +00008119 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008120 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008121 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008122 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008123 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008124 // FIXME: not all declaration name kinds are legal here
8125 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8126 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008127 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008128 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008129 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008130 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8131 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008132 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008133 D->setAccess(AS);
8134 CurContext->addDecl(D);
8135 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008136 }
John McCallb96ec562009-12-04 22:46:56 +00008137
Richard Smith09d5b3a2014-05-01 00:35:04 +00008138 auto Build = [&](bool Invalid) {
8139 UsingDecl *UD =
8140 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8141 HasTypenameKeyword);
8142 UD->setAccess(AS);
8143 CurContext->addDecl(UD);
8144 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008145 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008146 };
8147 auto BuildInvalid = [&]{ return Build(true); };
8148 auto BuildValid = [&]{ return Build(false); };
8149
8150 if (RequireCompleteDeclContext(SS, LookupContext))
8151 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008152
Richard Smith78163e22015-04-01 19:31:06 +00008153 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008154 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008155
John McCall3969e302009-12-08 07:46:18 +00008156 // Unlike most lookups, we don't always want to hide tag
8157 // declarations: tag names are visible through the using declaration
8158 // even if hidden by ordinary names, *except* in a dependent context
8159 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008160 if (!IsInstantiation)
8161 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008162
John McCall5dadb652012-04-07 03:04:20 +00008163 // For the purposes of this lookup, we have a base object type
8164 // equal to that of the current context.
8165 if (CurContext->isRecord()) {
8166 R.setBaseObjectType(
8167 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8168 }
8169
John McCall27b18f82009-11-17 02:14:36 +00008170 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008171
Richard Smith78163e22015-04-01 19:31:06 +00008172 // Try to correct typos if possible. If constructor name lookup finds no
8173 // results, that means the named class has no explicit constructors, and we
8174 // suppressed declaring implicit ones (probably because it's dependent or
8175 // invalid).
8176 if (R.empty() &&
8177 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008178 if (TypoCorrection Corrected = CorrectTypo(
8179 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8180 llvm::make_unique<UsingValidatorCCC>(
8181 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8182 dyn_cast<CXXRecordDecl>(CurContext)),
8183 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008184 // We reject any correction for which ND would be NULL.
8185 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008186
Richard Smithf9b15102013-08-17 00:46:16 +00008187 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008188 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008189 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8190 << NameInfo.getName() << LookupContext << 0
8191 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008192
8193 // If we corrected to an inheriting constructor, handle it as one.
8194 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8195 if (RD && RD->isInjectedClassName()) {
8196 // Fix up the information we'll use to build the using declaration.
8197 if (Corrected.WillReplaceSpecifier()) {
8198 NestedNameSpecifierLocBuilder Builder;
8199 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8200 QualifierLoc.getSourceRange());
8201 QualifierLoc = Builder.getWithLocInContext(Context);
8202 }
8203
8204 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8205 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008206 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00008207 for (auto *Ctor : LookupConstructors(RD))
8208 R.addDecl(Ctor);
8209 } else {
8210 // FIXME: Pick up all the declarations if we found an overloaded function.
8211 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008212 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008213 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008214 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008215 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008216 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008217 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008218 }
8219
Richard Smith09d5b3a2014-05-01 00:35:04 +00008220 if (R.isAmbiguous())
8221 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008222
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008223 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008224 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008225 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008226 Diag(IdentLoc, diag::err_using_typename_non_type);
8227 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8228 Diag((*I)->getUnderlyingDecl()->getLocation(),
8229 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008230 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008231 }
8232 } else {
8233 // If we asked for a non-typename and we got a type, error out,
8234 // but only if this is an instantiation of an unresolved using
8235 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008236 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008237 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8238 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008239 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008240 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008241 }
8242
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008243 // C++0x N2914 [namespace.udecl]p6:
8244 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008245 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008246 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8247 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008248 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008249 }
Mike Stump11289f42009-09-09 15:08:12 +00008250
Richard Smith09d5b3a2014-05-01 00:35:04 +00008251 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00008252
8253 // The normal rules do not apply to inheriting constructor declarations.
8254 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8255 // Suppress access diagnostics; the access check is instead performed at the
8256 // point of use for an inheriting constructor.
8257 R.suppressDiagnostics();
8258 CheckInheritingConstructorUsingDecl(UD);
8259 return UD;
8260 }
8261
8262 // Otherwise, look up the target name.
8263
John McCall84d87672009-12-10 09:41:52 +00008264 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008265 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008266 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8267 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008268 }
John McCall3f746822009-11-17 05:59:44 +00008269
8270 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008271}
8272
Sebastian Redl08905022011-02-05 19:23:19 +00008273/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008274bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008275 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008276
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008277 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008278 assert(SourceType &&
8279 "Using decl naming constructor doesn't have type in scope spec.");
8280 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8281
8282 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008283 bool AnyDependentBases = false;
8284 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8285 AnyDependentBases);
8286 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008287 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008288 diag::err_using_decl_constructor_not_in_direct_base)
8289 << UD->getNameInfo().getSourceRange()
8290 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008291 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008292 return true;
8293 }
8294
Richard Smith09d5b3a2014-05-01 00:35:04 +00008295 if (Base)
8296 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008297
8298 return false;
8299}
8300
John McCall84d87672009-12-10 09:41:52 +00008301/// Checks that the given using declaration is not an invalid
8302/// redeclaration. Note that this is checking only for the using decl
8303/// itself, not for any ill-formedness among the UsingShadowDecls.
8304bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008305 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008306 const CXXScopeSpec &SS,
8307 SourceLocation NameLoc,
8308 const LookupResult &Prev) {
8309 // C++03 [namespace.udecl]p8:
8310 // C++0x [namespace.udecl]p10:
8311 // A using-declaration is a declaration and can therefore be used
8312 // repeatedly where (and only where) multiple declarations are
8313 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008314 //
John McCall032092f2010-11-29 18:01:58 +00008315 // That's in non-member contexts.
8316 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008317 return false;
8318
Aaron Ballman4a979672014-01-03 13:56:08 +00008319 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008320
8321 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8322 NamedDecl *D = *I;
8323
8324 bool DTypename;
8325 NestedNameSpecifier *DQual;
8326 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008327 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008328 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008329 } else if (UnresolvedUsingValueDecl *UD
8330 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8331 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008332 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008333 } else if (UnresolvedUsingTypenameDecl *UD
8334 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8335 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008336 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008337 } else continue;
8338
8339 // using decls differ if one says 'typename' and the other doesn't.
8340 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008341 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008342
8343 // using decls differ if they name different scopes (but note that
8344 // template instantiation can cause this check to trigger when it
8345 // didn't before instantiation).
8346 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8347 Context.getCanonicalNestedNameSpecifier(DQual))
8348 continue;
8349
8350 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008351 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008352 return true;
8353 }
8354
8355 return false;
8356}
8357
John McCall3969e302009-12-08 07:46:18 +00008358
John McCallb96ec562009-12-04 22:46:56 +00008359/// Checks that the given nested-name qualifier used in a using decl
8360/// in the current context is appropriately related to the current
8361/// scope. If an error is found, diagnoses it and returns true.
8362bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8363 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008364 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008365 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008366 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008367
John McCall3969e302009-12-08 07:46:18 +00008368 if (!CurContext->isRecord()) {
8369 // C++03 [namespace.udecl]p3:
8370 // C++0x [namespace.udecl]p8:
8371 // A using-declaration for a class member shall be a member-declaration.
8372
8373 // If we weren't able to compute a valid scope, it must be a
8374 // dependent class scope.
8375 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008376 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008377 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008378 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008379
John McCall3969e302009-12-08 07:46:18 +00008380 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8381 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008382
8383 // If we have a complete, non-dependent source type, try to suggest a
8384 // way to get the same effect.
8385 if (!RD)
8386 return true;
8387
8388 // Find what this using-declaration was referring to.
8389 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8390 R.setHideTags(false);
8391 R.suppressDiagnostics();
8392 LookupQualifiedName(R, RD);
8393
8394 if (R.getAsSingle<TypeDecl>()) {
8395 if (getLangOpts().CPlusPlus11) {
8396 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8397 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8398 << 0 // alias declaration
8399 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8400 NameInfo.getName().getAsString() +
8401 " = ");
8402 } else {
8403 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8404 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00008405 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00008406 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8407 << 1 // typedef declaration
8408 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8409 << FixItHint::CreateInsertion(
8410 InsertLoc, " " + NameInfo.getName().getAsString());
8411 }
8412 } else if (R.getAsSingle<VarDecl>()) {
8413 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8414 // repeating the type of the static data member here.
8415 FixItHint FixIt;
8416 if (getLangOpts().CPlusPlus11) {
8417 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8418 FixIt = FixItHint::CreateReplacement(
8419 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8420 }
8421
8422 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8423 << 2 // reference declaration
8424 << FixIt;
8425 }
John McCall3969e302009-12-08 07:46:18 +00008426 return true;
8427 }
8428
8429 // Otherwise, everything is known to be fine.
8430 return false;
8431 }
8432
8433 // The current scope is a record.
8434
8435 // If the named context is dependent, we can't decide much.
8436 if (!NamedContext) {
8437 // FIXME: in C++0x, we can diagnose if we can prove that the
8438 // nested-name-specifier does not refer to a base class, which is
8439 // still possible in some cases.
8440
8441 // Otherwise we have to conservatively report that things might be
8442 // okay.
8443 return false;
8444 }
8445
8446 if (!NamedContext->isRecord()) {
8447 // Ideally this would point at the last name in the specifier,
8448 // but we don't have that level of source info.
8449 Diag(SS.getRange().getBegin(),
8450 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008451 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008452 return true;
8453 }
8454
Douglas Gregor7c842292010-12-21 07:41:49 +00008455 if (!NamedContext->isDependentContext() &&
8456 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8457 return true;
8458
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008459 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008460 // C++0x [namespace.udecl]p3:
8461 // In a using-declaration used as a member-declaration, the
8462 // nested-name-specifier shall name a base class of the class
8463 // being defined.
8464
8465 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8466 cast<CXXRecordDecl>(NamedContext))) {
8467 if (CurContext == NamedContext) {
8468 Diag(NameLoc,
8469 diag::err_using_decl_nested_name_specifier_is_current_class)
8470 << SS.getRange();
8471 return true;
8472 }
8473
8474 Diag(SS.getRange().getBegin(),
8475 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008476 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008477 << cast<CXXRecordDecl>(CurContext)
8478 << SS.getRange();
8479 return true;
8480 }
8481
8482 return false;
8483 }
8484
8485 // C++03 [namespace.udecl]p4:
8486 // A using-declaration used as a member-declaration shall refer
8487 // to a member of a base class of the class being defined [etc.].
8488
8489 // Salient point: SS doesn't have to name a base class as long as
8490 // lookup only finds members from base classes. Therefore we can
8491 // diagnose here only if we can prove that that can't happen,
8492 // i.e. if the class hierarchies provably don't intersect.
8493
8494 // TODO: it would be nice if "definitely valid" results were cached
8495 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8496 // need to be repeated.
8497
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008498 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8499 auto Collect = [&Bases](const CXXRecordDecl *Base) {
8500 Bases.insert(Base);
8501 return true;
John McCall3969e302009-12-08 07:46:18 +00008502 };
8503
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008504 // Collect all bases. Return false if we find a dependent base.
8505 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00008506 return false;
8507
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008508 // Returns true if the base is dependent or is one of the accumulated base
8509 // classes.
8510 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8511 return !Bases.count(Base);
8512 };
8513
8514 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00008515 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00008516 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8517 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00008518 return false;
8519
8520 Diag(SS.getRange().getBegin(),
8521 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008522 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008523 << cast<CXXRecordDecl>(CurContext)
8524 << SS.getRange();
8525
8526 return true;
John McCallb96ec562009-12-04 22:46:56 +00008527}
8528
Richard Smithdda56e42011-04-15 14:24:37 +00008529Decl *Sema::ActOnAliasDeclaration(Scope *S,
8530 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008531 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008532 SourceLocation UsingLoc,
8533 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008534 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00008535 TypeResult Type,
8536 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008537 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00008538 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00008539 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008540 assert((S->getFlags() & Scope::DeclScope) &&
8541 "got alias-declaration outside of declaration scope");
8542
8543 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008544 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008545
8546 bool Invalid = false;
8547 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008548 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008549 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008550
8551 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008552 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008553
8554 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008555 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008556 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008557 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8558 TInfo->getTypeLoc().getBeginLoc());
8559 }
Richard Smithdda56e42011-04-15 14:24:37 +00008560
8561 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8562 LookupName(Previous, S);
8563
8564 // Warn about shadowing the name of a template parameter.
8565 if (Previous.isSingleResult() &&
8566 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008567 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008568 Previous.clear();
8569 }
8570
8571 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8572 "name in alias declaration must be an identifier");
8573 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8574 Name.StartLocation,
8575 Name.Identifier, TInfo);
8576
8577 NewTD->setAccess(AS);
8578
8579 if (Invalid)
8580 NewTD->setInvalidDecl();
8581
Richard Smith54ecd982013-02-20 19:22:51 +00008582 ProcessDeclAttributeList(S, NewTD, AttrList);
8583
Richard Smith3f1b5d02011-05-05 21:57:07 +00008584 CheckTypedefForVariablyModifiedType(S, NewTD);
8585 Invalid |= NewTD->isInvalidDecl();
8586
Richard Smithdda56e42011-04-15 14:24:37 +00008587 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008588
8589 NamedDecl *NewND;
8590 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008591 TypeAliasTemplateDecl *OldDecl = nullptr;
8592 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008593
8594 if (TemplateParamLists.size() != 1) {
8595 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008596 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8597 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008598 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008599 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008600
8601 // Only consider previous declarations in the same scope.
8602 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8603 /*ExplicitInstantiationOrSpecialization*/false);
8604 if (!Previous.empty()) {
8605 Redeclaration = true;
8606
8607 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8608 if (!OldDecl && !Invalid) {
8609 Diag(UsingLoc, diag::err_redefinition_different_kind)
8610 << Name.Identifier;
8611
8612 NamedDecl *OldD = Previous.getRepresentativeDecl();
8613 if (OldD->getLocation().isValid())
8614 Diag(OldD->getLocation(), diag::note_previous_definition);
8615
8616 Invalid = true;
8617 }
8618
8619 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8620 if (TemplateParameterListsAreEqual(TemplateParams,
8621 OldDecl->getTemplateParameters(),
8622 /*Complain=*/true,
8623 TPL_TemplateMatch))
8624 OldTemplateParams = OldDecl->getTemplateParameters();
8625 else
8626 Invalid = true;
8627
8628 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8629 if (!Invalid &&
8630 !Context.hasSameType(OldTD->getUnderlyingType(),
8631 NewTD->getUnderlyingType())) {
8632 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8633 // but we can't reasonably accept it.
8634 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8635 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8636 if (OldTD->getLocation().isValid())
8637 Diag(OldTD->getLocation(), diag::note_previous_definition);
8638 Invalid = true;
8639 }
8640 }
8641 }
8642
8643 // Merge any previous default template arguments into our parameters,
8644 // and check the parameter list.
8645 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8646 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008647 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008648
8649 TypeAliasTemplateDecl *NewDecl =
8650 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8651 Name.Identifier, TemplateParams,
8652 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008653 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008654
8655 NewDecl->setAccess(AS);
8656
8657 if (Invalid)
8658 NewDecl->setInvalidDecl();
8659 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008660 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008661
8662 NewND = NewDecl;
8663 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00008664 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8665 setTagNameForLinkagePurposes(TD, NewTD);
8666 handleTagNumbering(TD, S);
8667 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00008668 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8669 NewND = NewTD;
8670 }
Richard Smithdda56e42011-04-15 14:24:37 +00008671
8672 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008673 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008674
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008675 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008676 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008677}
8678
Richard Smithf4634362014-09-03 23:11:22 +00008679Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8680 SourceLocation AliasLoc,
8681 IdentifierInfo *Alias, CXXScopeSpec &SS,
8682 SourceLocation IdentLoc,
8683 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008684
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008685 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008686 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8687 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008688
John McCall27b18f82009-11-17 02:14:36 +00008689 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008690 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008691
John McCall9f3059a2009-10-09 21:13:30 +00008692 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008693 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008694 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008695 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008696 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008697 }
Richard Smithf4634362014-09-03 23:11:22 +00008698 assert(!R.isAmbiguous() && !R.empty());
Richard Smith2b2a1762015-12-03 23:24:04 +00008699 NamedDecl *ND = R.getFoundDecl();
Richard Smithf4634362014-09-03 23:11:22 +00008700
8701 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00008702 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8703 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00008704 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00008705
Richard Smith2b2a1762015-12-03 23:24:04 +00008706 // Check we're not shadowing a template parameter.
8707 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8708 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8709 PrevR.clear();
8710 }
Aaron Ballman43f40102014-11-14 22:34:56 +00008711
Richard Smith2b2a1762015-12-03 23:24:04 +00008712 // Filter out any other lookup result from an enclosing scope.
8713 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8714 /*AllowInlineNamespace*/false);
8715
8716 // Find the previous declaration and check that we can redeclare it.
8717 NamespaceAliasDecl *Prev = nullptr;
8718 if (NamedDecl *PrevDecl = PrevR.getAsSingle<NamedDecl>()) {
Richard Smithf4634362014-09-03 23:11:22 +00008719 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8720 // We already have an alias with the same name that points to the same
8721 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00008722 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8723 Prev = AD;
8724 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00008725 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8726 << Alias;
8727 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8728 << AD->getNamespace();
8729 return nullptr;
8730 }
Richard Smith2b2a1762015-12-03 23:24:04 +00008731 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00008732 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8733 ? diag::err_redefinition
8734 : diag::err_redefinition_different_kind;
8735 Diag(AliasLoc, DiagID) << Alias;
8736 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8737 return nullptr;
8738 }
8739 }
Mike Stump11289f42009-09-09 15:08:12 +00008740
Nico Riecke50e59a2014-11-24 17:29:52 +00008741 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008742 DiagnoseUseOfDecl(ND, IdentLoc);
8743
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008744 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008745 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008746 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008747 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +00008748 if (Prev)
8749 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +00008750
John McCalld8d0d432010-02-16 06:53:13 +00008751 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008752 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008753}
8754
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008755Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008756Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8757 CXXMethodDecl *MD) {
8758 CXXRecordDecl *ClassDecl = MD->getParent();
8759
Douglas Gregor6d880b12010-07-01 22:31:05 +00008760 // C++ [except.spec]p14:
8761 // An implicitly declared special member function (Clause 12) shall have an
8762 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008763 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008764 if (ClassDecl->isInvalidDecl())
8765 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008766
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008767 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008768 for (const auto &B : ClassDecl->bases()) {
8769 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008770 continue;
8771
Aaron Ballman574705e2014-03-13 15:41:46 +00008772 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008774 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8775 // If this is a deleted function, add it anyway. This might be conformant
8776 // with the standard. This might not. I'm not sure. It might not matter.
8777 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008778 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008779 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008780 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008781
8782 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008783 for (const auto &B : ClassDecl->vbases()) {
8784 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008785 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008786 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8787 // If this is a deleted function, add it anyway. This might be conformant
8788 // with the standard. This might not. I'm not sure. It might not matter.
8789 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008790 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008791 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008792 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008793
8794 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008795 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008796 if (F->hasInClassInitializer()) {
8797 if (Expr *E = F->getInClassInitializer())
8798 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008799 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008800 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008801 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8803 // If this is a deleted function, add it anyway. This might be conformant
8804 // with the standard. This might not. I'm not sure. It might not matter.
8805 // In particular, the problem is that this function never gets called. It
8806 // might just be ill-formed because this function attempts to refer to
8807 // a deleted function here.
8808 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008809 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008810 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008811 }
John McCalldb40c7f2010-12-14 08:05:40 +00008812
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008813 return ExceptSpec;
8814}
8815
Richard Smithc2bc61b2013-03-18 21:12:30 +00008816Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008817Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8818 CXXRecordDecl *ClassDecl = CD->getParent();
8819
8820 // C++ [except.spec]p14:
8821 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008822 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008823 if (ClassDecl->isInvalidDecl())
8824 return ExceptSpec;
8825
8826 // Inherited constructor.
8827 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8828 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8829 // FIXME: Copying or moving the parameters could add extra exceptions to the
8830 // set, as could the default arguments for the inherited constructor. This
8831 // will be addressed when we implement the resolution of core issue 1351.
8832 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8833
8834 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008835 for (const auto &B : ClassDecl->bases()) {
8836 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008837 continue;
8838
Aaron Ballman574705e2014-03-13 15:41:46 +00008839 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008840 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8841 if (BaseClassDecl == InheritedDecl)
8842 continue;
8843 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8844 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008845 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008846 }
8847 }
8848
8849 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008850 for (const auto &B : ClassDecl->vbases()) {
8851 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008852 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8853 if (BaseClassDecl == InheritedDecl)
8854 continue;
8855 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8856 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008857 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008858 }
8859 }
8860
8861 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008862 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008863 if (F->hasInClassInitializer()) {
8864 if (Expr *E = F->getInClassInitializer())
8865 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008866 } else if (const RecordType *RecordTy
8867 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8868 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8869 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8870 if (Constructor)
8871 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8872 }
8873 }
8874
Richard Smithc2bc61b2013-03-18 21:12:30 +00008875 return ExceptSpec;
8876}
8877
Richard Smith8bf22e52012-11-29 01:34:07 +00008878namespace {
8879/// RAII object to register a special member as being currently declared.
8880struct DeclaringSpecialMember {
8881 Sema &S;
8882 Sema::SpecialMemberDecl D;
8883 bool WasAlreadyBeingDeclared;
8884
8885 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8886 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008887 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008888 if (WasAlreadyBeingDeclared)
8889 // This almost never happens, but if it does, ensure that our cache
8890 // doesn't contain a stale result.
8891 S.SpecialMemberCache.clear();
8892
8893 // FIXME: Register a note to be produced if we encounter an error while
8894 // declaring the special member.
8895 }
8896 ~DeclaringSpecialMember() {
8897 if (!WasAlreadyBeingDeclared)
8898 S.SpecialMembersBeingDeclared.erase(D);
8899 }
8900
8901 /// \brief Are we already trying to declare this special member?
8902 bool isAlreadyBeingDeclared() const {
8903 return WasAlreadyBeingDeclared;
8904 }
8905};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008906}
Richard Smith8bf22e52012-11-29 01:34:07 +00008907
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008908CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8909 CXXRecordDecl *ClassDecl) {
8910 // C++ [class.ctor]p5:
8911 // A default constructor for a class X is a constructor of class X
8912 // that can be called without an argument. If there is no
8913 // user-declared constructor for class X, a default constructor is
8914 // implicitly declared. An implicitly-declared default constructor
8915 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008916 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008917 "Should not build implicit default constructor!");
8918
Richard Smith8bf22e52012-11-29 01:34:07 +00008919 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8920 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008921 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008922
Richard Smithb5800092012-06-10 05:43:50 +00008923 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8924 CXXDefaultConstructor,
8925 false);
8926
Douglas Gregor6d880b12010-07-01 22:31:05 +00008927 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008928 CanQualType ClassType
8929 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008930 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008931 DeclarationName Name
8932 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008933 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008934 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008935 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8936 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8937 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008938 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008939 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008940
8941 if (getLangOpts().CUDA) {
8942 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8943 DefaultCon,
8944 /* ConstRHS */ false,
8945 /* Diagnose */ false);
8946 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008947
8948 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008949 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008950 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008951
Richard Smith6b02d462012-12-08 08:32:28 +00008952 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8953 // constructors is easy to compute.
8954 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8955
8956 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008957 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008958
Douglas Gregor9672f922010-07-03 00:47:00 +00008959 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008960 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008961
Douglas Gregor0be31a22010-07-02 17:43:08 +00008962 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008963 PushOnScopeChains(DefaultCon, S, false);
8964 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008965
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008966 return DefaultCon;
8967}
8968
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008969void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8970 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008971 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008972 !Constructor->doesThisDeclarationHaveABody() &&
8973 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008974 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008975
Anders Carlsson423f5d82010-04-23 16:04:08 +00008976 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008977 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008978
Eli Friedmaneaf34142012-10-18 20:14:08 +00008979 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008980 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008981 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008982 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008983 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008984 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008985 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008986 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008987 }
Douglas Gregor73193272010-09-20 16:48:21 +00008988
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008989 // The exception specification is needed because we are defining the
8990 // function.
8991 ResolveExceptionSpec(CurrentLocation,
8992 Constructor->getType()->castAs<FunctionProtoType>());
8993
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008994 SourceLocation Loc = Constructor->getLocEnd().isValid()
8995 ? Constructor->getLocEnd()
8996 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008997 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008998
Eli Friedman276dd182013-09-05 00:02:25 +00008999 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00009000 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009001
9002 if (ASTMutationListener *L = getASTMutationListener()) {
9003 L->CompletedImplicitDefinition(Constructor);
9004 }
Richard Trieuef64e942013-10-25 00:56:00 +00009005
9006 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009007}
9008
Richard Smith938f40b2011-06-11 17:19:42 +00009009void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009010 // Perform any delayed checks on exception specifications.
9011 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00009012}
9013
Richard Smith185be182013-04-10 05:48:59 +00009014namespace {
9015/// Information on inheriting constructors to declare.
9016class InheritingConstructorInfo {
9017public:
9018 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
9019 : SemaRef(SemaRef), Derived(Derived) {
9020 // Mark the constructors that we already have in the derived class.
9021 //
9022 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9023 // unless there is a user-declared constructor with the same signature in
9024 // the class where the using-declaration appears.
9025 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9026 }
9027
9028 void inheritAll(CXXRecordDecl *RD) {
9029 visitAll(RD, &InheritingConstructorInfo::inherit);
9030 }
9031
9032private:
9033 /// Information about an inheriting constructor.
9034 struct InheritingConstructor {
9035 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00009036 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00009037
9038 /// If \c true, a constructor with this signature is already declared
9039 /// in the derived class.
9040 bool DeclaredInDerived;
9041
9042 /// The constructor which is inherited.
9043 const CXXConstructorDecl *BaseCtor;
9044
9045 /// The derived constructor we declared.
9046 CXXConstructorDecl *DerivedCtor;
9047 };
9048
9049 /// Inheriting constructors with a given canonical type. There can be at
9050 /// most one such non-template constructor, and any number of templated
9051 /// constructors.
9052 struct InheritingConstructorsForType {
9053 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009054 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9055 Templates;
Richard Smith185be182013-04-10 05:48:59 +00009056
9057 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9058 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9059 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9060 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9061 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9062 false, S.TPL_TemplateMatch))
9063 return Templates[I].second;
9064 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9065 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009066 }
Richard Smith185be182013-04-10 05:48:59 +00009067
9068 return NonTemplate;
9069 }
9070 };
9071
9072 /// Get or create the inheriting constructor record for a constructor.
9073 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9074 QualType CtorType) {
9075 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9076 .getEntry(SemaRef, Ctor);
9077 }
9078
9079 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9080
9081 /// Process all constructors for a class.
9082 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009083 for (const auto *Ctor : RD->ctors())
9084 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009085 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9086 I(RD->decls_begin()), E(RD->decls_end());
9087 I != E; ++I) {
9088 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9089 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9090 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009091 }
9092 }
Richard Smith185be182013-04-10 05:48:59 +00009093
9094 /// Note that a constructor (or constructor template) was declared in Derived.
9095 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9096 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9097 }
9098
9099 /// Inherit a single constructor.
9100 void inherit(const CXXConstructorDecl *Ctor) {
9101 const FunctionProtoType *CtorType =
9102 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009103 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009104 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9105
9106 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9107
9108 // Core issue (no number yet): the ellipsis is always discarded.
9109 if (EPI.Variadic) {
9110 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9111 SemaRef.Diag(Ctor->getLocation(),
9112 diag::note_using_decl_constructor_ellipsis);
9113 EPI.Variadic = false;
9114 }
9115
9116 // Declare a constructor for each number of parameters.
9117 //
9118 // C++11 [class.inhctor]p1:
9119 // The candidate set of inherited constructors from the class X named in
9120 // the using-declaration consists of [... modulo defects ...] for each
9121 // constructor or constructor template of X, the set of constructors or
9122 // constructor templates that results from omitting any ellipsis parameter
9123 // specification and successively omitting parameters with a default
9124 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009125 unsigned MinParams = minParamsToInherit(Ctor);
9126 unsigned Params = Ctor->getNumParams();
9127 if (Params >= MinParams) {
9128 do
9129 declareCtor(UsingLoc, Ctor,
9130 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009131 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009132 while (Params > MinParams &&
9133 Ctor->getParamDecl(--Params)->hasDefaultArg());
9134 }
Richard Smith185be182013-04-10 05:48:59 +00009135 }
9136
9137 /// Find the using-declaration which specified that we should inherit the
9138 /// constructors of \p Base.
9139 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9140 // No fancy lookup required; just look for the base constructor name
9141 // directly within the derived class.
9142 ASTContext &Context = SemaRef.Context;
9143 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9144 Context.getCanonicalType(Context.getRecordType(Base)));
Richard Smithcf4bdde2015-02-21 02:45:19 +00009145 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith185be182013-04-10 05:48:59 +00009146 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9147 }
9148
9149 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9150 // C++11 [class.inhctor]p3:
9151 // [F]or each constructor template in the candidate set of inherited
9152 // constructors, a constructor template is implicitly declared
9153 if (Ctor->getDescribedFunctionTemplate())
9154 return 0;
9155
9156 // For each non-template constructor in the candidate set of inherited
9157 // constructors other than a constructor having no parameters or a
9158 // copy/move constructor having a single parameter, a constructor is
9159 // implicitly declared [...]
9160 if (Ctor->getNumParams() == 0)
9161 return 1;
9162 if (Ctor->isCopyOrMoveConstructor())
9163 return 2;
9164
9165 // Per discussion on core reflector, never inherit a constructor which
9166 // would become a default, copy, or move constructor of Derived either.
9167 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9168 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9169 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9170 }
9171
9172 /// Declare a single inheriting constructor, inheriting the specified
9173 /// constructor, with the given type.
9174 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9175 QualType DerivedType) {
9176 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9177
9178 // C++11 [class.inhctor]p3:
9179 // ... a constructor is implicitly declared with the same constructor
9180 // characteristics unless there is a user-declared constructor with
9181 // the same signature in the class where the using-declaration appears
9182 if (Entry.DeclaredInDerived)
9183 return;
9184
9185 // C++11 [class.inhctor]p7:
9186 // If two using-declarations declare inheriting constructors with the
9187 // same signature, the program is ill-formed
9188 if (Entry.DerivedCtor) {
9189 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9190 // Only diagnose this once per constructor.
9191 if (Entry.DerivedCtor->isInvalidDecl())
9192 return;
9193 Entry.DerivedCtor->setInvalidDecl();
9194
9195 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9196 SemaRef.Diag(BaseCtor->getLocation(),
9197 diag::note_using_decl_constructor_conflict_current_ctor);
9198 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9199 diag::note_using_decl_constructor_conflict_previous_ctor);
9200 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9201 diag::note_using_decl_constructor_conflict_previous_using);
9202 } else {
9203 // Core issue (no number): if the same inheriting constructor is
9204 // produced by multiple base class constructors from the same base
9205 // class, the inheriting constructor is defined as deleted.
9206 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9207 }
9208
9209 return;
9210 }
9211
9212 ASTContext &Context = SemaRef.Context;
9213 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9214 Context.getCanonicalType(Context.getRecordType(Derived)));
9215 DeclarationNameInfo NameInfo(Name, UsingLoc);
9216
Craig Topperc3ec1492014-05-26 06:22:03 +00009217 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009218 if (const FunctionTemplateDecl *FTD =
9219 BaseCtor->getDescribedFunctionTemplate()) {
9220 TemplateParams = FTD->getTemplateParameters();
9221 // We're reusing template parameters from a different DeclContext. This
9222 // is questionable at best, but works out because the template depth in
9223 // both places is guaranteed to be 0.
9224 // FIXME: Rebuild the template parameters in the new context, and
9225 // transform the function type to refer to them.
9226 }
9227
9228 // Build type source info pointing at the using-declaration. This is
9229 // required by template instantiation.
9230 TypeSourceInfo *TInfo =
9231 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9232 FunctionProtoTypeLoc ProtoLoc =
9233 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9234
9235 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9236 Context, Derived, UsingLoc, NameInfo, DerivedType,
9237 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9238 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9239
9240 // Build an unevaluated exception specification for this constructor.
9241 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9242 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009243 EPI.ExceptionSpec.Type = EST_Unevaluated;
9244 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009245 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009246 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009247
9248 // Build the parameter declarations.
9249 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009250 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009251 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009252 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009253 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009254 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9255 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009256 PD->setScopeInfo(0, I);
9257 PD->setImplicit();
9258 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009259 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009260 }
9261
9262 // Set up the new constructor.
9263 DerivedCtor->setAccess(BaseCtor->getAccess());
9264 DerivedCtor->setParams(ParamDecls);
9265 DerivedCtor->setInheritedConstructor(BaseCtor);
9266 if (BaseCtor->isDeleted())
9267 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9268
9269 // If this is a constructor template, build the template declaration.
9270 if (TemplateParams) {
9271 FunctionTemplateDecl *DerivedTemplate =
9272 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9273 TemplateParams, DerivedCtor);
9274 DerivedTemplate->setAccess(BaseCtor->getAccess());
9275 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9276 Derived->addDecl(DerivedTemplate);
9277 } else {
9278 Derived->addDecl(DerivedCtor);
9279 }
9280
9281 Entry.BaseCtor = BaseCtor;
9282 Entry.DerivedCtor = DerivedCtor;
9283 }
9284
9285 Sema &SemaRef;
9286 CXXRecordDecl *Derived;
9287 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9288 MapType Map;
9289};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009290}
Richard Smith185be182013-04-10 05:48:59 +00009291
9292void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9293 // Defer declaring the inheriting constructors until the class is
9294 // instantiated.
9295 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009296 return;
9297
Richard Smith185be182013-04-10 05:48:59 +00009298 // Find base classes from which we might inherit constructors.
9299 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009300 for (const auto &BaseIt : ClassDecl->bases())
9301 if (BaseIt.getInheritConstructors())
9302 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009303
Richard Smith185be182013-04-10 05:48:59 +00009304 // Go no further if we're not inheriting any constructors.
9305 if (InheritedBases.empty())
9306 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009307
Richard Smith185be182013-04-10 05:48:59 +00009308 // Declare the inherited constructors.
9309 InheritingConstructorInfo ICI(*this, ClassDecl);
9310 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9311 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009312}
9313
Richard Smithc2bc61b2013-03-18 21:12:30 +00009314void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9315 CXXConstructorDecl *Constructor) {
9316 CXXRecordDecl *ClassDecl = Constructor->getParent();
9317 assert(Constructor->getInheritedConstructor() &&
9318 !Constructor->doesThisDeclarationHaveABody() &&
9319 !Constructor->isDeleted());
9320
9321 SynthesizedFunctionScope Scope(*this, Constructor);
9322 DiagnosticErrorTrap Trap(Diags);
9323 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9324 Trap.hasErrorOccurred()) {
9325 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9326 << Context.getTagDeclType(ClassDecl);
9327 Constructor->setInvalidDecl();
9328 return;
9329 }
9330
9331 SourceLocation Loc = Constructor->getLocation();
9332 Constructor->setBody(new (Context) CompoundStmt(Loc));
9333
Eli Friedman276dd182013-09-05 00:02:25 +00009334 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009335 MarkVTableUsed(CurrentLocation, ClassDecl);
9336
9337 if (ASTMutationListener *L = getASTMutationListener()) {
9338 L->CompletedImplicitDefinition(Constructor);
9339 }
9340}
9341
9342
Alexis Huntf91729462011-05-12 22:46:25 +00009343Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009344Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9345 CXXRecordDecl *ClassDecl = MD->getParent();
9346
Douglas Gregorf1203042010-07-01 19:09:28 +00009347 // C++ [except.spec]p14:
9348 // An implicitly declared special member function (Clause 12) shall have
9349 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009350 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009351 if (ClassDecl->isInvalidDecl())
9352 return ExceptSpec;
9353
Douglas Gregorf1203042010-07-01 19:09:28 +00009354 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009355 for (const auto &B : ClassDecl->bases()) {
9356 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009357 continue;
9358
Aaron Ballman574705e2014-03-13 15:41:46 +00009359 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9360 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009361 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009362 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009363
Douglas Gregorf1203042010-07-01 19:09:28 +00009364 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009365 for (const auto &B : ClassDecl->vbases()) {
9366 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9367 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009368 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009369 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009370
Douglas Gregorf1203042010-07-01 19:09:28 +00009371 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009372 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009373 if (const RecordType *RecordTy
9374 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009375 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009376 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009377 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009378
Alexis Huntf91729462011-05-12 22:46:25 +00009379 return ExceptSpec;
9380}
9381
9382CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9383 // C++ [class.dtor]p2:
9384 // If a class has no user-declared destructor, a destructor is
9385 // declared implicitly. An implicitly-declared destructor is an
9386 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009387 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009388
Richard Smith8bf22e52012-11-29 01:34:07 +00009389 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9390 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009391 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009392
Douglas Gregor7454c562010-07-02 20:37:36 +00009393 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009394 CanQualType ClassType
9395 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009396 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009397 DeclarationName Name
9398 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009399 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009400 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009401 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009402 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009403 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009404 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009405 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009406
9407 if (getLangOpts().CUDA) {
9408 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9409 Destructor,
9410 /* ConstRHS */ false,
9411 /* Diagnose */ false);
9412 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009413
9414 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009415 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009416 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009417
Richard Smith6b02d462012-12-08 08:32:28 +00009418 AddOverriddenMethods(ClassDecl, Destructor);
9419
9420 // We don't need to use SpecialMemberIsTrivial here; triviality for
9421 // destructors is easy to compute.
9422 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9423
9424 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009425 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009426
Douglas Gregor7454c562010-07-02 20:37:36 +00009427 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009428 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009429
Douglas Gregor7454c562010-07-02 20:37:36 +00009430 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009431 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009432 PushOnScopeChains(Destructor, S, false);
9433 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009434
Douglas Gregorf1203042010-07-01 19:09:28 +00009435 return Destructor;
9436}
9437
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009438void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009439 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009440 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009441 !Destructor->doesThisDeclarationHaveABody() &&
9442 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009443 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009444 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009445 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009446
Douglas Gregor54818f02010-05-12 16:39:35 +00009447 if (Destructor->isInvalidDecl())
9448 return;
9449
Eli Friedmaneaf34142012-10-18 20:14:08 +00009450 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009451
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009452 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009453 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9454 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009455
Douglas Gregor54818f02010-05-12 16:39:35 +00009456 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009457 Diag(CurrentLocation, diag::note_member_synthesized_at)
9458 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9459
9460 Destructor->setInvalidDecl();
9461 return;
9462 }
9463
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009464 // The exception specification is needed because we are defining the
9465 // function.
9466 ResolveExceptionSpec(CurrentLocation,
9467 Destructor->getType()->castAs<FunctionProtoType>());
9468
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009469 SourceLocation Loc = Destructor->getLocEnd().isValid()
9470 ? Destructor->getLocEnd()
9471 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009472 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009473 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009474 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009475
9476 if (ASTMutationListener *L = getASTMutationListener()) {
9477 L->CompletedImplicitDefinition(Destructor);
9478 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009479}
9480
Richard Smith84973e52012-04-21 18:42:51 +00009481/// \brief Perform any semantic analysis which needs to be delayed until all
9482/// pending class member declarations have been parsed.
9483void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009484 // If the context is an invalid C++ class, just suppress these checks.
9485 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9486 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009487 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009488 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009489 return;
9490 }
9491 }
Richard Smith84973e52012-04-21 18:42:51 +00009492}
9493
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009494static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9495 // Don't do anything for template patterns.
9496 if (Class->getDescribedClassTemplate())
9497 return;
9498
9499 for (Decl *Member : Class->decls()) {
9500 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9501 if (!CD) {
9502 // Recurse on nested classes.
9503 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9504 getDefaultArgExprsForConstructors(S, NestedRD);
9505 continue;
9506 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9507 continue;
9508 }
9509
9510 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9511 // Skip any default arguments that we've already instantiated.
9512 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9513 continue;
9514
9515 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9516 CD->getParamDecl(I)).get();
David Majnemer9321f922015-06-11 02:38:06 +00009517 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009518 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9519 }
9520 }
9521}
9522
Hans Wennborg99000c22015-08-15 01:18:16 +00009523void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009524 auto *RD = dyn_cast<CXXRecordDecl>(D);
9525
9526 // Default constructors that are annotated with __declspec(dllexport) which
9527 // have default arguments or don't use the standard calling convention are
9528 // wrapped with a thunk called the default constructor closure.
9529 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9530 getDefaultArgExprsForConstructors(*this, RD);
Hans Wennborg99000c22015-08-15 01:18:16 +00009531
9532 if (!DelayedDllExportClasses.empty()) {
9533 // Calling ReferenceDllExportedMethods might cause the current function to
9534 // be called again, so use a local copy of DelayedDllExportClasses.
9535 SmallVector<CXXRecordDecl *, 4> WorkList;
9536 std::swap(DelayedDllExportClasses, WorkList);
9537 for (CXXRecordDecl *Class : WorkList)
9538 ReferenceDllExportedMethods(*this, Class);
9539 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009540}
9541
Richard Smithd3b5c9082012-07-27 04:22:15 +00009542void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9543 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009544 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009545 "adjusting dtor exception specs was introduced in c++11");
9546
Sebastian Redl623ea822011-05-19 05:13:44 +00009547 // C++11 [class.dtor]p3:
9548 // A declaration of a destructor that does not have an exception-
9549 // specification is implicitly considered to have the same exception-
9550 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009551 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009552 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009553 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009554 return;
9555
Chandler Carruth9a797572011-09-20 04:55:26 +00009556 // Replace the destructor's type, building off the existing one. Fortunately,
9557 // the only thing of interest in the destructor type is its extended info.
9558 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009559 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009560 EPI.ExceptionSpec.Type = EST_Unevaluated;
9561 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009562 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009563
Sebastian Redl623ea822011-05-19 05:13:44 +00009564 // FIXME: If the destructor has a body that could throw, and the newly created
9565 // spec doesn't allow exceptions, we should emit a warning, because this
9566 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009567 // However, we don't have a body or an exception specification yet, so it
9568 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009569}
9570
Pavel Labath58934982013-08-30 08:52:28 +00009571namespace {
9572/// \brief An abstract base class for all helper classes used in building the
9573// copy/move operators. These classes serve as factory functions and help us
9574// avoid using the same Expr* in the AST twice.
9575class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +00009576 ExprBuilder(const ExprBuilder&) = delete;
9577 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +00009578
9579protected:
9580 static Expr *assertNotNull(Expr *E) {
9581 assert(E && "Expression construction must not fail.");
9582 return E;
9583 }
9584
9585public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009586 ExprBuilder() {}
9587 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +00009588
9589 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9590};
9591
9592class RefBuilder: public ExprBuilder {
9593 VarDecl *Var;
9594 QualType VarType;
9595
9596public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009597 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009598 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009599 }
9600
9601 RefBuilder(VarDecl *Var, QualType VarType)
9602 : Var(Var), VarType(VarType) {}
9603};
9604
9605class ThisBuilder: public ExprBuilder {
9606public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009607 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009608 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009609 }
9610};
9611
9612class CastBuilder: public ExprBuilder {
9613 const ExprBuilder &Builder;
9614 QualType Type;
9615 ExprValueKind Kind;
9616 const CXXCastPath &Path;
9617
9618public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009619 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009620 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9621 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009622 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009623 }
9624
9625 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9626 const CXXCastPath &Path)
9627 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9628};
9629
9630class DerefBuilder: public ExprBuilder {
9631 const ExprBuilder &Builder;
9632
9633public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009634 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009635 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009636 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009637 }
9638
9639 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9640};
9641
9642class MemberBuilder: public ExprBuilder {
9643 const ExprBuilder &Builder;
9644 QualType Type;
9645 CXXScopeSpec SS;
9646 bool IsArrow;
9647 LookupResult &MemberLookup;
9648
9649public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009650 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009651 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009652 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +00009653 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009654 }
9655
9656 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9657 LookupResult &MemberLookup)
9658 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9659 MemberLookup(MemberLookup) {}
9660};
9661
9662class MoveCastBuilder: public ExprBuilder {
9663 const ExprBuilder &Builder;
9664
9665public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009666 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009667 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9668 }
9669
9670 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9671};
9672
9673class LvalueConvBuilder: public ExprBuilder {
9674 const ExprBuilder &Builder;
9675
9676public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009677 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009678 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009679 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009680 }
9681
9682 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9683};
9684
9685class SubscriptBuilder: public ExprBuilder {
9686 const ExprBuilder &Base;
9687 const ExprBuilder &Index;
9688
9689public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009690 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009691 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009692 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009693 }
9694
9695 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9696 : Base(Base), Index(Index) {}
9697};
9698
9699} // end anonymous namespace
9700
Richard Smith41ae3282012-11-14 00:50:40 +00009701/// When generating a defaulted copy or move assignment operator, if a field
9702/// should be copied with __builtin_memcpy rather than via explicit assignments,
9703/// do so. This optimization only applies for arrays of scalars, and for arrays
9704/// of class type where the selected copy/move-assignment operator is trivial.
9705static StmtResult
9706buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009707 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009708 // Compute the size of the memory buffer to be copied.
9709 QualType SizeType = S.Context.getSizeType();
9710 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9711 S.Context.getTypeSizeInChars(T).getQuantity());
9712
9713 // Take the address of the field references for "from" and "to". We
9714 // directly construct UnaryOperators here because semantic analysis
9715 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009716 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009717 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9718 S.Context.getPointerType(From->getType()),
9719 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009720 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009721 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9722 S.Context.getPointerType(To->getType()),
9723 VK_RValue, OK_Ordinary, Loc);
9724
9725 const Type *E = T->getBaseElementTypeUnsafe();
9726 bool NeedsCollectableMemCpy =
9727 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9728
9729 // Create a reference to the __builtin_objc_memmove_collectable function
9730 StringRef MemCpyName = NeedsCollectableMemCpy ?
9731 "__builtin_objc_memmove_collectable" :
9732 "__builtin_memcpy";
9733 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9734 Sema::LookupOrdinaryName);
9735 S.LookupName(R, S.TUScope, true);
9736
9737 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9738 if (!MemCpy)
9739 // Something went horribly wrong earlier, and we will have complained
9740 // about it.
9741 return StmtError();
9742
9743 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009744 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009745 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9746
9747 Expr *CallArgs[] = {
9748 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9749 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009750 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009751 Loc, CallArgs, Loc);
9752
9753 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009754 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009755}
9756
Sebastian Redl22653ba2011-08-30 19:58:05 +00009757/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009758/// \c To.
9759///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009760/// This routine is used to copy/move the members of a class with an
9761/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009762/// copied are arrays, this routine builds for loops to copy them.
9763///
9764/// \param S The Sema object used for type-checking.
9765///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009766/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009767///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009768/// \param T The type of the expressions being copied/moved. Both expressions
9769/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009770///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009771/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009772///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009773/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009774///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009775/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009776/// Otherwise, it's a non-static member subobject.
9777///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009778/// \param Copying Whether we're copying or moving.
9779///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009780/// \param Depth Internal parameter recording the depth of the recursion.
9781///
Richard Smith41ae3282012-11-14 00:50:40 +00009782/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9783/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009784static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009785buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009786 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009787 bool CopyingBaseSubobject, bool Copying,
9788 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009789 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009790 // Each subobject is assigned in the manner appropriate to its type:
9791 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009792 // - if the subobject is of class type, as if by a call to operator= with
9793 // the subobject as the object expression and the corresponding
9794 // subobject of x as a single function argument (as if by explicit
9795 // qualification; that is, ignoring any possible virtual overriding
9796 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009797 //
9798 // C++03 [class.copy]p13:
9799 // - if the subobject is of class type, the copy assignment operator for
9800 // the class is used (as if by explicit qualification; that is,
9801 // ignoring any possible virtual overriding functions in more derived
9802 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009803 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9804 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009805
Douglas Gregorb139cd52010-05-01 20:49:11 +00009806 // Look for operator=.
9807 DeclarationName Name
9808 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9809 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9810 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009811
Richard Smith52c0b582012-11-13 00:54:12 +00009812 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9813 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009814 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009815 LookupResult::Filter F = OpLookup.makeFilter();
9816 while (F.hasNext()) {
9817 NamedDecl *D = F.next();
9818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9819 if (Method->isCopyAssignmentOperator() ||
9820 (!Copying && Method->isMoveAssignmentOperator()))
9821 continue;
9822
9823 F.erase();
9824 }
9825 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009826 }
Richard Smith52c0b582012-11-13 00:54:12 +00009827
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009828 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009829 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009830 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009831 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009832 // ambiguities), we need to cast "this" to that subobject type; to
9833 // ensure that we don't go through the virtual call mechanism, we need
9834 // to qualify the operator= name with the base class (see below). However,
9835 // this means that if the base class has a protected copy assignment
9836 // operator, the protected member access check will fail. So, we
9837 // rewrite "protected" access to "public" access in this case, since we
9838 // know by construction that we're calling from a derived class.
9839 if (CopyingBaseSubobject) {
9840 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9841 L != LEnd; ++L) {
9842 if (L.getAccess() == AS_protected)
9843 L.setAccess(AS_public);
9844 }
9845 }
Richard Smith52c0b582012-11-13 00:54:12 +00009846
Douglas Gregorb139cd52010-05-01 20:49:11 +00009847 // Create the nested-name-specifier that will be used to qualify the
9848 // reference to operator=; this is required to suppress the virtual
9849 // call mechanism.
9850 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009851 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009852 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009853 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009854 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009855 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009856
Douglas Gregorb139cd52010-05-01 20:49:11 +00009857 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009858 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009859 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9860 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009861 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009862 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00009863 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009864 /*SuppressQualifierCheck=*/true);
9865 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009866 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009867
Douglas Gregorb139cd52010-05-01 20:49:11 +00009868 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009869
Pavel Labath58934982013-08-30 08:52:28 +00009870 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009871 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009872 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009873 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009874 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009875 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009876
Richard Smith41ae3282012-11-14 00:50:40 +00009877 // If we built a call to a trivial 'operator=' while copying an array,
9878 // bail out. We'll replace the whole shebang with a memcpy.
9879 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9880 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009881 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009882
Richard Smith52c0b582012-11-13 00:54:12 +00009883 // Convert to an expression-statement, and clean up any produced
9884 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009885 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009886 }
John McCallab8c2732010-03-16 06:11:48 +00009887
Richard Smith52c0b582012-11-13 00:54:12 +00009888 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009889 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009890 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009891 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009892 ExprResult Assignment = S.CreateBuiltinBinOp(
9893 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009894 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009895 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009896 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009897 }
Richard Smith52c0b582012-11-13 00:54:12 +00009898
9899 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009900 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009901
Douglas Gregorb139cd52010-05-01 20:49:11 +00009902 // Construct a loop over the array bounds, e.g.,
9903 //
9904 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9905 //
9906 // that will copy each of the array elements.
9907 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009908
Douglas Gregorb139cd52010-05-01 20:49:11 +00009909 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009910 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009911 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009912 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009913 llvm::raw_svector_ostream OS(Str);
9914 OS << "__i" << Depth;
9915 IterationVarName = &S.Context.Idents.get(OS.str());
9916 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009917 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009918 IterationVarName, SizeType,
9919 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009920 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009921
Douglas Gregorb139cd52010-05-01 20:49:11 +00009922 // Initialize the iteration variable to zero.
9923 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009924 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009925
Pavel Labath58934982013-08-30 08:52:28 +00009926 // Creates a reference to the iteration variable.
9927 RefBuilder IterationVarRef(IterationVar, SizeType);
9928 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009929
Douglas Gregorb139cd52010-05-01 20:49:11 +00009930 // Create the DeclStmt that holds the iteration variable.
9931 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009932
Douglas Gregorb139cd52010-05-01 20:49:11 +00009933 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009934 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9935 MoveCastBuilder FromIndexMove(FromIndexCopy);
9936 const ExprBuilder *FromIndex;
9937 if (Copying)
9938 FromIndex = &FromIndexCopy;
9939 else
9940 FromIndex = &FromIndexMove;
9941
9942 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009943
9944 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009945 StmtResult Copy =
9946 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009947 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009948 Copying, Depth + 1);
9949 // Bail out if copying fails or if we determined that we should use memcpy.
9950 if (Copy.isInvalid() || !Copy.get())
9951 return Copy;
9952
9953 // Create the comparison against the array bound.
9954 llvm::APInt Upper
9955 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9956 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009957 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009958 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9959 BO_NE, S.Context.BoolTy,
9960 VK_RValue, OK_Ordinary, Loc, false);
9961
9962 // Create the pre-increment of the iteration variable.
9963 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009964 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9965 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009966
Douglas Gregorb139cd52010-05-01 20:49:11 +00009967 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009968 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009969 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009970 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009971 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009972}
9973
Richard Smith41ae3282012-11-14 00:50:40 +00009974static StmtResult
9975buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009976 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009977 bool CopyingBaseSubobject, bool Copying) {
9978 // Maybe we should use a memcpy?
9979 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9980 T.isTriviallyCopyableType(S.Context))
9981 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9982
9983 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9984 CopyingBaseSubobject,
9985 Copying, 0));
9986
9987 // If we ended up picking a trivial assignment operator for an array of a
9988 // non-trivially-copyable class type, just emit a memcpy.
9989 if (!Result.isInvalid() && !Result.get())
9990 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9991
9992 return Result;
9993}
9994
Richard Smithd3b5c9082012-07-27 04:22:15 +00009995Sema::ImplicitExceptionSpecification
9996Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9997 CXXRecordDecl *ClassDecl = MD->getParent();
9998
9999 ImplicitExceptionSpecification ExceptSpec(*this);
10000 if (ClassDecl->isInvalidDecl())
10001 return ExceptSpec;
10002
10003 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010004 assert(T->getNumParams() == 1 && "not a copy assignment op");
10005 unsigned ArgQuals =
10006 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010007
Douglas Gregor68e11362010-07-01 17:48:08 +000010008 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000010009 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000010010 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000010011
10012 // It is unspecified whether or not an implicit copy assignment operator
10013 // attempts to deduplicate calls to assignment operators of virtual bases are
10014 // made. As such, this exception specification is effectively unspecified.
10015 // Based on a similar decision made for constness in C++0x, we're erring on
10016 // the side of assuming such calls to be made regardless of whether they
10017 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000010018 for (const auto &Base : ClassDecl->bases()) {
10019 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000010020 continue;
10021
Douglas Gregor330b9cf2010-07-02 21:50:04 +000010022 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010023 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010024 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10025 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010026 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000010027 }
Alexis Hunt491ec602011-06-21 23:42:56 +000010028
Aaron Ballman445a9392014-03-13 16:15:17 +000010029 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010030 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010031 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010032 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10033 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010034 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010035 }
10036
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010037 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010038 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010039 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10040 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010041 LookupCopyingAssignment(FieldClassDecl,
10042 ArgQuals | FieldType.getCVRQualifiers(),
10043 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010044 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010045 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010046 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010047
Richard Smithd3b5c9082012-07-27 04:22:15 +000010048 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010049}
10050
10051CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10052 // Note: The following rules are largely analoguous to the copy
10053 // constructor rules. Note that virtual bases are not taken into account
10054 // for determining the argument type of the operator. Note also that
10055 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010056 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010057
Richard Smith8bf22e52012-11-29 01:34:07 +000010058 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10059 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010060 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010061
Alexis Hunt119f3652011-05-14 05:23:20 +000010062 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10063 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010064 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10065 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010066 ArgType = ArgType.withConst();
10067 ArgType = Context.getLValueReferenceType(ArgType);
10068
Richard Smith99005e62013-05-07 03:19:20 +000010069 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10070 CXXCopyAssignment,
10071 Const);
10072
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010073 // An implicitly-declared copy assignment operator is an inline public
10074 // member of its class.
10075 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010076 SourceLocation ClassLoc = ClassDecl->getLocation();
10077 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010078 CXXMethodDecl *CopyAssignment =
10079 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010080 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10081 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010082 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010083 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010084 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010085
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010086 if (getLangOpts().CUDA) {
10087 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10088 CopyAssignment,
10089 /* ConstRHS */ Const,
10090 /* Diagnose */ false);
10091 }
10092
Richard Smithd3b5c9082012-07-27 04:22:15 +000010093 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010094 FunctionProtoType::ExtProtoInfo EPI =
10095 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010096 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010097
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010098 // Add the parameter to the operator.
10099 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010100 ClassLoc, ClassLoc,
10101 /*Id=*/nullptr, ArgType,
10102 /*TInfo=*/nullptr, SC_None,
10103 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010104 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010105
Richard Smith6b02d462012-12-08 08:32:28 +000010106 AddOverriddenMethods(ClassDecl, CopyAssignment);
10107
10108 CopyAssignment->setTrivial(
10109 ClassDecl->needsOverloadResolutionForCopyAssignment()
10110 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10111 : ClassDecl->hasTrivialCopyAssignment());
10112
Richard Smith852265f2012-03-30 20:53:28 +000010113 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +000010114 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010115
Richard Smith6b02d462012-12-08 08:32:28 +000010116 // Note that we have added this copy-assignment operator.
10117 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10118
10119 if (Scope *S = getScopeForContext(ClassDecl))
10120 PushOnScopeChains(CopyAssignment, S, false);
10121 ClassDecl->addDecl(CopyAssignment);
10122
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010123 return CopyAssignment;
10124}
10125
Richard Smithd577fbb2013-06-13 03:23:42 +000010126/// Diagnose an implicit copy operation for a class which is odr-used, but
10127/// which is deprecated because the class has a user-declared copy constructor,
10128/// copy assignment operator, or destructor.
10129static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10130 SourceLocation UseLoc) {
10131 assert(CopyOp->isImplicit());
10132
10133 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010134 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010135
10136 // In Microsoft mode, assignment operations don't affect constructors and
10137 // vice versa.
10138 if (RD->hasUserDeclaredDestructor()) {
10139 UserDeclaredOperation = RD->getDestructor();
10140 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10141 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010142 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010143 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010144 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010145 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010146 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010147 break;
10148 }
10149 }
10150 assert(UserDeclaredOperation);
10151 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10152 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010153 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010154 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010155 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010156 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010157 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010158 break;
10159 }
10160 }
10161 assert(UserDeclaredOperation);
10162 }
10163
10164 if (UserDeclaredOperation) {
10165 S.Diag(UserDeclaredOperation->getLocation(),
10166 diag::warn_deprecated_copy_operation)
10167 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10168 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10169 S.Diag(UseLoc, diag::note_member_synthesized_at)
10170 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10171 : Sema::CXXCopyAssignment)
10172 << RD;
10173 }
10174}
10175
Douglas Gregorb139cd52010-05-01 20:49:11 +000010176void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10177 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010178 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010179 CopyAssignOperator->isOverloadedOperator() &&
10180 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010181 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10182 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010183 "DefineImplicitCopyAssignment called for wrong function");
10184
10185 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10186
10187 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10188 CopyAssignOperator->setInvalidDecl();
10189 return;
10190 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010191
10192 // C++11 [class.copy]p18:
10193 // The [definition of an implicitly declared copy assignment operator] is
10194 // deprecated if the class has a user-declared copy constructor or a
10195 // user-declared destructor.
10196 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10197 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10198
Eli Friedman276dd182013-09-05 00:02:25 +000010199 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010200
Eli Friedmaneaf34142012-10-18 20:14:08 +000010201 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010202 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010203
10204 // C++0x [class.copy]p30:
10205 // The implicitly-defined or explicitly-defaulted copy assignment operator
10206 // for a non-union class X performs memberwise copy assignment of its
10207 // subobjects. The direct base classes of X are assigned first, in the
10208 // order of their declaration in the base-specifier-list, and then the
10209 // immediate non-static data members of X are assigned, in the order in
10210 // which they were declared in the class definition.
10211
10212 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010213 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010214
10215 // The parameter for the "other" object, which we are copying from.
10216 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10217 Qualifiers OtherQuals = Other->getType().getQualifiers();
10218 QualType OtherRefType = Other->getType();
10219 if (const LValueReferenceType *OtherRef
10220 = OtherRefType->getAs<LValueReferenceType>()) {
10221 OtherRefType = OtherRef->getPointeeType();
10222 OtherQuals = OtherRefType.getQualifiers();
10223 }
10224
10225 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010226 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10227 ? CopyAssignOperator->getLocEnd()
10228 : CopyAssignOperator->getLocation();
10229
Pavel Labath58934982013-08-30 08:52:28 +000010230 // Builds a DeclRefExpr for the "other" object.
10231 RefBuilder OtherRef(Other, OtherRefType);
10232
10233 // Builds the "this" pointer.
10234 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010235
10236 // Assign base classes.
10237 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010238 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010239 // Form the assignment:
10240 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010241 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010242 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010243 Invalid = true;
10244 continue;
10245 }
10246
John McCallcf142162010-08-07 06:22:56 +000010247 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010248 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010249
Douglas Gregorb139cd52010-05-01 20:49:11 +000010250 // Construct the "from" expression, which is an implicit cast to the
10251 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010252 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10253 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010254
10255 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010256 DerefBuilder DerefThis(This);
10257 CastBuilder To(DerefThis,
10258 Context.getCVRQualifiedType(
10259 BaseType, CopyAssignOperator->getTypeQualifiers()),
10260 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010261
10262 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010263 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010264 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010265 /*CopyingBaseSubobject=*/true,
10266 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010267 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010268 Diag(CurrentLocation, diag::note_member_synthesized_at)
10269 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10270 CopyAssignOperator->setInvalidDecl();
10271 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010272 }
10273
10274 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010275 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010276 }
10277
Douglas Gregorb139cd52010-05-01 20:49:11 +000010278 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010279 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010280 // FIXME: We should form some kind of AST representation for the implied
10281 // memcpy in a union copy operation.
10282 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010283 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010284
10285 if (Field->isInvalidDecl()) {
10286 Invalid = true;
10287 continue;
10288 }
10289
Douglas Gregorb139cd52010-05-01 20:49:11 +000010290 // Check for members of reference type; we can't copy those.
10291 if (Field->getType()->isReferenceType()) {
10292 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10293 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10294 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010295 Diag(CurrentLocation, diag::note_member_synthesized_at)
10296 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010297 Invalid = true;
10298 continue;
10299 }
10300
10301 // Check for members of const-qualified, non-class type.
10302 QualType BaseType = Context.getBaseElementType(Field->getType());
10303 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10304 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10305 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10306 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010307 Diag(CurrentLocation, diag::note_member_synthesized_at)
10308 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010309 Invalid = true;
10310 continue;
10311 }
John McCall1b1a1db2011-06-17 00:18:42 +000010312
10313 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010314 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10315 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010316
10317 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010318 if (FieldType->isIncompleteArrayType()) {
10319 assert(ClassDecl->hasFlexibleArrayMember() &&
10320 "Incomplete array type is not valid");
10321 continue;
10322 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010323
10324 // Build references to the field in the object we're copying from and to.
10325 CXXScopeSpec SS; // Intentionally empty
10326 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10327 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010328 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010329 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010330
10331 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10332
10333 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010334
Douglas Gregorb139cd52010-05-01 20:49:11 +000010335 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010336 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010337 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010338 /*CopyingBaseSubobject=*/false,
10339 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010340 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010341 Diag(CurrentLocation, diag::note_member_synthesized_at)
10342 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10343 CopyAssignOperator->setInvalidDecl();
10344 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010345 }
10346
10347 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010348 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010349 }
10350
10351 if (!Invalid) {
10352 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010353 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010354
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010355 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010356 if (Return.isInvalid())
10357 Invalid = true;
10358 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010359 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010360
10361 if (Trap.hasErrorOccurred()) {
10362 Diag(CurrentLocation, diag::note_member_synthesized_at)
10363 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10364 Invalid = true;
10365 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010366 }
10367 }
10368
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010369 // The exception specification is needed because we are defining the
10370 // function.
10371 ResolveExceptionSpec(CurrentLocation,
10372 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10373
Douglas Gregorb139cd52010-05-01 20:49:11 +000010374 if (Invalid) {
10375 CopyAssignOperator->setInvalidDecl();
10376 return;
10377 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010378
10379 StmtResult Body;
10380 {
10381 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010382 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010383 /*isStmtExpr=*/false);
10384 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10385 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010386 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010387
10388 if (ASTMutationListener *L = getASTMutationListener()) {
10389 L->CompletedImplicitDefinition(CopyAssignOperator);
10390 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010391}
10392
Sebastian Redl22653ba2011-08-30 19:58:05 +000010393Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010394Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10395 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010396
Richard Smithd3b5c9082012-07-27 04:22:15 +000010397 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010398 if (ClassDecl->isInvalidDecl())
10399 return ExceptSpec;
10400
10401 // C++0x [except.spec]p14:
10402 // An implicitly declared special member function (Clause 12) shall have an
10403 // exception-specification. [...]
10404
10405 // It is unspecified whether or not an implicit move assignment operator
10406 // attempts to deduplicate calls to assignment operators of virtual bases are
10407 // made. As such, this exception specification is effectively unspecified.
10408 // Based on a similar decision made for constness in C++0x, we're erring on
10409 // the side of assuming such calls to be made regardless of whether they
10410 // actually happen.
10411 // Note that a move constructor is not implicitly declared when there are
10412 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010413 for (const auto &Base : ClassDecl->bases()) {
10414 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010415 continue;
10416
10417 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010418 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010419 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010420 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010421 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010422 }
10423
Aaron Ballman445a9392014-03-13 16:15:17 +000010424 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010425 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010426 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010427 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010428 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010429 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010430 }
10431
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010432 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010433 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010434 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010435 if (CXXMethodDecl *MoveAssign =
10436 LookupMovingAssignment(FieldClassDecl,
10437 FieldType.getCVRQualifiers(),
10438 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010439 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010440 }
10441 }
10442
10443 return ExceptSpec;
10444}
10445
10446CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010447 assert(ClassDecl->needsImplicitMoveAssignment());
10448
Richard Smith8bf22e52012-11-29 01:34:07 +000010449 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10450 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010451 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010452
Sebastian Redl22653ba2011-08-30 19:58:05 +000010453 // Note: The following rules are largely analoguous to the move
10454 // constructor rules.
10455
Sebastian Redl22653ba2011-08-30 19:58:05 +000010456 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10457 QualType RetType = Context.getLValueReferenceType(ArgType);
10458 ArgType = Context.getRValueReferenceType(ArgType);
10459
Richard Smith99005e62013-05-07 03:19:20 +000010460 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10461 CXXMoveAssignment,
10462 false);
10463
Sebastian Redl22653ba2011-08-30 19:58:05 +000010464 // An implicitly-declared move assignment operator is an inline public
10465 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010466 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10467 SourceLocation ClassLoc = ClassDecl->getLocation();
10468 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010469 CXXMethodDecl *MoveAssignment =
10470 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010471 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010472 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010473 MoveAssignment->setAccess(AS_public);
10474 MoveAssignment->setDefaulted();
10475 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010476
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010477 if (getLangOpts().CUDA) {
10478 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10479 MoveAssignment,
10480 /* ConstRHS */ false,
10481 /* Diagnose */ false);
10482 }
10483
Richard Smithd3b5c9082012-07-27 04:22:15 +000010484 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010485 FunctionProtoType::ExtProtoInfo EPI =
10486 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010487 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010488
Sebastian Redl22653ba2011-08-30 19:58:05 +000010489 // Add the parameter to the operator.
10490 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010491 ClassLoc, ClassLoc,
10492 /*Id=*/nullptr, ArgType,
10493 /*TInfo=*/nullptr, SC_None,
10494 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010495 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010496
Richard Smith6b02d462012-12-08 08:32:28 +000010497 AddOverriddenMethods(ClassDecl, MoveAssignment);
10498
10499 MoveAssignment->setTrivial(
10500 ClassDecl->needsOverloadResolutionForMoveAssignment()
10501 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10502 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010503
Richard Smithd951a1d2012-02-18 02:02:13 +000010504 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010505 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10506 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010507 }
10508
Richard Smith6b02d462012-12-08 08:32:28 +000010509 // Note that we have added this copy-assignment operator.
10510 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10511
Sebastian Redl22653ba2011-08-30 19:58:05 +000010512 if (Scope *S = getScopeForContext(ClassDecl))
10513 PushOnScopeChains(MoveAssignment, S, false);
10514 ClassDecl->addDecl(MoveAssignment);
10515
Sebastian Redl22653ba2011-08-30 19:58:05 +000010516 return MoveAssignment;
10517}
10518
Richard Smithb2504bd2013-11-04 04:26:14 +000010519/// Check if we're implicitly defining a move assignment operator for a class
10520/// with virtual bases. Such a move assignment might move-assign the virtual
10521/// base multiple times.
10522static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10523 SourceLocation CurrentLocation) {
10524 assert(!Class->isDependentContext() && "should not define dependent move");
10525
10526 // Only a virtual base could get implicitly move-assigned multiple times.
10527 // Only a non-trivial move assignment can observe this. We only want to
10528 // diagnose if we implicitly define an assignment operator that assigns
10529 // two base classes, both of which move-assign the same virtual base.
10530 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10531 Class->getNumBases() < 2)
10532 return;
10533
10534 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10535 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10536 VBaseMap VBases;
10537
Aaron Ballman574705e2014-03-13 15:41:46 +000010538 for (auto &BI : Class->bases()) {
10539 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010540 while (!Worklist.empty()) {
10541 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10542 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10543
10544 // If the base has no non-trivial move assignment operators,
10545 // we don't care about moves from it.
10546 if (!Base->hasNonTrivialMoveAssignment())
10547 continue;
10548
10549 // If there's nothing virtual here, skip it.
10550 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10551 continue;
10552
10553 // If we're not actually going to call a move assignment for this base,
10554 // or the selected move assignment is trivial, skip it.
10555 Sema::SpecialMemberOverloadResult *SMOR =
10556 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10557 /*ConstArg*/false, /*VolatileArg*/false,
10558 /*RValueThis*/true, /*ConstThis*/false,
10559 /*VolatileThis*/false);
10560 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10561 !SMOR->getMethod()->isMoveAssignmentOperator())
10562 continue;
10563
10564 if (BaseSpec->isVirtual()) {
10565 // We're going to move-assign this virtual base, and its move
10566 // assignment operator is not trivial. If this can happen for
10567 // multiple distinct direct bases of Class, diagnose it. (If it
10568 // only happens in one base, we'll diagnose it when synthesizing
10569 // that base class's move assignment operator.)
10570 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010571 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010572 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010573 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010574 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10575 << Class << Base;
10576 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10577 << (Base->getCanonicalDecl() ==
10578 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10579 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010580 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010581 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010582 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10583 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010584
10585 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010586 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010587 }
10588 } else {
10589 // Only walk over bases that have defaulted move assignment operators.
10590 // We assume that any user-provided move assignment operator handles
10591 // the multiple-moves-of-vbase case itself somehow.
10592 if (!SMOR->getMethod()->isDefaulted())
10593 continue;
10594
10595 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010596 for (auto &BI : Base->bases())
10597 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010598 }
10599 }
10600 }
10601}
10602
Sebastian Redl22653ba2011-08-30 19:58:05 +000010603void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10604 CXXMethodDecl *MoveAssignOperator) {
10605 assert((MoveAssignOperator->isDefaulted() &&
10606 MoveAssignOperator->isOverloadedOperator() &&
10607 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010608 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10609 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010610 "DefineImplicitMoveAssignment called for wrong function");
10611
10612 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10613
10614 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10615 MoveAssignOperator->setInvalidDecl();
10616 return;
10617 }
10618
Eli Friedman276dd182013-09-05 00:02:25 +000010619 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010620
Eli Friedmaneaf34142012-10-18 20:14:08 +000010621 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010622 DiagnosticErrorTrap Trap(Diags);
10623
10624 // C++0x [class.copy]p28:
10625 // The implicitly-defined or move assignment operator for a non-union class
10626 // X performs memberwise move assignment of its subobjects. The direct base
10627 // classes of X are assigned first, in the order of their declaration in the
10628 // base-specifier-list, and then the immediate non-static data members of X
10629 // are assigned, in the order in which they were declared in the class
10630 // definition.
10631
Richard Smithb2504bd2013-11-04 04:26:14 +000010632 // Issue a warning if our implicit move assignment operator will move
10633 // from a virtual base more than once.
10634 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010635
Sebastian Redl22653ba2011-08-30 19:58:05 +000010636 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010637 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010638
10639 // The parameter for the "other" object, which we are move from.
10640 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10641 QualType OtherRefType = Other->getType()->
10642 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010643 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010644 "Bad argument type of defaulted move assignment");
10645
10646 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010647 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10648 ? MoveAssignOperator->getLocEnd()
10649 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010650
Pavel Labath58934982013-08-30 08:52:28 +000010651 // Builds a reference to the "other" object.
10652 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010653 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010654 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010655
Pavel Labath58934982013-08-30 08:52:28 +000010656 // Builds the "this" pointer.
10657 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010658
Sebastian Redl22653ba2011-08-30 19:58:05 +000010659 // Assign base classes.
10660 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010661 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010662 // C++11 [class.copy]p28:
10663 // It is unspecified whether subobjects representing virtual base classes
10664 // are assigned more than once by the implicitly-defined copy assignment
10665 // operator.
10666 // FIXME: Do not assign to a vbase that will be assigned by some other base
10667 // class. For a move-assignment, this can result in the vbase being moved
10668 // multiple times.
10669
Sebastian Redl22653ba2011-08-30 19:58:05 +000010670 // Form the assignment:
10671 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010672 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010673 if (!BaseType->isRecordType()) {
10674 Invalid = true;
10675 continue;
10676 }
10677
10678 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010679 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010680
10681 // Construct the "from" expression, which is an implicit cast to the
10682 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010683 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010684
10685 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010686 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010687
10688 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010689 CastBuilder To(DerefThis,
10690 Context.getCVRQualifiedType(
10691 BaseType, MoveAssignOperator->getTypeQualifiers()),
10692 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010693
10694 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010695 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010696 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010697 /*CopyingBaseSubobject=*/true,
10698 /*Copying=*/false);
10699 if (Move.isInvalid()) {
10700 Diag(CurrentLocation, diag::note_member_synthesized_at)
10701 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10702 MoveAssignOperator->setInvalidDecl();
10703 return;
10704 }
10705
10706 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010707 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010708 }
10709
Sebastian Redl22653ba2011-08-30 19:58:05 +000010710 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010711 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010712 // FIXME: We should form some kind of AST representation for the implied
10713 // memcpy in a union copy operation.
10714 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010715 continue;
10716
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010717 if (Field->isInvalidDecl()) {
10718 Invalid = true;
10719 continue;
10720 }
10721
Sebastian Redl22653ba2011-08-30 19:58:05 +000010722 // Check for members of reference type; we can't move those.
10723 if (Field->getType()->isReferenceType()) {
10724 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10725 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10726 Diag(Field->getLocation(), diag::note_declared_at);
10727 Diag(CurrentLocation, diag::note_member_synthesized_at)
10728 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10729 Invalid = true;
10730 continue;
10731 }
10732
10733 // Check for members of const-qualified, non-class type.
10734 QualType BaseType = Context.getBaseElementType(Field->getType());
10735 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10736 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10737 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10738 Diag(Field->getLocation(), diag::note_declared_at);
10739 Diag(CurrentLocation, diag::note_member_synthesized_at)
10740 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10741 Invalid = true;
10742 continue;
10743 }
10744
10745 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010746 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10747 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010748
10749 QualType FieldType = Field->getType().getNonReferenceType();
10750 if (FieldType->isIncompleteArrayType()) {
10751 assert(ClassDecl->hasFlexibleArrayMember() &&
10752 "Incomplete array type is not valid");
10753 continue;
10754 }
10755
10756 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010757 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10758 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010759 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010760 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010761 MemberBuilder From(MoveOther, OtherRefType,
10762 /*IsArrow=*/false, MemberLookup);
10763 MemberBuilder To(This, getCurrentThisType(),
10764 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010765
Pavel Labath58934982013-08-30 08:52:28 +000010766 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010767 "Member reference with rvalue base must be rvalue except for reference "
10768 "members, which aren't allowed for move assignment.");
10769
Sebastian Redl22653ba2011-08-30 19:58:05 +000010770 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010771 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010772 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010773 /*CopyingBaseSubobject=*/false,
10774 /*Copying=*/false);
10775 if (Move.isInvalid()) {
10776 Diag(CurrentLocation, diag::note_member_synthesized_at)
10777 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10778 MoveAssignOperator->setInvalidDecl();
10779 return;
10780 }
Richard Smith11d19592012-11-12 23:33:00 +000010781
Sebastian Redl22653ba2011-08-30 19:58:05 +000010782 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010783 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010784 }
10785
10786 if (!Invalid) {
10787 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010788 ExprResult ThisObj =
10789 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10790
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010791 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010792 if (Return.isInvalid())
10793 Invalid = true;
10794 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010795 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010796
10797 if (Trap.hasErrorOccurred()) {
10798 Diag(CurrentLocation, diag::note_member_synthesized_at)
10799 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10800 Invalid = true;
10801 }
10802 }
10803 }
10804
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010805 // The exception specification is needed because we are defining the
10806 // function.
10807 ResolveExceptionSpec(CurrentLocation,
10808 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10809
Sebastian Redl22653ba2011-08-30 19:58:05 +000010810 if (Invalid) {
10811 MoveAssignOperator->setInvalidDecl();
10812 return;
10813 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010814
10815 StmtResult Body;
10816 {
10817 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010818 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010819 /*isStmtExpr=*/false);
10820 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10821 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010822 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010823
10824 if (ASTMutationListener *L = getASTMutationListener()) {
10825 L->CompletedImplicitDefinition(MoveAssignOperator);
10826 }
10827}
10828
Richard Smithd3b5c9082012-07-27 04:22:15 +000010829Sema::ImplicitExceptionSpecification
10830Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10831 CXXRecordDecl *ClassDecl = MD->getParent();
10832
10833 ImplicitExceptionSpecification ExceptSpec(*this);
10834 if (ClassDecl->isInvalidDecl())
10835 return ExceptSpec;
10836
10837 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010838 assert(T->getNumParams() >= 1 && "not a copy ctor");
10839 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010840
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010841 // C++ [except.spec]p14:
10842 // An implicitly declared special member function (Clause 12) shall have an
10843 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010844 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010845 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010846 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010847 continue;
10848
Douglas Gregora6d69502010-07-02 23:41:54 +000010849 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010850 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010851 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010852 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010853 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010854 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010855 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010856 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010857 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010858 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010859 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010860 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010861 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010862 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010863 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010864 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10865 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010866 LookupCopyingConstructor(FieldClassDecl,
10867 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010868 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010869 }
10870 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010871
Richard Smithd3b5c9082012-07-27 04:22:15 +000010872 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010873}
10874
10875CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10876 CXXRecordDecl *ClassDecl) {
10877 // C++ [class.copy]p4:
10878 // If the class definition does not explicitly declare a copy
10879 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010880 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010881
Richard Smith8bf22e52012-11-29 01:34:07 +000010882 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10883 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010884 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010885
Alexis Hunt913820d2011-05-13 06:10:58 +000010886 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10887 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010888 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010889 if (Const)
10890 ArgType = ArgType.withConst();
10891 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010892
Richard Smithb5800092012-06-10 05:43:50 +000010893 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10894 CXXCopyConstructor,
10895 Const);
10896
Douglas Gregor54be3392010-07-01 17:57:27 +000010897 DeclarationName Name
10898 = Context.DeclarationNames.getCXXConstructorName(
10899 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010900 SourceLocation ClassLoc = ClassDecl->getLocation();
10901 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010902
10903 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010904 // member of its class.
10905 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010906 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010907 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010908 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010909 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010910 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010911
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010912 if (getLangOpts().CUDA) {
10913 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10914 CopyConstructor,
10915 /* ConstRHS */ Const,
10916 /* Diagnose */ false);
10917 }
10918
Richard Smithd3b5c9082012-07-27 04:22:15 +000010919 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010920 FunctionProtoType::ExtProtoInfo EPI =
10921 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010922 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010923 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010924
Douglas Gregor54be3392010-07-01 17:57:27 +000010925 // Add the parameter to the constructor.
10926 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010927 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010928 /*IdentifierInfo=*/nullptr,
10929 ArgType, /*TInfo=*/nullptr,
10930 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010931 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010932
Richard Smith6b02d462012-12-08 08:32:28 +000010933 CopyConstructor->setTrivial(
10934 ClassDecl->needsOverloadResolutionForCopyConstructor()
10935 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10936 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010937
Richard Smith852265f2012-03-30 20:53:28 +000010938 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010939 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010940
Richard Smith6b02d462012-12-08 08:32:28 +000010941 // Note that we have declared this constructor.
10942 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10943
10944 if (Scope *S = getScopeForContext(ClassDecl))
10945 PushOnScopeChains(CopyConstructor, S, false);
10946 ClassDecl->addDecl(CopyConstructor);
10947
Douglas Gregor54be3392010-07-01 17:57:27 +000010948 return CopyConstructor;
10949}
10950
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010951void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010952 CXXConstructorDecl *CopyConstructor) {
10953 assert((CopyConstructor->isDefaulted() &&
10954 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010955 !CopyConstructor->doesThisDeclarationHaveABody() &&
10956 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010957 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010958
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010959 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010960 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010961
Richard Smithd577fbb2013-06-13 03:23:42 +000010962 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010963 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010964 // deprecated if the class has a user-declared copy assignment operator
10965 // or a user-declared destructor.
10966 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10967 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10968
Eli Friedmaneaf34142012-10-18 20:14:08 +000010969 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010970 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010971
David Blaikie3fc2f912013-01-17 05:26:25 +000010972 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010973 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010974 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010975 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010976 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010977 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010978 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10979 ? CopyConstructor->getLocEnd()
10980 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010981 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010982 CopyConstructor->setBody(
10983 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010984 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010985
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010986 // The exception specification is needed because we are defining the
10987 // function.
10988 ResolveExceptionSpec(CurrentLocation,
10989 CopyConstructor->getType()->castAs<FunctionProtoType>());
10990
Eli Friedman276dd182013-09-05 00:02:25 +000010991 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010992 MarkVTableUsed(CurrentLocation, ClassDecl);
10993
Sebastian Redlab238a72011-04-24 16:28:06 +000010994 if (ASTMutationListener *L = getASTMutationListener()) {
10995 L->CompletedImplicitDefinition(CopyConstructor);
10996 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010997}
10998
Sebastian Redl22653ba2011-08-30 19:58:05 +000010999Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011000Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11001 CXXRecordDecl *ClassDecl = MD->getParent();
11002
Sebastian Redl22653ba2011-08-30 19:58:05 +000011003 // C++ [except.spec]p14:
11004 // An implicitly declared special member function (Clause 12) shall have an
11005 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000011006 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011007 if (ClassDecl->isInvalidDecl())
11008 return ExceptSpec;
11009
11010 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000011011 for (const auto &B : ClassDecl->bases()) {
11012 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011013 continue;
11014
Aaron Ballman574705e2014-03-13 15:41:46 +000011015 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011016 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011017 CXXConstructorDecl *Constructor =
11018 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011019 // If this is a deleted function, add it anyway. This might be conformant
11020 // with the standard. This might not. I'm not sure. It might not matter.
11021 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000011022 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011023 }
11024 }
11025
11026 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000011027 for (const auto &B : ClassDecl->vbases()) {
11028 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011030 CXXConstructorDecl *Constructor =
11031 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011032 // If this is a deleted function, add it anyway. This might be conformant
11033 // with the standard. This might not. I'm not sure. It might not matter.
11034 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011035 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011036 }
11037 }
11038
11039 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011040 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011041 QualType FieldType = Context.getBaseElementType(F->getType());
11042 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11043 CXXConstructorDecl *Constructor =
11044 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011045 // If this is a deleted function, add it anyway. This might be conformant
11046 // with the standard. This might not. I'm not sure. It might not matter.
11047 // In particular, the problem is that this function never gets called. It
11048 // might just be ill-formed because this function attempts to refer to
11049 // a deleted function here.
11050 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011051 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011052 }
11053 }
11054
11055 return ExceptSpec;
11056}
11057
11058CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11059 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011060 assert(ClassDecl->needsImplicitMoveConstructor());
11061
Richard Smith8bf22e52012-11-29 01:34:07 +000011062 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11063 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011064 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011065
Sebastian Redl22653ba2011-08-30 19:58:05 +000011066 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11067 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011068
Richard Smithb5800092012-06-10 05:43:50 +000011069 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11070 CXXMoveConstructor,
11071 false);
11072
Sebastian Redl22653ba2011-08-30 19:58:05 +000011073 DeclarationName Name
11074 = Context.DeclarationNames.getCXXConstructorName(
11075 Context.getCanonicalType(ClassType));
11076 SourceLocation ClassLoc = ClassDecl->getLocation();
11077 DeclarationNameInfo NameInfo(Name, ClassLoc);
11078
Richard Smith99005e62013-05-07 03:19:20 +000011079 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011080 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011081 // member of its class.
11082 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011083 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011084 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011085 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011086 MoveConstructor->setAccess(AS_public);
11087 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011088
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011089 if (getLangOpts().CUDA) {
11090 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11091 MoveConstructor,
11092 /* ConstRHS */ false,
11093 /* Diagnose */ false);
11094 }
11095
Richard Smithd3b5c9082012-07-27 04:22:15 +000011096 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011097 FunctionProtoType::ExtProtoInfo EPI =
11098 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011099 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011100 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011101
Sebastian Redl22653ba2011-08-30 19:58:05 +000011102 // Add the parameter to the constructor.
11103 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11104 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011105 /*IdentifierInfo=*/nullptr,
11106 ArgType, /*TInfo=*/nullptr,
11107 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011108 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011109
Richard Smith6b02d462012-12-08 08:32:28 +000011110 MoveConstructor->setTrivial(
11111 ClassDecl->needsOverloadResolutionForMoveConstructor()
11112 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11113 : ClassDecl->hasTrivialMoveConstructor());
11114
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000011115 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011116 ClassDecl->setImplicitMoveConstructorIsDeleted();
11117 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011118 }
11119
11120 // Note that we have declared this constructor.
11121 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11122
11123 if (Scope *S = getScopeForContext(ClassDecl))
11124 PushOnScopeChains(MoveConstructor, S, false);
11125 ClassDecl->addDecl(MoveConstructor);
11126
11127 return MoveConstructor;
11128}
11129
11130void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11131 CXXConstructorDecl *MoveConstructor) {
11132 assert((MoveConstructor->isDefaulted() &&
11133 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011134 !MoveConstructor->doesThisDeclarationHaveABody() &&
11135 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011136 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11137
11138 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11139 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11140
Eli Friedmaneaf34142012-10-18 20:14:08 +000011141 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011142 DiagnosticErrorTrap Trap(Diags);
11143
David Blaikie3fc2f912013-01-17 05:26:25 +000011144 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011145 Trap.hasErrorOccurred()) {
11146 Diag(CurrentLocation, diag::note_member_synthesized_at)
11147 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11148 MoveConstructor->setInvalidDecl();
11149 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011150 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11151 ? MoveConstructor->getLocEnd()
11152 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011153 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011154 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011155 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011156 }
11157
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011158 // The exception specification is needed because we are defining the
11159 // function.
11160 ResolveExceptionSpec(CurrentLocation,
11161 MoveConstructor->getType()->castAs<FunctionProtoType>());
11162
Eli Friedman276dd182013-09-05 00:02:25 +000011163 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011164 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011165
11166 if (ASTMutationListener *L = getASTMutationListener()) {
11167 L->CompletedImplicitDefinition(MoveConstructor);
11168 }
11169}
11170
Douglas Gregor74f7d502012-02-15 19:33:52 +000011171bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011172 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011173}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011174
11175void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011176 SourceLocation CurrentLocation,
11177 CXXConversionDecl *Conv) {
11178 CXXRecordDecl *Lambda = Conv->getParent();
11179 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11180 // If we are defining a specialization of a conversion to function-ptr
11181 // cache the deduced template arguments for this specialization
11182 // so that we can use them to retrieve the corresponding call-operator
11183 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011184 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11185
Faisal Vali571df122013-09-29 08:45:24 +000011186 // Retrieve the corresponding call-operator specialization.
11187 if (Lambda->isGenericLambda()) {
11188 assert(Conv->isFunctionTemplateSpecialization());
11189 FunctionTemplateDecl *CallOpTemplate =
11190 CallOp->getDescribedFunctionTemplate();
11191 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011192 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011193 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011194 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011195 InsertPos);
11196 assert(CallOpSpec &&
11197 "Conversion operator must have a corresponding call operator");
11198 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11199 }
11200 // Mark the call operator referenced (and add to pending instantiations
11201 // if necessary).
11202 // For both the conversion and static-invoker template specializations
11203 // we construct their body's in this function, so no need to add them
11204 // to the PendingInstantiations.
11205 MarkFunctionReferenced(CurrentLocation, CallOp);
11206
Eli Friedmaneaf34142012-10-18 20:14:08 +000011207 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011208 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011209
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011210 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011211 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11212 // ... and get the corresponding specialization for a generic lambda.
11213 if (Lambda->isGenericLambda()) {
11214 assert(DeducedTemplateArgs &&
11215 "Must have deduced template arguments from Conversion Operator");
11216 FunctionTemplateDecl *InvokeTemplate =
11217 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011218 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011219 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011220 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011221 InsertPos);
11222 assert(InvokeSpec &&
11223 "Must have a corresponding static invoker specialization");
11224 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11225 }
11226 // Construct the body of the conversion function { return __invoke; }.
11227 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011228 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011229 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011230 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011231 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11232 Conv->getLocation(),
11233 Conv->getLocation()));
11234
11235 Conv->markUsed(Context);
11236 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011237
Faisal Vali571df122013-09-29 08:45:24 +000011238 // Fill in the __invoke function with a dummy implementation. IR generation
11239 // will fill in the actual details.
11240 Invoker->markUsed(Context);
11241 Invoker->setReferenced();
11242 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11243
Douglas Gregord3b672c2012-02-16 01:06:16 +000011244 if (ASTMutationListener *L = getASTMutationListener()) {
11245 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011246 L->CompletedImplicitDefinition(Invoker);
11247 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011248}
11249
Faisal Vali571df122013-09-29 08:45:24 +000011250
11251
Douglas Gregord3b672c2012-02-16 01:06:16 +000011252void Sema::DefineImplicitLambdaToBlockPointerConversion(
11253 SourceLocation CurrentLocation,
11254 CXXConversionDecl *Conv)
11255{
Faisal Vali850da1a2013-09-29 17:08:32 +000011256 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011257
Eli Friedman276dd182013-09-05 00:02:25 +000011258 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011259
Eli Friedmaneaf34142012-10-18 20:14:08 +000011260 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011261 DiagnosticErrorTrap Trap(Diags);
11262
Douglas Gregored90df32012-02-22 05:02:47 +000011263 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011264 Expr *This = ActOnCXXThis(CurrentLocation).get();
11265 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011266
Eli Friedman98b01ed2012-03-01 04:01:32 +000011267 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11268 Conv->getLocation(),
11269 Conv, DerefThis);
11270
11271 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11272 // behavior. Note that only the general conversion function does this
11273 // (since it's unusable otherwise); in the case where we inline the
11274 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011275 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011276 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11277 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011278 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011279
11280 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011281 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011282 Conv->setInvalidDecl();
11283 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011284 }
Douglas Gregored90df32012-02-22 05:02:47 +000011285
Douglas Gregored90df32012-02-22 05:02:47 +000011286 // Create the return statement that returns the block from the conversion
11287 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011288 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011289 if (Return.isInvalid()) {
11290 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11291 Conv->setInvalidDecl();
11292 return;
11293 }
11294
11295 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011296 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011297 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011298 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011299 Conv->getLocation()));
11300
Douglas Gregored90df32012-02-22 05:02:47 +000011301 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011302 if (ASTMutationListener *L = getASTMutationListener()) {
11303 L->CompletedImplicitDefinition(Conv);
11304 }
11305}
11306
Douglas Gregord2f70072012-03-10 06:53:13 +000011307/// \brief Determine whether the given list arguments contains exactly one
11308/// "real" (non-default) argument.
11309static bool hasOneRealArgument(MultiExprArg Args) {
11310 switch (Args.size()) {
11311 case 0:
11312 return false;
11313
11314 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011315 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011316 return false;
11317
11318 // fall through
11319 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011320 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011321 }
11322
11323 return false;
11324}
11325
John McCalldadc5752010-08-24 06:29:42 +000011326ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011327Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011328 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011329 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011330 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011331 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011332 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011333 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011334 unsigned ConstructKind,
11335 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011336 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011337
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011338 // C++0x [class.copy]p34:
11339 // When certain criteria are met, an implementation is allowed to
11340 // omit the copy/move construction of a class object, even if the
11341 // copy/move constructor and/or destructor for the object have
11342 // side effects. [...]
11343 // - when a temporary class object that has not been bound to a
11344 // reference (12.2) would be copied/moved to a class object
11345 // with the same cv-unqualified type, the copy/move operation
11346 // can be omitted by constructing the temporary object
11347 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011348 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011349 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011350 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011351 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011352 }
Mike Stump11289f42009-09-09 15:08:12 +000011353
11354 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011355 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011356 IsListInitialization,
11357 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011358 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011359}
11360
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011361/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11362/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011363ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011364Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11365 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011366 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011367 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011368 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011369 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011370 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011371 unsigned ConstructKind,
11372 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011373 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011374 return CXXConstructExpr::Create(
11375 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011376 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11377 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011378 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11379 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011380}
11381
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011382ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11383 assert(Field->hasInClassInitializer());
11384
11385 // If we already have the in-class initializer nothing needs to be done.
11386 if (Field->getInClassInitializer())
11387 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11388
11389 // Maybe we haven't instantiated the in-class initializer. Go check the
11390 // pattern FieldDecl to see if it has one.
11391 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11392
11393 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11394 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11395 DeclContext::lookup_result Lookup =
11396 ClassPattern->lookup(Field->getDeclName());
11397 assert(Lookup.size() == 1);
11398 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11399 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11400 getTemplateInstantiationArgs(Field)))
11401 return ExprError();
11402 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11403 }
11404
11405 // DR1351:
11406 // If the brace-or-equal-initializer of a non-static data member
11407 // invokes a defaulted default constructor of its class or of an
11408 // enclosing class in a potentially evaluated subexpression, the
11409 // program is ill-formed.
11410 //
11411 // This resolution is unworkable: the exception specification of the
11412 // default constructor can be needed in an unevaluated context, in
11413 // particular, in the operand of a noexcept-expression, and we can be
11414 // unable to compute an exception specification for an enclosed class.
11415 //
11416 // Any attempt to resolve the exception specification of a defaulted default
11417 // constructor before the initializer is lexically complete will ultimately
11418 // come here at which point we can diagnose it.
11419 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11420 if (OutermostClass == ParentRD) {
11421 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11422 << ParentRD << Field;
11423 } else {
11424 Diag(Field->getLocEnd(),
11425 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11426 << ParentRD << OutermostClass << Field;
11427 }
11428
11429 return ExprError();
11430}
11431
John McCall03c48482010-02-02 09:10:11 +000011432void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011433 if (VD->isInvalidDecl()) return;
11434
John McCall03c48482010-02-02 09:10:11 +000011435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011436 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011437 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011438 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011439
Chandler Carruth86d17d32011-03-27 21:26:48 +000011440 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011441 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011442 CheckDestructorAccess(VD->getLocation(), Destructor,
11443 PDiag(diag::err_access_dtor_var)
11444 << VD->getDeclName()
11445 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011446 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011447
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011448 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011449 if (!VD->hasGlobalStorage()) return;
11450
11451 // Emit warning for non-trivial dtor in global scope (a real global,
11452 // class-static, function-static).
11453 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11454
11455 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011456 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011457 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011458}
11459
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011460/// \brief Given a constructor and the set of arguments provided for the
11461/// constructor, convert the arguments and add any required default arguments
11462/// to form a proper call to this constructor.
11463///
11464/// \returns true if an error occurred, false otherwise.
11465bool
11466Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11467 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011468 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011469 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011470 bool AllowExplicit,
11471 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011472 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11473 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011474 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011475
11476 const FunctionProtoType *Proto
11477 = Constructor->getType()->getAs<FunctionProtoType>();
11478 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011479 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011480
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011481 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011482 if (NumArgs < NumParams)
11483 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011484 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011485 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011486
11487 VariadicCallType CallType =
11488 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011489 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011490 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011491 Proto, 0,
11492 llvm::makeArrayRef(Args, NumArgs),
11493 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011494 CallType, AllowExplicit,
11495 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011496 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011497
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011498 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011499
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011500 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011501 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011502 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011503
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011504 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011505}
11506
Anders Carlssone363c8e2009-12-12 00:32:00 +000011507static inline bool
11508CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11509 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011510 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011511 if (isa<NamespaceDecl>(DC)) {
11512 return SemaRef.Diag(FnDecl->getLocation(),
11513 diag::err_operator_new_delete_declared_in_namespace)
11514 << FnDecl->getDeclName();
11515 }
11516
11517 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011518 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011519 return SemaRef.Diag(FnDecl->getLocation(),
11520 diag::err_operator_new_delete_declared_static)
11521 << FnDecl->getDeclName();
11522 }
11523
Anders Carlsson60659a82009-12-12 02:43:16 +000011524 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011525}
11526
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011527static inline bool
11528CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11529 CanQualType ExpectedResultType,
11530 CanQualType ExpectedFirstParamType,
11531 unsigned DependentParamTypeDiag,
11532 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011533 QualType ResultType =
11534 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011535
11536 // Check that the result type is not dependent.
11537 if (ResultType->isDependentType())
11538 return SemaRef.Diag(FnDecl->getLocation(),
11539 diag::err_operator_new_delete_dependent_result_type)
11540 << FnDecl->getDeclName() << ExpectedResultType;
11541
11542 // Check that the result type is what we expect.
11543 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11544 return SemaRef.Diag(FnDecl->getLocation(),
11545 diag::err_operator_new_delete_invalid_result_type)
11546 << FnDecl->getDeclName() << ExpectedResultType;
11547
11548 // A function template must have at least 2 parameters.
11549 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11550 return SemaRef.Diag(FnDecl->getLocation(),
11551 diag::err_operator_new_delete_template_too_few_parameters)
11552 << FnDecl->getDeclName();
11553
11554 // The function decl must have at least 1 parameter.
11555 if (FnDecl->getNumParams() == 0)
11556 return SemaRef.Diag(FnDecl->getLocation(),
11557 diag::err_operator_new_delete_too_few_parameters)
11558 << FnDecl->getDeclName();
11559
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011560 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011561 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11562 if (FirstParamType->isDependentType())
11563 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11564 << FnDecl->getDeclName() << ExpectedFirstParamType;
11565
11566 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011567 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011568 ExpectedFirstParamType)
11569 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11570 << FnDecl->getDeclName() << ExpectedFirstParamType;
11571
11572 return false;
11573}
11574
Anders Carlsson12308f42009-12-11 23:23:22 +000011575static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011576CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011577 // C++ [basic.stc.dynamic.allocation]p1:
11578 // A program is ill-formed if an allocation function is declared in a
11579 // namespace scope other than global scope or declared static in global
11580 // scope.
11581 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11582 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011583
11584 CanQualType SizeTy =
11585 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11586
11587 // C++ [basic.stc.dynamic.allocation]p1:
11588 // The return type shall be void*. The first parameter shall have type
11589 // std::size_t.
11590 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11591 SizeTy,
11592 diag::err_operator_new_dependent_param_type,
11593 diag::err_operator_new_param_type))
11594 return true;
11595
11596 // C++ [basic.stc.dynamic.allocation]p1:
11597 // The first parameter shall not have an associated default argument.
11598 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011599 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011600 diag::err_operator_new_default_arg)
11601 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11602
11603 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011604}
11605
11606static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011607CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011608 // C++ [basic.stc.dynamic.deallocation]p1:
11609 // A program is ill-formed if deallocation functions are declared in a
11610 // namespace scope other than global scope or declared static in global
11611 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011612 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11613 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011614
11615 // C++ [basic.stc.dynamic.deallocation]p2:
11616 // Each deallocation function shall return void and its first parameter
11617 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011618 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11619 SemaRef.Context.VoidPtrTy,
11620 diag::err_operator_delete_dependent_param_type,
11621 diag::err_operator_delete_param_type))
11622 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011623
Anders Carlsson12308f42009-12-11 23:23:22 +000011624 return false;
11625}
11626
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011627/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11628/// of this overloaded operator is well-formed. If so, returns false;
11629/// otherwise, emits appropriate diagnostics and returns true.
11630bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011631 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011632 "Expected an overloaded operator declaration");
11633
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011634 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11635
Mike Stump11289f42009-09-09 15:08:12 +000011636 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011637 // The allocation and deallocation functions, operator new,
11638 // operator new[], operator delete and operator delete[], are
11639 // described completely in 3.7.3. The attributes and restrictions
11640 // found in the rest of this subclause do not apply to them unless
11641 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011642 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011643 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011644
Anders Carlsson22f443f2009-12-12 00:26:23 +000011645 if (Op == OO_New || Op == OO_Array_New)
11646 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011647
11648 // C++ [over.oper]p6:
11649 // An operator function shall either be a non-static member
11650 // function or be a non-member function and have at least one
11651 // parameter whose type is a class, a reference to a class, an
11652 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011653 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11654 if (MethodDecl->isStatic())
11655 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011656 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011657 } else {
11658 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011659 for (auto Param : FnDecl->params()) {
11660 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011661 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11662 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011663 ClassOrEnumParam = true;
11664 break;
11665 }
11666 }
11667
Douglas Gregord69246b2008-11-17 16:14:12 +000011668 if (!ClassOrEnumParam)
11669 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011670 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011671 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011672 }
11673
11674 // C++ [over.oper]p8:
11675 // An operator function cannot have default arguments (8.3.6),
11676 // except where explicitly stated below.
11677 //
Mike Stump11289f42009-09-09 15:08:12 +000011678 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011679 // (C++ [over.call]p1).
11680 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011681 for (auto Param : FnDecl->params()) {
11682 if (Param->hasDefaultArg())
11683 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011684 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011685 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011686 }
11687 }
11688
Douglas Gregor6cf08062008-11-10 13:38:07 +000011689 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11690 { false, false, false }
11691#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11692 , { Unary, Binary, MemberOnly }
11693#include "clang/Basic/OperatorKinds.def"
11694 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011695
Douglas Gregor6cf08062008-11-10 13:38:07 +000011696 bool CanBeUnaryOperator = OperatorUses[Op][0];
11697 bool CanBeBinaryOperator = OperatorUses[Op][1];
11698 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011699
11700 // C++ [over.oper]p8:
11701 // [...] Operator functions cannot have more or fewer parameters
11702 // than the number required for the corresponding operator, as
11703 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011704 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011705 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011706 if (Op != OO_Call &&
11707 ((NumParams == 1 && !CanBeUnaryOperator) ||
11708 (NumParams == 2 && !CanBeBinaryOperator) ||
11709 (NumParams < 1) || (NumParams > 2))) {
11710 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011711 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011712 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011713 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011714 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011715 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011716 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011717 assert(CanBeBinaryOperator &&
11718 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011719 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011720 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011721
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011722 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011723 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011724 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011725
Douglas Gregord69246b2008-11-17 16:14:12 +000011726 // Overloaded operators other than operator() cannot be variadic.
11727 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011728 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011729 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011730 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011731 }
11732
11733 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011734 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11735 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011736 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011737 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011738 }
11739
11740 // C++ [over.inc]p1:
11741 // The user-defined function called operator++ implements the
11742 // prefix and postfix ++ operator. If this function is a member
11743 // function with no parameters, or a non-member function with one
11744 // parameter of class or enumeration type, it defines the prefix
11745 // increment operator ++ for objects of that type. If the function
11746 // is a member function with one parameter (which shall be of type
11747 // int) or a non-member function with two parameters (the second
11748 // of which shall be of type int), it defines the postfix
11749 // increment operator ++ for objects of that type.
11750 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11751 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011752 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011753
Richard Smith538b52a2014-01-30 22:24:05 +000011754 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11755 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011756 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011757 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011758 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011759 }
11760
Douglas Gregord69246b2008-11-17 16:14:12 +000011761 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011762}
Chris Lattner3b024a32008-12-17 07:09:26 +000011763
Alexis Huntc88db062010-01-13 09:01:02 +000011764/// CheckLiteralOperatorDeclaration - Check whether the declaration
11765/// of this literal operator function is well-formed. If so, returns
11766/// false; otherwise, emits appropriate diagnostics and returns true.
11767bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011768 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011769 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11770 << FnDecl->getDeclName();
11771 return true;
11772 }
11773
Richard Smith72eebee2012-03-04 09:41:16 +000011774 if (FnDecl->isExternC()) {
11775 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11776 return true;
11777 }
11778
Alexis Huntc88db062010-01-13 09:01:02 +000011779 bool Valid = false;
11780
Richard Smithbcc22fc2012-03-09 08:00:36 +000011781 // This might be the definition of a literal operator template.
11782 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11783 // This might be a specialization of a literal operator template.
11784 if (!TpDecl)
11785 TpDecl = FnDecl->getPrimaryTemplate();
11786
Richard Smithb8b41d32013-10-07 19:57:58 +000011787 // template <char...> type operator "" name() and
11788 // template <class T, T...> type operator "" name() are the only valid
11789 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011790 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011791 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011792 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011793 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11794 if (Params->size() == 1) {
11795 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011796 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011797
Alexis Hunt7dd26172010-04-07 23:11:06 +000011798 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011799 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11800 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11801 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011802 } else if (Params->size() == 2) {
11803 TemplateTypeParmDecl *PmType =
11804 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11805 NonTypeTemplateParmDecl *PmArgs =
11806 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11807
11808 // The second template parameter must be a parameter pack with the
11809 // first template parameter as its type.
11810 if (PmType && PmArgs &&
11811 !PmType->isTemplateParameterPack() &&
11812 PmArgs->isTemplateParameterPack()) {
11813 const TemplateTypeParmType *TArgs =
11814 PmArgs->getType()->getAs<TemplateTypeParmType>();
11815 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11816 TArgs->getIndex() == PmType->getIndex()) {
11817 Valid = true;
11818 if (ActiveTemplateInstantiations.empty())
11819 Diag(FnDecl->getLocation(),
11820 diag::ext_string_literal_operator_template);
11821 }
11822 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011823 }
11824 }
Richard Smith72eebee2012-03-04 09:41:16 +000011825 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011826 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011827 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11828
Richard Smith72eebee2012-03-04 09:41:16 +000011829 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011830
Alexis Hunt079a6f72010-04-07 22:57:35 +000011831 // unsigned long long int, long double, and any character type are allowed
11832 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011833 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11834 Context.hasSameType(T, Context.LongDoubleTy) ||
11835 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011836 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011837 Context.hasSameType(T, Context.Char16Ty) ||
11838 Context.hasSameType(T, Context.Char32Ty)) {
11839 if (++Param == FnDecl->param_end())
11840 Valid = true;
11841 goto FinishedParams;
11842 }
11843
Alexis Hunt079a6f72010-04-07 22:57:35 +000011844 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011845 const PointerType *PT = T->getAs<PointerType>();
11846 if (!PT)
11847 goto FinishedParams;
11848 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011849 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011850 goto FinishedParams;
11851 T = T.getUnqualifiedType();
11852
11853 // Move on to the second parameter;
11854 ++Param;
11855
11856 // If there is no second parameter, the first must be a const char *
11857 if (Param == FnDecl->param_end()) {
11858 if (Context.hasSameType(T, Context.CharTy))
11859 Valid = true;
11860 goto FinishedParams;
11861 }
11862
11863 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11864 // are allowed as the first parameter to a two-parameter function
11865 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011866 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011867 Context.hasSameType(T, Context.Char16Ty) ||
11868 Context.hasSameType(T, Context.Char32Ty)))
11869 goto FinishedParams;
11870
11871 // The second and final parameter must be an std::size_t
11872 T = (*Param)->getType().getUnqualifiedType();
11873 if (Context.hasSameType(T, Context.getSizeType()) &&
11874 ++Param == FnDecl->param_end())
11875 Valid = true;
11876 }
11877
11878 // FIXME: This diagnostic is absolutely terrible.
11879FinishedParams:
11880 if (!Valid) {
11881 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11882 << FnDecl->getDeclName();
11883 return true;
11884 }
11885
Richard Smith768cecc2012-03-09 08:16:22 +000011886 // A parameter-declaration-clause containing a default argument is not
11887 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011888 for (auto Param : FnDecl->params()) {
11889 if (Param->hasDefaultArg()) {
11890 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011891 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011892 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011893 break;
11894 }
11895 }
11896
Richard Smith0df56f42012-03-08 02:39:21 +000011897 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011898 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11899 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011900 // C++11 [usrlit.suffix]p1:
11901 // Literal suffix identifiers that do not start with an underscore
11902 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011903 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11904 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011905 }
Richard Smith0df56f42012-03-08 02:39:21 +000011906
Alexis Huntc88db062010-01-13 09:01:02 +000011907 return false;
11908}
11909
Douglas Gregor07665a62009-01-05 19:45:36 +000011910/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11911/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011912/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11913/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011914/// the '{' brace. Otherwise, this linkage specification does not
11915/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011916Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011917 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011918 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011919 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11920 if (!Lit->isAscii()) {
11921 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11922 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011923 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011924 }
11925
11926 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011927 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011928 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011929 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011930 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011931 Language = LinkageSpecDecl::lang_cxx;
11932 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011933 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11934 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011935 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011936 }
Mike Stump11289f42009-09-09 15:08:12 +000011937
Chris Lattner438e5012008-12-17 07:13:27 +000011938 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011939
Richard Smith4ee696d2014-02-17 23:25:27 +000011940 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11941 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011942 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011943 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011944 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011945 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011946}
11947
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011948/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011949/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11950/// valid, it's the position of the closing '}' brace in a linkage
11951/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011952Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011953 Decl *LinkageSpec,
11954 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011955 if (RBraceLoc.isValid()) {
11956 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11957 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011958 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011959 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011960 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011961}
11962
Michael Han84324352013-02-22 17:15:32 +000011963Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11964 AttributeList *AttrList,
11965 SourceLocation SemiLoc) {
11966 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11967 // Attribute declarations appertain to empty declaration so we handle
11968 // them here.
11969 if (AttrList)
11970 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011971
Michael Han84324352013-02-22 17:15:32 +000011972 CurContext->addDecl(ED);
11973 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011974}
11975
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011976/// \brief Perform semantic analysis for the variable declaration that
11977/// occurs within a C++ catch clause, returning the newly-created
11978/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011979VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011980 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011981 SourceLocation StartLoc,
11982 SourceLocation Loc,
11983 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011984 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011985 QualType ExDeclType = TInfo->getType();
11986
Sebastian Redl54c04d42008-12-22 19:15:10 +000011987 // Arrays and functions decay.
11988 if (ExDeclType->isArrayType())
11989 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11990 else if (ExDeclType->isFunctionType())
11991 ExDeclType = Context.getPointerType(ExDeclType);
11992
11993 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11994 // The exception-declaration shall not denote a pointer or reference to an
11995 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011996 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011997 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011998 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011999 Invalid = true;
12000 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012001
Sebastian Redl54c04d42008-12-22 19:15:10 +000012002 QualType BaseType = ExDeclType;
12003 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000012004 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012005 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012006 BaseType = Ptr->getPointeeType();
12007 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000012008 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000012009 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000012010 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012011 BaseType = Ref->getPointeeType();
12012 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000012013 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012014 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000012015 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000012016 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000012017 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012018
Mike Stump11289f42009-09-09 15:08:12 +000012019 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012020 RequireNonAbstractType(Loc, ExDeclType,
12021 diag::err_abstract_type_in_decl,
12022 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000012023 Invalid = true;
12024
John McCall2ca705e2010-07-24 00:37:23 +000012025 // Only the non-fragile NeXT runtime currently supports C++ catches
12026 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012027 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000012028 QualType T = ExDeclType;
12029 if (const ReferenceType *RT = T->getAs<ReferenceType>())
12030 T = RT->getPointeeType();
12031
12032 if (T->isObjCObjectType()) {
12033 Diag(Loc, diag::err_objc_object_catch);
12034 Invalid = true;
12035 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000012036 // FIXME: should this be a test for macosx-fragile specifically?
12037 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000012038 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000012039 }
12040 }
12041
Abramo Bagnaradff19302011-03-08 08:55:46 +000012042 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000012043 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000012044 ExDecl->setExceptionVariable(true);
12045
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012046 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012047 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012048 Invalid = true;
12049
Douglas Gregor750734c2011-07-06 18:14:43 +000012050 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000012051 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000012052 // Insulate this from anything else we might currently be parsing.
12053 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12054
Douglas Gregor6de584c2010-03-05 23:38:39 +000012055 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000012056 // The object declared in an exception-declaration or, if the
12057 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000012058 // copy-initialized (8.5) from the exception object. [...]
12059 // The object is destroyed when the handler exits, after the destruction
12060 // of any automatic objects initialized within the handler.
12061 //
Nick Lewycky0f292892013-09-22 10:06:57 +000012062 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000012063 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000012064 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000012065
12066 InitializedEntity entity =
12067 InitializedEntity::InitializeVariable(ExDecl);
12068 InitializationKind initKind =
12069 InitializationKind::CreateCopy(Loc, SourceLocation());
12070
12071 Expr *opaqueValue =
12072 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000012073 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12074 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000012075 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000012076 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000012077 else {
12078 // If the constructor used was non-trivial, set this as the
12079 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012080 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000012081 if (!construct->getConstructor()->isTrivial()) {
12082 Expr *init = MaybeCreateExprWithCleanups(construct);
12083 ExDecl->setInit(init);
12084 }
12085
12086 // And make sure it's destructable.
12087 FinalizeVarWithDestructor(ExDecl, recordType);
12088 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000012089 }
12090 }
12091
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012092 if (Invalid)
12093 ExDecl->setInvalidDecl();
12094
12095 return ExDecl;
12096}
12097
12098/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12099/// handler.
John McCall48871652010-08-21 09:40:31 +000012100Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000012101 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000012102 bool Invalid = D.isInvalidType();
12103
12104 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000012105 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12106 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000012107 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12108 D.getIdentifierLoc());
12109 Invalid = true;
12110 }
12111
Sebastian Redl54c04d42008-12-22 19:15:10 +000012112 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012113 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000012114 LookupOrdinaryName,
12115 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012116 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012117 // it contains any previous declaration, except for function parameters in
12118 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012119 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012120 if (isDeclInScope(PrevDecl, CurContext, S)) {
12121 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12122 << D.getIdentifier();
12123 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12124 Invalid = true;
12125 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012126 // Maybe we will complain about the shadowed template parameter.
12127 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012128 }
12129
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012130 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012131 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12132 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012133 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012134 }
12135
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012136 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012137 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012138 D.getIdentifierLoc(),
12139 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012140 if (Invalid)
12141 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012142
Sebastian Redl54c04d42008-12-22 19:15:10 +000012143 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012144 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012145 PushOnScopeChains(ExDecl, S);
12146 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012147 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012148
Douglas Gregor758a8692009-06-17 21:51:59 +000012149 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012150 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012151}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012152
Abramo Bagnaraea947882011-03-08 16:41:52 +000012153Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012154 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012155 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012156 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012157 StringLiteral *AssertMessage =
12158 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012159
Richard Smithded9c2e2012-07-11 22:37:56 +000012160 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012161 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012162
12163 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12164 AssertMessage, RParenLoc, false);
12165}
12166
12167Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12168 Expr *AssertExpr,
12169 StringLiteral *AssertMessage,
12170 SourceLocation RParenLoc,
12171 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012172 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012173 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12174 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012175 // In a static_assert-declaration, the constant-expression shall be a
12176 // constant expression that can be contextually converted to bool.
12177 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12178 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012179 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012180
Richard Smith902ca212011-12-14 23:32:26 +000012181 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012182 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012183 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012184 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012185 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012186
Richard Smithded9c2e2012-07-11 22:37:56 +000012187 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012188 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012189 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012190 if (AssertMessage)
12191 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012192 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012193 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012194 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012195 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012196 }
Mike Stump11289f42009-09-09 15:08:12 +000012197
Abramo Bagnaraea947882011-03-08 16:41:52 +000012198 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012199 AssertExpr, AssertMessage, RParenLoc,
12200 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012201
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012202 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012203 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012204}
Sebastian Redlf769df52009-03-24 22:27:57 +000012205
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012206/// \brief Perform semantic analysis of the given friend type declaration.
12207///
12208/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012209FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012210 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012211 TypeSourceInfo *TSInfo) {
12212 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12213
12214 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012215 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012216
Richard Smithc8239732011-10-18 21:39:00 +000012217 // C++03 [class.friend]p2:
12218 // An elaborated-type-specifier shall be used in a friend declaration
12219 // for a class.*
12220 //
12221 // * The class-key of the elaborated-type-specifier is required.
12222 if (!ActiveTemplateInstantiations.empty()) {
12223 // Do not complain about the form of friend template types during
12224 // template instantiation; we will already have complained when the
12225 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012226 } else {
12227 if (!T->isElaboratedTypeSpecifier()) {
12228 // If we evaluated the type to a record type, suggest putting
12229 // a tag in front.
12230 if (const RecordType *RT = T->getAs<RecordType>()) {
12231 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012232
12233 SmallString<16> InsertionText(" ");
12234 InsertionText += RD->getKindName();
12235
Nick Lewycky36722d22013-02-06 05:59:33 +000012236 Diag(TypeRange.getBegin(),
12237 getLangOpts().CPlusPlus11 ?
12238 diag::warn_cxx98_compat_unelaborated_friend_type :
12239 diag::ext_unelaborated_friend_type)
12240 << (unsigned) RD->getTagKind()
12241 << T
Craig Topper07fa1762015-11-15 02:31:46 +000012242 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000012243 InsertionText);
12244 } else {
12245 Diag(FriendLoc,
12246 getLangOpts().CPlusPlus11 ?
12247 diag::warn_cxx98_compat_nonclass_type_friend :
12248 diag::ext_nonclass_type_friend)
12249 << T
12250 << TypeRange;
12251 }
12252 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012253 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012254 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012255 diag::warn_cxx98_compat_enum_friend :
12256 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012257 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012258 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012259 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012260
Nick Lewycky36722d22013-02-06 05:59:33 +000012261 // C++11 [class.friend]p3:
12262 // A friend declaration that does not declare a function shall have one
12263 // of the following forms:
12264 // friend elaborated-type-specifier ;
12265 // friend simple-type-specifier ;
12266 // friend typename-specifier ;
12267 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12268 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12269 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012270
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012271 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012272 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012273 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012274 return FriendDecl::Create(Context, CurContext,
12275 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12276 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012277}
12278
John McCallace48cd2010-10-19 01:40:49 +000012279/// Handle a friend tag declaration where the scope specifier was
12280/// templated.
12281Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12282 unsigned TagSpec, SourceLocation TagLoc,
12283 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012284 IdentifierInfo *Name,
12285 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012286 AttributeList *Attr,
12287 MultiTemplateParamsArg TempParamLists) {
12288 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12289
12290 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012291 bool Invalid = false;
12292
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012293 if (TemplateParameterList *TemplateParams =
12294 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012295 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012296 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012297 if (TemplateParams->size() > 0) {
12298 // This is a declaration of a class template.
12299 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012300 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012301
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012302 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12303 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012304 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012305 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012306 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012307 } else {
12308 // The "template<>" header is extraneous.
12309 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12310 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12311 isExplicitSpecialization = true;
12312 }
12313 }
12314
Craig Topperc3ec1492014-05-26 06:22:03 +000012315 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012316
John McCallace48cd2010-10-19 01:40:49 +000012317 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012318 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012319 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012320 isAllExplicitSpecializations = false;
12321 break;
12322 }
12323 }
12324
12325 // FIXME: don't ignore attributes.
12326
12327 // If it's explicit specializations all the way down, just forget
12328 // about the template header and build an appropriate non-templated
12329 // friend. TODO: for source fidelity, remember the headers.
12330 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012331 if (SS.isEmpty()) {
12332 bool Owned = false;
12333 bool IsDependent = false;
12334 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012335 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012336 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012337 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012338 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012339 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012340 /*UnderlyingType=*/TypeResult(),
12341 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012342 }
Richard Smith649c7b062014-01-08 00:56:48 +000012343
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012344 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012345 ElaboratedTypeKeyword Keyword
12346 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012347 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012348 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012349 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012350 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012351
12352 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12353 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012354 DependentNameTypeLoc TL =
12355 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012356 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012357 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012358 TL.setNameLoc(NameLoc);
12359 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012360 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012361 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012362 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012363 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012364 }
12365
12366 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012367 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012368 Friend->setAccess(AS_public);
12369 CurContext->addDecl(Friend);
12370 return Friend;
12371 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012372
12373 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12374
12375
John McCallace48cd2010-10-19 01:40:49 +000012376
12377 // Handle the case of a templated-scope friend class. e.g.
12378 // template <class T> class A<T>::B;
12379 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012380 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12381 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012382 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12383 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12384 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012385 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012386 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012387 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012388 TL.setNameLoc(NameLoc);
12389
12390 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012391 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012392 Friend->setAccess(AS_public);
12393 Friend->setUnsupportedFriend(true);
12394 CurContext->addDecl(Friend);
12395 return Friend;
12396}
12397
12398
John McCall11083da2009-09-16 22:47:08 +000012399/// Handle a friend type declaration. This works in tandem with
12400/// ActOnTag.
12401///
12402/// Notes on friend class templates:
12403///
12404/// We generally treat friend class declarations as if they were
12405/// declaring a class. So, for example, the elaborated type specifier
12406/// in a friend declaration is required to obey the restrictions of a
12407/// class-head (i.e. no typedefs in the scope chain), template
12408/// parameters are required to match up with simple template-ids, &c.
12409/// However, unlike when declaring a template specialization, it's
12410/// okay to refer to a template specialization without an empty
12411/// template parameter declaration, e.g.
12412/// friend class A<T>::B<unsigned>;
12413/// We permit this as a special case; if there are any template
12414/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012415/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012416Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012417 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012418 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012419
12420 assert(DS.isFriendSpecified());
12421 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12422
John McCall11083da2009-09-16 22:47:08 +000012423 // Try to convert the decl specifier to a type. This works for
12424 // friend templates because ActOnTag never produces a ClassTemplateDecl
12425 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012426 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012427 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12428 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012429 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012430 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012431
Douglas Gregor6c110f32010-12-16 01:14:37 +000012432 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012433 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012434
John McCall11083da2009-09-16 22:47:08 +000012435 // This is definitely an error in C++98. It's probably meant to
12436 // be forbidden in C++0x, too, but the specification is just
12437 // poorly written.
12438 //
12439 // The problem is with declarations like the following:
12440 // template <T> friend A<T>::foo;
12441 // where deciding whether a class C is a friend or not now hinges
12442 // on whether there exists an instantiation of A that causes
12443 // 'foo' to equal C. There are restrictions on class-heads
12444 // (which we declare (by fiat) elaborated friend declarations to
12445 // be) that makes this tractable.
12446 //
12447 // FIXME: handle "template <> friend class A<T>;", which
12448 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012449 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012450 Diag(Loc, diag::err_tagless_friend_type_template)
12451 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012452 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012453 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012454
John McCallaa74a0c2009-08-28 07:59:38 +000012455 // C++98 [class.friend]p1: A friend of a class is a function
12456 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012457 // This is fixed in DR77, which just barely didn't make the C++03
12458 // deadline. It's also a very silly restriction that seriously
12459 // affects inner classes and which nobody else seems to implement;
12460 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012461 //
12462 // But note that we could warn about it: it's always useless to
12463 // friend one of your own members (it's not, however, worthless to
12464 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012465
John McCall11083da2009-09-16 22:47:08 +000012466 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012467 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012468 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012469 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012470 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012471 TSI,
John McCall11083da2009-09-16 22:47:08 +000012472 DS.getFriendSpecLoc());
12473 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012474 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012475
12476 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012477 return nullptr;
12478
John McCall11083da2009-09-16 22:47:08 +000012479 D->setAccess(AS_public);
12480 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012481
John McCall48871652010-08-21 09:40:31 +000012482 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012483}
12484
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012485NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12486 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012487 const DeclSpec &DS = D.getDeclSpec();
12488
12489 assert(DS.isFriendSpecified());
12490 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12491
12492 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012493 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012494
12495 // C++ [class.friend]p1
12496 // A friend of a class is a function or class....
12497 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012498 // It *doesn't* see through dependent types, which is correct
12499 // according to [temp.arg.type]p3:
12500 // If a declaration acquires a function type through a
12501 // type dependent on a template-parameter and this causes
12502 // a declaration that does not use the syntactic form of a
12503 // function declarator to have a function type, the program
12504 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012505 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012506 Diag(Loc, diag::err_unexpected_friend);
12507
12508 // It might be worthwhile to try to recover by creating an
12509 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012510 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012511 }
12512
12513 // C++ [namespace.memdef]p3
12514 // - If a friend declaration in a non-local class first declares a
12515 // class or function, the friend class or function is a member
12516 // of the innermost enclosing namespace.
12517 // - The name of the friend is not found by simple name lookup
12518 // until a matching declaration is provided in that namespace
12519 // scope (either before or after the class declaration granting
12520 // friendship).
12521 // - If a friend function is called, its name may be found by the
12522 // name lookup that considers functions from namespaces and
12523 // classes associated with the types of the function arguments.
12524 // - When looking for a prior declaration of a class or a function
12525 // declared as a friend, scopes outside the innermost enclosing
12526 // namespace scope are not considered.
12527
John McCallde3fd222010-10-12 23:13:28 +000012528 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012529 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12530 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012531 assert(Name);
12532
Douglas Gregor6c110f32010-12-16 01:14:37 +000012533 // Check for unexpanded parameter packs.
12534 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12535 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12536 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012537 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012538
John McCall07e91c02009-08-06 02:15:43 +000012539 // The context we found the declaration in, or in which we should
12540 // create the declaration.
12541 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012542 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012543 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012544 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012545
Richard Smith114394f2013-08-09 04:35:01 +000012546 // There are five cases here.
12547 // - There's no scope specifier and we're in a local class. Only look
12548 // for functions declared in the immediately-enclosing block scope.
12549 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012550 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012551 if ((SS.isInvalid() || !SS.isSet()) &&
12552 (FunctionContainingLocalClass =
12553 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12554 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012555 // If a friend declaration appears in a local class and the name
12556 // specified is an unqualified name, a prior declaration is
12557 // looked up without considering scopes that are outside the
12558 // innermost enclosing non-class scope. For a friend function
12559 // declaration, if there is no prior declaration, the program is
12560 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012561
12562 // Find the innermost enclosing non-class scope. This is the block
12563 // scope containing the local class definition (or for a nested class,
12564 // the outer local class).
12565 DCScope = S->getFnParent();
12566
12567 // Look up the function name in the scope.
12568 Previous.clear(LookupLocalFriendName);
12569 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12570
12571 if (!Previous.empty()) {
12572 // All possible previous declarations must have the same context:
12573 // either they were declared at block scope or they are members of
12574 // one of the enclosing local classes.
12575 DC = Previous.getRepresentativeDecl()->getDeclContext();
12576 } else {
12577 // This is ill-formed, but provide the context that we would have
12578 // declared the function in, if we were permitted to, for error recovery.
12579 DC = FunctionContainingLocalClass;
12580 }
Richard Smith541b38b2013-09-20 01:15:31 +000012581 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012582
12583 // C++ [class.friend]p6:
12584 // A function can be defined in a friend declaration of a class if and
12585 // only if the class is a non-local class (9.8), the function name is
12586 // unqualified, and the function has namespace scope.
12587 if (D.isFunctionDefinition()) {
12588 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12589 }
12590
12591 // - There's no scope specifier, in which case we just go to the
12592 // appropriate scope and look for a function or function template
12593 // there as appropriate.
12594 } else if (SS.isInvalid() || !SS.isSet()) {
12595 // C++11 [namespace.memdef]p3:
12596 // If the name in a friend declaration is neither qualified nor
12597 // a template-id and the declaration is a function or an
12598 // elaborated-type-specifier, the lookup to determine whether
12599 // the entity has been previously declared shall not consider
12600 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012601 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012602
John McCallf7cfb222010-10-13 05:45:15 +000012603 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012604 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012605
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012606 // Skip class contexts. If someone can cite chapter and verse
12607 // for this behavior, that would be nice --- it's what GCC and
12608 // EDG do, and it seems like a reasonable intent, but the spec
12609 // really only says that checks for unqualified existing
12610 // declarations should stop at the nearest enclosing namespace,
12611 // not that they should only consider the nearest enclosing
12612 // namespace.
12613 while (DC->isRecord())
12614 DC = DC->getParent();
12615
12616 DeclContext *LookupDC = DC;
12617 while (LookupDC->isTransparentContext())
12618 LookupDC = LookupDC->getParent();
12619
12620 while (true) {
12621 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012622
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012623 if (!Previous.empty()) {
12624 DC = LookupDC;
12625 break;
John McCallf4776592010-10-14 22:22:28 +000012626 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012627
12628 if (isTemplateId) {
12629 if (isa<TranslationUnitDecl>(LookupDC)) break;
12630 } else {
12631 if (LookupDC->isFileContext()) break;
12632 }
12633 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012634 }
12635
John McCallccbc0322010-10-13 06:22:15 +000012636 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012637
John McCallde3fd222010-10-12 23:13:28 +000012638 // - There's a non-dependent scope specifier, in which case we
12639 // compute it and do a previous lookup there for a function
12640 // or function template.
12641 } else if (!SS.getScopeRep()->isDependent()) {
12642 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012643 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012644
Craig Topperc3ec1492014-05-26 06:22:03 +000012645 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012646
12647 LookupQualifiedName(Previous, DC);
12648
12649 // Ignore things found implicitly in the wrong scope.
12650 // TODO: better diagnostics for this case. Suggesting the right
12651 // qualified scope would be nice...
12652 LookupResult::Filter F = Previous.makeFilter();
12653 while (F.hasNext()) {
12654 NamedDecl *D = F.next();
12655 if (!DC->InEnclosingNamespaceSetOf(
12656 D->getDeclContext()->getRedeclContext()))
12657 F.erase();
12658 }
12659 F.done();
12660
12661 if (Previous.empty()) {
12662 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012663 Diag(Loc, diag::err_qualified_friend_not_found)
12664 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012665 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012666 }
12667
12668 // C++ [class.friend]p1: A friend of a class is a function or
12669 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012670 if (DC->Equals(CurContext))
12671 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012672 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012673 diag::warn_cxx98_compat_friend_is_member :
12674 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012675
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012676 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012677 // C++ [class.friend]p6:
12678 // A function can be defined in a friend declaration of a class if and
12679 // only if the class is a non-local class (9.8), the function name is
12680 // unqualified, and the function has namespace scope.
12681 SemaDiagnosticBuilder DB
12682 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12683
12684 DB << SS.getScopeRep();
12685 if (DC->isFileContext())
12686 DB << FixItHint::CreateRemoval(SS.getRange());
12687 SS.clear();
12688 }
John McCallde3fd222010-10-12 23:13:28 +000012689
12690 // - There's a scope specifier that does not match any template
12691 // parameter lists, in which case we use some arbitrary context,
12692 // create a method or method template, and wait for instantiation.
12693 // - There's a scope specifier that does match some template
12694 // parameter lists, which we don't handle right now.
12695 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012696 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012697 // C++ [class.friend]p6:
12698 // A function can be defined in a friend declaration of a class if and
12699 // only if the class is a non-local class (9.8), the function name is
12700 // unqualified, and the function has namespace scope.
12701 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12702 << SS.getScopeRep();
12703 }
12704
John McCallde3fd222010-10-12 23:13:28 +000012705 DC = CurContext;
12706 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012707 }
David Majnemere14d5302015-09-30 22:07:43 +000012708
John McCallf7cfb222010-10-13 05:45:15 +000012709 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000012710 int DiagArg = -1;
12711 switch (D.getName().getKind()) {
12712 case UnqualifiedId::IK_ConstructorTemplateId:
12713 case UnqualifiedId::IK_ConstructorName:
12714 DiagArg = 0;
12715 break;
12716 case UnqualifiedId::IK_DestructorName:
12717 DiagArg = 1;
12718 break;
12719 case UnqualifiedId::IK_ConversionFunctionId:
12720 DiagArg = 2;
12721 break;
12722 case UnqualifiedId::IK_Identifier:
12723 case UnqualifiedId::IK_ImplicitSelfParam:
12724 case UnqualifiedId::IK_LiteralOperatorId:
12725 case UnqualifiedId::IK_OperatorFunctionId:
12726 case UnqualifiedId::IK_TemplateId:
12727 break;
David Majnemere14d5302015-09-30 22:07:43 +000012728 }
John McCall07e91c02009-08-06 02:15:43 +000012729 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000012730 if (DiagArg >= 0) {
12731 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000012732 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012733 }
John McCall07e91c02009-08-06 02:15:43 +000012734 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012735
Douglas Gregordd847ba2011-11-03 16:37:14 +000012736 // FIXME: This is an egregious hack to cope with cases where the scope stack
12737 // does not contain the declaration context, i.e., in an out-of-line
12738 // definition of a class.
12739 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12740 if (!DCScope) {
12741 FakeDCScope.setEntity(DC);
12742 DCScope = &FakeDCScope;
12743 }
Richard Smith114394f2013-08-09 04:35:01 +000012744
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012745 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012746 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012747 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012748 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012749
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012750 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012751
Richard Smith114394f2013-08-09 04:35:01 +000012752 // If we performed typo correction, we might have added a scope specifier
12753 // and changed the decl context.
12754 DC = ND->getDeclContext();
12755
John McCall759e32b2009-08-31 22:39:49 +000012756 // Add the function declaration to the appropriate lookup tables,
12757 // adjusting the redeclarations list as necessary. We don't
12758 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012759 //
John McCall759e32b2009-08-31 22:39:49 +000012760 // Also update the scope-based lookup if the target context's
12761 // lookup context is in lexical scope.
12762 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012763 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012764 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012765 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012766 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012767 }
John McCallaa74a0c2009-08-28 07:59:38 +000012768
12769 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012770 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012771 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012772 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012773 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012774
John McCalla0a96892012-08-10 03:15:35 +000012775 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012776 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012777 } else {
12778 if (DC->isRecord()) CheckFriendAccess(ND);
12779
John McCall2c2eb122010-10-16 06:59:13 +000012780 FunctionDecl *FD;
12781 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12782 FD = FTD->getTemplatedDecl();
12783 else
12784 FD = cast<FunctionDecl>(ND);
12785
David Majnemer502b0ed2013-06-25 23:09:30 +000012786 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12787 // default argument expression, that declaration shall be a definition
12788 // and shall be the only declaration of the function or function
12789 // template in the translation unit.
12790 if (functionDeclHasDefaultArgument(FD)) {
12791 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12792 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12793 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12794 } else if (!D.isFunctionDefinition())
12795 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12796 }
12797
John McCall2c2eb122010-10-16 06:59:13 +000012798 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012799 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12800 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12801 << SS.getScopeRep() << SS.getRange()
12802 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012803 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012804 }
John McCall2c2eb122010-10-16 06:59:13 +000012805 }
John McCallde3fd222010-10-12 23:13:28 +000012806
John McCall48871652010-08-21 09:40:31 +000012807 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012808}
12809
John McCall48871652010-08-21 09:40:31 +000012810void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12811 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012812
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012813 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012814 if (!Fn) {
12815 Diag(DelLoc, diag::err_deleted_non_function);
12816 return;
12817 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012818
Douglas Gregorec9fd132012-01-14 16:38:05 +000012819 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012820 // Don't consider the implicit declaration we generate for explicit
12821 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012822 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12823 Prev->getPreviousDecl()) &&
12824 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012825 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012826 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12827 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12828 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012829 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012830 // If the declaration wasn't the first, we delete the function anyway for
12831 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012832 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012833 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012834
Nico Rieck9de0a572014-05-29 16:51:19 +000012835 // dllimport/dllexport cannot be deleted.
12836 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12837 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12838 Fn->setInvalidDecl();
12839 }
12840
Richard Smithb4d2a152013-04-02 19:38:47 +000012841 if (Fn->isDeleted())
12842 return;
12843
12844 // See if we're deleting a function which is already known to override a
12845 // non-deleted virtual function.
12846 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12847 bool IssuedDiagnostic = false;
12848 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12849 E = MD->end_overridden_methods();
12850 I != E; ++I) {
12851 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12852 if (!IssuedDiagnostic) {
12853 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12854 IssuedDiagnostic = true;
12855 }
12856 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12857 }
12858 }
12859 }
12860
Richard Smithb63b6ee2014-01-22 01:43:19 +000012861 // C++11 [basic.start.main]p3:
12862 // A program that defines main as deleted [...] is ill-formed.
12863 if (Fn->isMain())
12864 Diag(DelLoc, diag::err_deleted_main);
12865
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012866 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012867}
Sebastian Redl4c018662009-04-27 21:33:24 +000012868
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012869void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012870 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012871
12872 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012873 if (MD->getParent()->isDependentType()) {
12874 MD->setDefaulted();
12875 MD->setExplicitlyDefaulted();
12876 return;
12877 }
12878
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012879 CXXSpecialMember Member = getSpecialMember(MD);
12880 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012881 if (!MD->isInvalidDecl())
12882 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012883 return;
12884 }
12885
12886 MD->setDefaulted();
12887 MD->setExplicitlyDefaulted();
12888
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012889 // If this definition appears within the record, do the checking when
12890 // the record is complete.
12891 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012892 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012893 // Find the uninstantiated declaration that actually had the '= default'
12894 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012895 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012896
Richard Smith3901dfe2013-03-27 00:22:47 +000012897 // If the method was defaulted on its first declaration, we will have
12898 // already performed the checking in CheckCompletedCXXClass. Such a
12899 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012900 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012901 return;
12902
Richard Smithd3b5c9082012-07-27 04:22:15 +000012903 CheckExplicitlyDefaultedSpecialMember(MD);
12904
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012905 if (MD->isInvalidDecl())
12906 return;
12907
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012908 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012909 case CXXDefaultConstructor:
12910 DefineImplicitDefaultConstructor(DefaultLoc,
12911 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012912 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012913 case CXXCopyConstructor:
12914 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012915 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012916 case CXXCopyAssignment:
12917 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012918 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012919 case CXXDestructor:
12920 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012921 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012922 case CXXMoveConstructor:
12923 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012924 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012925 case CXXMoveAssignment:
12926 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012927 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012928 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012929 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012930 }
12931 } else {
12932 Diag(DefaultLoc, diag::err_default_special_members);
12933 }
12934}
12935
Sebastian Redl4c018662009-04-27 21:33:24 +000012936static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000012937 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012938 if (!SubStmt)
12939 continue;
12940 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012941 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012942 diag::err_return_in_constructor_handler);
12943 if (!isa<Expr>(SubStmt))
12944 SearchForReturnInStmt(Self, SubStmt);
12945 }
12946}
12947
12948void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12949 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12950 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12951 SearchForReturnInStmt(*this, Handler);
12952 }
12953}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012954
David Blaikie68f71a32013-01-18 23:03:15 +000012955bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012956 const CXXMethodDecl *Old) {
12957 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12958 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12959
12960 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12961
12962 // If the calling conventions match, everything is fine
12963 if (NewCC == OldCC)
12964 return false;
12965
Hans Wennborg2545efe2013-12-11 17:42:11 +000012966 // If the calling conventions mismatch because the new function is static,
12967 // suppress the calling convention mismatch error; the error about static
12968 // function override (err_static_overrides_virtual from
12969 // Sema::CheckFunctionDeclaration) is more clear.
12970 if (New->getStorageClass() == SC_Static)
12971 return false;
12972
Reid Kleckner78af0702013-08-27 23:08:25 +000012973 Diag(New->getLocation(),
12974 diag::err_conflicting_overriding_cc_attributes)
12975 << New->getDeclName() << New->getType() << Old->getType();
12976 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12977 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012978}
12979
Mike Stump11289f42009-09-09 15:08:12 +000012980bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012981 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012982 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12983 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012984
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012985 if (Context.hasSameType(NewTy, OldTy) ||
12986 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012987 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012988
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012989 // Check if the return types are covariant
12990 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012991
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012992 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012993 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12994 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012995 NewClassTy = NewPT->getPointeeType();
12996 OldClassTy = OldPT->getPointeeType();
12997 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012998 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12999 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13000 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13001 NewClassTy = NewRT->getPointeeType();
13002 OldClassTy = OldRT->getPointeeType();
13003 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013004 }
13005 }
Mike Stump11289f42009-09-09 15:08:12 +000013006
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013007 // The return types aren't either both pointers or references to a class type.
13008 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000013009 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013010 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013011 << New->getDeclName() << NewTy << OldTy
13012 << New->getReturnTypeSourceRange();
13013 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13014 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000013015
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013016 return true;
13017 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013018
Anders Carlssone60365b2009-12-31 18:34:24 +000013019 // C++ [class.virtual]p6:
13020 // If the return type of D::f differs from the return type of B::f, the
13021 // class type in the return type of D::f shall be complete at the point of
13022 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000013023 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13024 if (!RT->isBeingDefined() &&
13025 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000013026 diag::err_covariant_return_incomplete,
13027 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000013028 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000013029 }
Anders Carlssone60365b2009-12-31 18:34:24 +000013030
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000013031 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013032 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000013033 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000013034 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13035 << New->getDeclName() << NewTy << OldTy
13036 << New->getReturnTypeSourceRange();
13037 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13038 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013039 return true;
13040 }
Mike Stump11289f42009-09-09 15:08:12 +000013041
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013042 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013043 if (CheckDerivedToBaseConversion(
13044 NewClassTy, OldClassTy,
13045 diag::err_covariant_return_inaccessible_base,
13046 diag::err_covariant_return_ambiguous_derived_to_base_conv,
13047 New->getLocation(), New->getReturnTypeSourceRange(),
13048 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000013049 // FIXME: this note won't trigger for delayed access control
13050 // diagnostics, and it's impossible to get an undelayed error
13051 // here from access control during the original parse because
13052 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013053 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13054 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013055 return true;
13056 }
13057 }
Mike Stump11289f42009-09-09 15:08:12 +000013058
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013059 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013060 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013061 Diag(New->getLocation(),
13062 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013063 << New->getDeclName() << NewTy << OldTy
13064 << New->getReturnTypeSourceRange();
13065 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13066 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013067 return true;
13068 };
Mike Stump11289f42009-09-09 15:08:12 +000013069
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013070
13071 // The new class type must have the same or less qualifiers as the old type.
13072 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13073 Diag(New->getLocation(),
13074 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013075 << New->getDeclName() << NewTy << OldTy
13076 << New->getReturnTypeSourceRange();
13077 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13078 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013079 return true;
13080 };
Mike Stump11289f42009-09-09 15:08:12 +000013081
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013082 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013083}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013084
Douglas Gregor21920e372009-12-01 17:24:26 +000013085/// \brief Mark the given method pure.
13086///
13087/// \param Method the method to be marked pure.
13088///
13089/// \param InitRange the source range that covers the "0" initializer.
13090bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013091 SourceLocation EndLoc = InitRange.getEnd();
13092 if (EndLoc.isValid())
13093 Method->setRangeEnd(EndLoc);
13094
Douglas Gregor21920e372009-12-01 17:24:26 +000013095 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13096 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000013097 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013098 }
Douglas Gregor21920e372009-12-01 17:24:26 +000013099
13100 if (!Method->isInvalidDecl())
13101 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13102 << Method->getDeclName() << InitRange;
13103 return true;
13104}
13105
Richard Smith9ba0fec2015-06-30 01:28:56 +000013106void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13107 if (D->getFriendObjectKind())
13108 Diag(D->getLocation(), diag::err_pure_friend);
13109 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13110 CheckPureMethod(M, ZeroLoc);
13111 else
13112 Diag(D->getLocation(), diag::err_illegal_initializer);
13113}
13114
Douglas Gregor926410d2012-02-21 02:22:07 +000013115/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013116static bool isStaticDataMember(const Decl *D) {
13117 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13118 return Var->isStaticDataMember();
13119
13120 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000013121}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013122
John McCall1f4ee7b2009-12-19 09:28:58 +000013123/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13124/// an initializer for the out-of-line declaration 'Dcl'. The scope
13125/// is a fresh scope pushed for just this purpose.
13126///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013127/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13128/// static data member of class X, names should be looked up in the scope of
13129/// class X.
John McCall48871652010-08-21 09:40:31 +000013130void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013131 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013132 if (!D || D->isInvalidDecl())
13133 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013134
Richard Smitha2302242013-12-05 07:51:02 +000013135 // We will always have a nested name specifier here, but this declaration
13136 // might not be out of line if the specifier names the current namespace:
13137 // extern int n;
13138 // int ::n = 0;
13139 if (D->isOutOfLine())
13140 EnterDeclaratorContext(S, D->getDeclContext());
13141
Douglas Gregor926410d2012-02-21 02:22:07 +000013142 // If we are parsing the initializer for a static data member, push a
13143 // new expression evaluation context that is associated with this static
13144 // data member.
13145 if (isStaticDataMember(D))
13146 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013147}
13148
13149/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013150/// initializer for the out-of-line declaration 'D'.
13151void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013152 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013153 if (!D || D->isInvalidDecl())
13154 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013155
Douglas Gregor926410d2012-02-21 02:22:07 +000013156 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013157 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013158
Richard Smitha2302242013-12-05 07:51:02 +000013159 if (D->isOutOfLine())
13160 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013161}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013162
13163/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13164/// C++ if/switch/while/for statement.
13165/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013166DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013167 // C++ 6.4p2:
13168 // The declarator shall not specify a function or an array.
13169 // The type-specifier-seq shall not contain typedef and shall not declare a
13170 // new class or enumeration.
13171 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13172 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013173
13174 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013175 if (!Dcl)
13176 return true;
13177
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013178 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13179 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013180 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013181 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013182 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013183
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013184 return Dcl;
13185}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013186
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013187void Sema::LoadExternalVTableUses() {
13188 if (!ExternalSource)
13189 return;
13190
13191 SmallVector<ExternalVTableUse, 4> VTables;
13192 ExternalSource->ReadUsedVTables(VTables);
13193 SmallVector<VTableUse, 4> NewUses;
13194 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13195 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13196 = VTablesUsed.find(VTables[I].Record);
13197 // Even if a definition wasn't required before, it may be required now.
13198 if (Pos != VTablesUsed.end()) {
13199 if (!Pos->second && VTables[I].DefinitionRequired)
13200 Pos->second = true;
13201 continue;
13202 }
13203
13204 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13205 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13206 }
13207
13208 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13209}
13210
Douglas Gregor88d292c2010-05-13 16:44:06 +000013211void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13212 bool DefinitionRequired) {
13213 // Ignore any vtable uses in unevaluated operands or for classes that do
13214 // not have a vtable.
13215 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013216 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013217 return;
13218
Douglas Gregor88d292c2010-05-13 16:44:06 +000013219 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013220 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013221 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13222 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13223 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13224 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013225 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013226 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013227 // list, since we may have already processed the first entry.
13228 if (DefinitionRequired && !Pos.first->second) {
13229 Pos.first->second = true;
13230 } else {
13231 // Otherwise, we can early exit.
13232 return;
13233 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013234 } else {
13235 // The Microsoft ABI requires that we perform the destructor body
13236 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13237 // the deleting destructor is emitted with the vtable, not with the
13238 // destructor definition as in the Itanium ABI.
13239 // If it has a definition, we do the check at that point instead.
13240 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13241 Class->hasUserDeclaredDestructor() &&
13242 !Class->getDestructor()->isDefined() &&
13243 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013244 CXXDestructorDecl *DD = Class->getDestructor();
13245 ContextRAII SavedContext(*this, DD);
13246 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013247 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013248 }
13249
13250 // Local classes need to have their virtual members marked
13251 // immediately. For all other classes, we mark their virtual members
13252 // at the end of the translation unit.
13253 if (Class->isLocalClass())
13254 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013255 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013256 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013257}
13258
Douglas Gregor88d292c2010-05-13 16:44:06 +000013259bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013260 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013261 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013262 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013263
Douglas Gregor88d292c2010-05-13 16:44:06 +000013264 // Note: The VTableUses vector could grow as a result of marking
13265 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013266 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013267 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013268 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013269 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013270 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013271 if (!Class)
13272 continue;
13273
13274 SourceLocation Loc = VTableUses[I].second;
13275
Richard Smithd3b5c9082012-07-27 04:22:15 +000013276 bool DefineVTable = true;
13277
Douglas Gregor88d292c2010-05-13 16:44:06 +000013278 // If this class has a key function, but that key function is
13279 // defined in another translation unit, we don't need to emit the
13280 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013281 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013282 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013283 // The key function is in another translation unit.
13284 DefineVTable = false;
13285 TemplateSpecializationKind TSK =
13286 KeyFunction->getTemplateSpecializationKind();
13287 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13288 TSK != TSK_ImplicitInstantiation &&
13289 "Instantiations don't have key functions");
13290 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013291 } else if (!KeyFunction) {
13292 // If we have a class with no key function that is the subject
13293 // of an explicit instantiation declaration, suppress the
13294 // vtable; it will live with the explicit instantiation
13295 // definition.
13296 bool IsExplicitInstantiationDeclaration
13297 = Class->getTemplateSpecializationKind()
13298 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013299 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013300 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013301 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013302 if (TSK == TSK_ExplicitInstantiationDeclaration)
13303 IsExplicitInstantiationDeclaration = true;
13304 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13305 IsExplicitInstantiationDeclaration = false;
13306 break;
13307 }
13308 }
13309
13310 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013311 DefineVTable = false;
13312 }
13313
13314 // The exception specifications for all virtual members may be needed even
13315 // if we are not providing an authoritative form of the vtable in this TU.
13316 // We may choose to emit it available_externally anyway.
13317 if (!DefineVTable) {
13318 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13319 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013320 }
13321
13322 // Mark all of the virtual members of this class as referenced, so
13323 // that we can build a vtable. Then, tell the AST consumer that a
13324 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013325 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013326 MarkVirtualMembersReferenced(Loc, Class);
13327 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013328 if (VTablesUsed[Canonical])
13329 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013330
13331 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013332 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013333 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013334 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013335 if (!KeyFunction ||
13336 (KeyFunction->hasBody(KeyFunctionDef) &&
13337 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013338 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13339 TSK_ExplicitInstantiationDefinition
13340 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13341 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013342 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013343 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013344 VTableUses.clear();
13345
Douglas Gregor97509692011-04-22 22:25:37 +000013346 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013347}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013348
Richard Smithd3b5c9082012-07-27 04:22:15 +000013349void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13350 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013351 for (const auto *I : RD->methods())
13352 if (I->isVirtual() && !I->isPure())
13353 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013354}
13355
Rafael Espindola5b334082010-03-26 00:36:59 +000013356void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13357 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013358 // Mark all functions which will appear in RD's vtable as used.
13359 CXXFinalOverriderMap FinalOverriders;
13360 RD->getFinalOverriders(FinalOverriders);
13361 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13362 E = FinalOverriders.end();
13363 I != E; ++I) {
13364 for (OverridingMethods::const_iterator OI = I->second.begin(),
13365 OE = I->second.end();
13366 OI != OE; ++OI) {
13367 assert(OI->second.size() > 0 && "no final overrider");
13368 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013369
Richard Smith4ff9ff92012-07-07 06:59:51 +000013370 // C++ [basic.def.odr]p2:
13371 // [...] A virtual member function is used if it is not pure. [...]
13372 if (!Overrider->isPure())
13373 MarkFunctionReferenced(Loc, Overrider);
13374 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013375 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013376
13377 // Only classes that have virtual bases need a VTT.
13378 if (RD->getNumVBases() == 0)
13379 return;
13380
Aaron Ballman574705e2014-03-13 15:41:46 +000013381 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013382 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013383 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013384 if (Base->getNumVBases() == 0)
13385 continue;
13386 MarkVirtualMembersReferenced(Loc, Base);
13387 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013388}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013389
13390/// SetIvarInitializers - This routine builds initialization ASTs for the
13391/// Objective-C implementation whose ivars need be initialized.
13392void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013393 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013394 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013395 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013396 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013397 CollectIvarsToConstructOrDestruct(OID, ivars);
13398 if (ivars.empty())
13399 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013400 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013401 for (unsigned i = 0; i < ivars.size(); i++) {
13402 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013403 if (Field->isInvalidDecl())
13404 continue;
13405
Alexis Hunt1d792652011-01-08 20:30:50 +000013406 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013407 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13408 InitializationKind InitKind =
13409 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013410
13411 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13412 ExprResult MemberInit =
13413 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013414 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013415 // Note, MemberInit could actually come back empty if no initialization
13416 // is required (e.g., because it would call a trivial default constructor)
13417 if (!MemberInit.get() || MemberInit.isInvalid())
13418 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013419
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013420 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013421 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13422 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013423 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013424 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013425 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013426
13427 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013428 if (const RecordType *RecordTy =
13429 Context.getBaseElementType(Field->getType())
13430 ->getAs<RecordType>()) {
13431 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013432 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013433 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013434 CheckDestructorAccess(Field->getLocation(), Destructor,
13435 PDiag(diag::err_access_dtor_ivar)
13436 << Context.getBaseElementType(Field->getType()));
13437 }
13438 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013439 }
13440 ObjCImplementation->setIvarInitializers(Context,
13441 AllToInit.data(), AllToInit.size());
13442 }
13443}
Alexis Hunt6118d662011-05-04 05:57:24 +000013444
Alexis Hunt27a761d2011-05-04 23:29:54 +000013445static
13446void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13447 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13448 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13449 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13450 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013451 if (Ctor->isInvalidDecl())
13452 return;
13453
Richard Smith802c4b72012-08-23 06:16:52 +000013454 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13455
13456 // Target may not be determinable yet, for instance if this is a dependent
13457 // call in an uninstantiated template.
13458 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013459 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013460 (void)Target->hasBody(FNTarget);
13461 Target = const_cast<CXXConstructorDecl*>(
13462 cast_or_null<CXXConstructorDecl>(FNTarget));
13463 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013464
13465 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13466 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013467 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013468
David Blaikie82e95a32014-11-19 07:49:47 +000013469 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013470 return;
13471
13472 // We know that beyond here, we aren't chaining into a cycle.
13473 if (!Target || !Target->isDelegatingConstructor() ||
13474 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013475 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013476 Current.clear();
13477 // We've hit a cycle.
13478 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13479 Current.count(TCanonical)) {
13480 // If we haven't diagnosed this cycle yet, do so now.
13481 if (!Invalid.count(TCanonical)) {
13482 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013483 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013484 << Ctor;
13485
Richard Smith802c4b72012-08-23 06:16:52 +000013486 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013487 if (TCanonical != Canonical)
13488 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13489
13490 CXXConstructorDecl *C = Target;
13491 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013492 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013493 (void)C->getTargetConstructor()->hasBody(FNTarget);
13494 assert(FNTarget && "Ctor cycle through bodiless function");
13495
Richard Smith802c4b72012-08-23 06:16:52 +000013496 C = const_cast<CXXConstructorDecl*>(
13497 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013498 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13499 }
13500 }
13501
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013502 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013503 Current.clear();
13504 } else {
13505 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13506 }
13507}
13508
13509
Alexis Hunt6118d662011-05-04 05:57:24 +000013510void Sema::CheckDelegatingCtorCycles() {
13511 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13512
Douglas Gregorbae31202011-07-27 21:57:17 +000013513 for (DelegatingCtorDeclsType::iterator
13514 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013515 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013516 I != E; ++I)
13517 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013518
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013519 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13520 CE = Invalid.end();
13521 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013522 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013523}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013524
Douglas Gregor3024f072012-04-16 07:05:22 +000013525namespace {
13526 /// \brief AST visitor that finds references to the 'this' expression.
13527 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13528 Sema &S;
13529
13530 public:
13531 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13532
13533 bool VisitCXXThisExpr(CXXThisExpr *E) {
13534 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13535 << E->isImplicit();
13536 return false;
13537 }
13538 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013539}
Douglas Gregor3024f072012-04-16 07:05:22 +000013540
13541bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13542 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13543 if (!TSInfo)
13544 return false;
13545
13546 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013547 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013548 if (!ProtoTL)
13549 return false;
13550
13551 // C++11 [expr.prim.general]p3:
13552 // [The expression this] shall not appear before the optional
13553 // cv-qualifier-seq and it shall not appear within the declaration of a
13554 // static member function (although its type and value category are defined
13555 // within a static member function as they are within a non-static member
13556 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013557 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013558 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013559 FindCXXThisExpr Finder(*this);
13560
13561 // If the return type came after the cv-qualifier-seq, check it now.
13562 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013563 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013564 return true;
13565
13566 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013567 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13568 return true;
13569
13570 return checkThisInStaticMemberFunctionAttributes(Method);
13571}
13572
13573bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13574 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13575 if (!TSInfo)
13576 return false;
13577
13578 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013579 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013580 if (!ProtoTL)
13581 return false;
13582
David Blaikie6adc78e2013-02-18 22:06:02 +000013583 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013584 FindCXXThisExpr Finder(*this);
13585
Douglas Gregor3024f072012-04-16 07:05:22 +000013586 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013587 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013588 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013589 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013590 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013591 case EST_DynamicNone:
13592 case EST_MSAny:
13593 case EST_None:
13594 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013595
Douglas Gregor3024f072012-04-16 07:05:22 +000013596 case EST_ComputedNoexcept:
13597 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13598 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013599
Douglas Gregor3024f072012-04-16 07:05:22 +000013600 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013601 for (const auto &E : Proto->exceptions()) {
13602 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013603 return true;
13604 }
13605 break;
13606 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013607
13608 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013609}
13610
13611bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13612 FindCXXThisExpr Finder(*this);
13613
13614 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013615 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013616 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013617 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013618 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013619 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013620 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013621 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013622 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013623 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013624 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013625 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013626 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013627 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013628 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013629 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013630 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013631 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013632 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013633 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013634 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013635 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013636 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013637 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013638 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013639 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013640 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013641 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013642 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013643 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013644 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013645
13646 if (Arg && !Finder.TraverseStmt(Arg))
13647 return true;
13648
13649 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13650 if (!Finder.TraverseStmt(Args[I]))
13651 return true;
13652 }
13653 }
13654
13655 return false;
13656}
13657
Richard Smith2e321552014-11-12 02:00:47 +000013658void Sema::checkExceptionSpecification(
13659 bool IsTopLevel, ExceptionSpecificationType EST,
13660 ArrayRef<ParsedType> DynamicExceptions,
13661 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13662 SmallVectorImpl<QualType> &Exceptions,
13663 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013664 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013665 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013666 if (EST == EST_Dynamic) {
13667 Exceptions.reserve(DynamicExceptions.size());
13668 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13669 // FIXME: Preserve type source info.
13670 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13671
Richard Smith2e321552014-11-12 02:00:47 +000013672 if (IsTopLevel) {
13673 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13674 collectUnexpandedParameterPacks(ET, Unexpanded);
13675 if (!Unexpanded.empty()) {
13676 DiagnoseUnexpandedParameterPacks(
13677 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13678 Unexpanded);
13679 continue;
13680 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013681 }
13682
13683 // Check that the type is valid for an exception spec, and
13684 // drop it if not.
13685 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13686 Exceptions.push_back(ET);
13687 }
Richard Smith8acb4282014-07-31 21:57:55 +000013688 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013689 return;
13690 }
Richard Smith8acb4282014-07-31 21:57:55 +000013691
Douglas Gregor433e0532012-04-16 18:27:27 +000013692 if (EST == EST_ComputedNoexcept) {
13693 // If an error occurred, there's no expression here.
13694 if (NoexceptExpr) {
13695 assert((NoexceptExpr->isTypeDependent() ||
13696 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13697 Context.BoolTy) &&
13698 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013699 if (IsTopLevel && NoexceptExpr &&
13700 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013701 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013702 return;
13703 }
Richard Smith8acb4282014-07-31 21:57:55 +000013704
Douglas Gregor433e0532012-04-16 18:27:27 +000013705 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013706 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013707 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013708 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013709 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013710 }
13711 return;
13712 }
13713}
13714
Richard Smith0b3a4622014-11-13 20:01:57 +000013715void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13716 ExceptionSpecificationType EST,
13717 SourceRange SpecificationRange,
13718 ArrayRef<ParsedType> DynamicExceptions,
13719 ArrayRef<SourceRange> DynamicExceptionRanges,
13720 Expr *NoexceptExpr) {
13721 if (!MethodD)
13722 return;
13723
13724 // Dig out the method we're referring to.
13725 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13726 MethodD = FunTmpl->getTemplatedDecl();
13727
13728 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13729 if (!Method)
13730 return;
13731
13732 // Check the exception specification.
13733 llvm::SmallVector<QualType, 4> Exceptions;
13734 FunctionProtoType::ExceptionSpecInfo ESI;
13735 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13736 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13737 ESI);
13738
13739 // Update the exception specification on the function type.
13740 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13741
13742 if (Method->isStatic())
13743 checkThisInStaticMemberFunctionExceptionSpec(Method);
13744
13745 if (Method->isVirtual()) {
13746 // Check overrides, which we previously had to delay.
13747 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13748 OEnd = Method->end_overridden_methods();
13749 O != OEnd; ++O)
13750 CheckOverridingFunctionExceptionSpec(Method, *O);
13751 }
13752}
13753
John McCall5e77d762013-04-16 07:28:30 +000013754/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13755///
13756MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13757 SourceLocation DeclStart,
13758 Declarator &D, Expr *BitWidth,
13759 InClassInitStyle InitStyle,
13760 AccessSpecifier AS,
13761 AttributeList *MSPropertyAttr) {
13762 IdentifierInfo *II = D.getIdentifier();
13763 if (!II) {
13764 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013765 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013766 }
13767 SourceLocation Loc = D.getIdentifierLoc();
13768
13769 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13770 QualType T = TInfo->getType();
13771 if (getLangOpts().CPlusPlus) {
13772 CheckExtraCXXDefaultArguments(D);
13773
13774 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13775 UPPC_DataMemberType)) {
13776 D.setInvalidType();
13777 T = Context.IntTy;
13778 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13779 }
13780 }
13781
13782 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13783
13784 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13785 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13786 diag::err_invalid_thread)
13787 << DeclSpec::getSpecifierName(TSCS);
13788
13789 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013790 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013791 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13792 LookupName(Previous, S);
13793 switch (Previous.getResultKind()) {
13794 case LookupResult::Found:
13795 case LookupResult::FoundUnresolvedValue:
13796 PrevDecl = Previous.getAsSingle<NamedDecl>();
13797 break;
13798
13799 case LookupResult::FoundOverloaded:
13800 PrevDecl = Previous.getRepresentativeDecl();
13801 break;
13802
13803 case LookupResult::NotFound:
13804 case LookupResult::NotFoundInCurrentInstantiation:
13805 case LookupResult::Ambiguous:
13806 break;
13807 }
13808
13809 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13810 // Maybe we will complain about the shadowed template parameter.
13811 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13812 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013813 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013814 }
13815
13816 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013817 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013818
13819 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013820 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013821 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13822 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013823 ProcessDeclAttributes(TUScope, NewPD, D);
13824 NewPD->setAccess(AS);
13825
13826 if (NewPD->isInvalidDecl())
13827 Record->setInvalidDecl();
13828
13829 if (D.getDeclSpec().isModulePrivateSpecified())
13830 NewPD->setModulePrivate();
13831
13832 if (NewPD->isInvalidDecl() && PrevDecl) {
13833 // Don't introduce NewFD into scope; there's already something
13834 // with the same name in the same scope.
13835 } else if (II) {
13836 PushOnScopeChains(NewPD, S);
13837 } else
13838 Record->addDecl(NewPD);
13839
13840 return NewPD;
13841}