blob: 57ace2b802b728b9d6e58e94e3ceccf294e5f42c [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Reid Klecknerd60b82f2014-11-17 23:36:45 +000039#include "clang/Sema/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000272 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param,
349 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000350 if (!param)
351 return;
Mike Stump11289f42009-09-09 15:08:12 +0000352
John McCall48871652010-08-21 09:40:31 +0000353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000355 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000356 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000357 OpaqueValueExpr(EqualLoc,
358 Param->getType().getNonReferenceType(),
359 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000360}
361
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Alp Tokerc5350722014-02-26 22:27:52 +0000386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387 ++argIdx) {
388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000391 SourceRange SR;
392 if (Toks->size() > 1)
393 SR = SourceRange((*Toks)[1].getLocation(),
394 Toks->back().getLocation());
395 else
396 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000398 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000399 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000400 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000401 } else if (Param->getDefaultArg()) {
402 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
403 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000404 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000405 }
406 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000407 } else if (chunk.Kind != DeclaratorChunk::Paren) {
408 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000409 }
410 }
411}
412
David Majnemer502b0ed2013-06-25 23:09:30 +0000413static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
414 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
415 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
416 if (!PVD->hasDefaultArg())
417 return false;
418 if (!PVD->hasInheritedDefaultArg())
419 return true;
420 }
421 return false;
422}
423
Craig Toppere4794282012-09-21 04:33:26 +0000424/// MergeCXXFunctionDecl - Merge two declarations of the same C++
425/// function, once we already know that they have the same
426/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
427/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000428bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
429 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000430 bool Invalid = false;
431
Chris Lattner199abbc2008-04-08 05:04:30 +0000432 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000433 // For non-template functions, default arguments can be added in
434 // later declarations of a function in the same
435 // scope. Declarations in different scopes have completely
436 // distinct sets of default arguments. That is, declarations in
437 // inner scopes do not acquire default arguments from
438 // declarations in outer scopes, and vice versa. In a given
439 // function declaration, all parameters subsequent to a
440 // parameter with a default argument shall have default
441 // arguments supplied in this or previous declarations. A
442 // default argument shall not be redefined by a later
443 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000444 //
445 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000446 // Except for member functions of class templates, the default arguments
447 // in a member function definition that appears outside of the class
448 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000449 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000450 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
451 ParmVarDecl *OldParam = Old->getParamDecl(p);
452 ParmVarDecl *NewParam = New->getParamDecl(p);
453
James Molloye9430032012-03-13 08:55:35 +0000454 bool OldParamHasDfl = OldParam->hasDefaultArg();
455 bool NewParamHasDfl = NewParam->hasDefaultArg();
456
Richard Smith541b38b2013-09-20 01:15:31 +0000457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
Richard Smith5971e8c2014-08-27 22:31:34 +0000460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000464 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000465 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000466 // the same scope and this is not an out-of-line definition of
467 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000468 OldParamHasDfl = false;
Richard Smith5971e8c2014-08-27 22:31:34 +0000469 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
470 // If only one of these is a local function declaration, then they are
471 // declared in different scopes, even though isDeclInScope may think
472 // they're in the same scope. (If both are local, the scope check is
473 // sufficent, and if neither is local, then they are in the same scope.)
474 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000475
476 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000477
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000478 unsigned DiagDefaultParamID =
479 diag::err_param_default_argument_redefinition;
480
481 // MSVC accepts that default parameters be redefined for member functions
482 // of template class. The new default parameter's value is ignored.
483 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000484 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000485 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
486 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // Merge the old default argument into the new parameter.
488 NewParam->setHasInheritedDefaultArg();
489 if (OldParam->hasUninstantiatedDefaultArg())
490 NewParam->setUninstantiatedDefaultArg(
491 OldParam->getUninstantiatedDefaultArg());
492 else
493 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000494 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Invalid = false;
496 }
497 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000498
Francois Pichet8cb243a2011-04-10 04:58:30 +0000499 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
500 // hint here. Alternatively, we could walk the type-source information
501 // for NewParam to find the last source location in the type... but it
502 // isn't worth the effort right now. This is the kind of test case that
503 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000504 // int f(int);
505 // void g(int (*fp)(int) = f);
506 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000508 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000509
510 // Look for the function declaration where the default argument was
511 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000512 for (FunctionDecl *Older = Old->getPreviousDecl();
513 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000514 if (!Older->getParamDecl(p)->hasDefaultArg())
515 break;
516
517 OldParam = Older->getParamDecl(p);
518 }
519
520 Diag(OldParam->getLocation(), diag::note_previous_definition)
521 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000522 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000523 // Merge the old default argument into the new parameter.
524 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000525 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000526 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000527 if (OldParam->hasUninstantiatedDefaultArg())
528 NewParam->setUninstantiatedDefaultArg(
529 OldParam->getUninstantiatedDefaultArg());
530 else
John McCalle61b02b2010-05-04 01:53:42 +0000531 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000532 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000533 if (New->getDescribedFunctionTemplate()) {
534 // Paragraph 4, quoted above, only applies to non-template functions.
535 Diag(NewParam->getLocation(),
536 diag::err_param_default_argument_template_redecl)
537 << NewParam->getDefaultArgRange();
538 Diag(Old->getLocation(), diag::note_template_prev_declaration)
539 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000540 } else if (New->getTemplateSpecializationKind()
541 != TSK_ImplicitInstantiation &&
542 New->getTemplateSpecializationKind() != TSK_Undeclared) {
543 // C++ [temp.expr.spec]p21:
544 // Default function arguments shall not be specified in a declaration
545 // or a definition for one of the following explicit specializations:
546 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000547 // - the explicit specialization of a member function template;
548 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000549 // template where the class template specialization to which the
550 // member function specialization belongs is implicitly
551 // instantiated.
552 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
553 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
554 << New->getDeclName()
555 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000556 } else if (New->getDeclContext()->isDependentContext()) {
557 // C++ [dcl.fct.default]p6 (DR217):
558 // Default arguments for a member function of a class template shall
559 // be specified on the initial declaration of the member function
560 // within the class template.
561 //
562 // Reading the tea leaves a bit in DR217 and its reference to DR205
563 // leads me to the conclusion that one cannot add default function
564 // arguments for an out-of-line definition of a member function of a
565 // dependent type.
566 int WhichKind = 2;
567 if (CXXRecordDecl *Record
568 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
569 if (Record->getDescribedClassTemplate())
570 WhichKind = 0;
571 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
572 WhichKind = 1;
573 else
574 WhichKind = 2;
575 }
576
577 Diag(NewParam->getLocation(),
578 diag::err_param_default_argument_member_template_redecl)
579 << WhichKind
580 << NewParam->getDefaultArgRange();
581 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000582 }
583 }
584
Richard Smith58c3cc12012-11-28 03:45:24 +0000585 // DR1344: If a default argument is added outside a class definition and that
586 // default argument makes the function a special member function, the program
587 // is ill-formed. This can only happen for constructors.
588 if (isa<CXXConstructorDecl>(New) &&
589 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
590 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
591 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
592 if (NewSM != OldSM) {
593 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
594 assert(NewParam->hasDefaultArg());
595 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
596 << NewParam->getDefaultArgRange() << NewSM;
597 Diag(Old->getLocation(), diag::note_previous_declaration);
598 }
599 }
600
David Majnemeree4f4022014-03-30 06:44:54 +0000601 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000602 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000603 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000604 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000605 if (New->isConstexpr() != Old->isConstexpr()) {
606 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
607 << New << New->isConstexpr();
608 Diag(Old->getLocation(), diag::note_previous_declaration);
609 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000610 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
611 // C++11 [dcl.fcn.spec]p4:
612 // If the definition of a function appears in a translation unit before its
613 // first declaration as inline, the program is ill-formed.
614 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
615 Diag(Def->getLocation(), diag::note_previous_definition);
616 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000617 }
618
David Majnemer502b0ed2013-06-25 23:09:30 +0000619 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000620 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000621 // the only declaration of the function or function template in the
622 // translation unit.
623 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
624 functionDeclHasDefaultArgument(Old)) {
625 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
626 Diag(Old->getLocation(), diag::note_previous_declaration);
627 Invalid = true;
628 }
629
Douglas Gregorf40863c2010-02-12 07:32:17 +0000630 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000631 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000632
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000633 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000634}
635
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000636/// \brief Merge the exception specifications of two variable declarations.
637///
638/// This is called when there's a redeclaration of a VarDecl. The function
639/// checks if the redeclaration might have an exception specification and
640/// validates compatibility and merges the specs if necessary.
641void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
642 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000643 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000644 return;
645
646 assert(Context.hasSameType(New->getType(), Old->getType()) &&
647 "Should only be called if types are otherwise the same.");
648
649 QualType NewType = New->getType();
650 QualType OldType = Old->getType();
651
652 // We're only interested in pointers and references to functions, as well
653 // as pointers to member functions.
654 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
655 NewType = R->getPointeeType();
656 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
657 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
658 NewType = P->getPointeeType();
659 OldType = OldType->getAs<PointerType>()->getPointeeType();
660 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
661 NewType = M->getPointeeType();
662 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
663 }
664
665 if (!NewType->isFunctionProtoType())
666 return;
667
668 // There's lots of special cases for functions. For function pointers, system
669 // libraries are hopefully not as broken so that we don't need these
670 // workarounds.
671 if (CheckEquivalentExceptionSpec(
672 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
673 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
674 New->setInvalidDecl();
675 }
676}
677
Chris Lattner199abbc2008-04-08 05:04:30 +0000678/// CheckCXXDefaultArguments - Verify that the default arguments for a
679/// function declaration are well-formed according to C++
680/// [dcl.fct.default].
681void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
682 unsigned NumParams = FD->getNumParams();
683 unsigned p;
684
685 // Find first parameter with a default argument
686 for (p = 0; p < NumParams; ++p) {
687 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000688 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000689 break;
690 }
691
692 // C++ [dcl.fct.default]p4:
693 // In a given function declaration, all parameters
694 // subsequent to a parameter with a default argument shall
695 // have default arguments supplied in this or previous
696 // declarations. A default argument shall not be redefined
697 // by a later declaration (not even to the same value).
698 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000699 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000700 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000701 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000702 if (Param->isInvalidDecl())
703 /* We already complained about this parameter. */;
704 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000705 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000706 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000707 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000708 else
Mike Stump11289f42009-09-09 15:08:12 +0000709 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000711
Chris Lattner199abbc2008-04-08 05:04:30 +0000712 LastMissingDefaultArg = p;
713 }
714 }
715
716 if (LastMissingDefaultArg > 0) {
717 // Some default arguments were missing. Clear out all of the
718 // default arguments up to (and including) the last missing
719 // default argument, so that we leave the function parameters
720 // in a semantically valid state.
721 for (p = 0; p <= LastMissingDefaultArg; ++p) {
722 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000723 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000725 }
726 }
727 }
728}
Douglas Gregor556877c2008-04-13 21:30:24 +0000729
Richard Smitheb3c10c2011-10-01 02:31:28 +0000730// CheckConstexprParameterTypes - Check whether a function's parameter types
731// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000732// diagnostic and return false.
733static bool CheckConstexprParameterTypes(Sema &SemaRef,
734 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 unsigned ArgIndex = 0;
736 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000737 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
738 e = FT->param_type_end();
739 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000740 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
741 SourceLocation ParamLoc = PD->getLocation();
742 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000743 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000744 diag::err_constexpr_non_literal_param,
745 ArgIndex+1, PD->getSourceRange(),
746 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000747 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000748 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000749 return true;
750}
751
752/// \brief Get diagnostic %select index for tag kind for
753/// record diagnostic message.
754/// WARNING: Indexes apply to particular diagnostics only!
755///
756/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000757static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000758 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000759 case TTK_Struct: return 0;
760 case TTK_Interface: return 1;
761 case TTK_Class: return 2;
762 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000763 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000764}
765
766// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
767// the requirements of a constexpr function definition or a constexpr
768// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000769// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000770//
Richard Smith3607ffe2012-02-13 03:54:03 +0000771// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
772bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000773 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
774 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000775 // C++11 [dcl.constexpr]p4:
776 // The definition of a constexpr constructor shall satisfy the following
777 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000779 const CXXRecordDecl *RD = MD->getParent();
780 if (RD->getNumVBases()) {
781 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
782 << isa<CXXConstructorDecl>(NewFD)
783 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000784 for (const auto &I : RD->vbases())
785 Diag(I.getLocStart(),
786 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787 return false;
788 }
Richard Smith7971b692012-01-13 04:54:00 +0000789 }
790
791 if (!isa<CXXConstructorDecl>(NewFD)) {
792 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793 // The definition of a constexpr function shall satisfy the following
794 // constraints:
795 // - it shall not be virtual;
796 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
797 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000798 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000799
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 // If it's not obvious why this function is virtual, find an overridden
801 // function which uses the 'virtual' keyword.
802 const CXXMethodDecl *WrittenVirtual = Method;
803 while (!WrittenVirtual->isVirtualAsWritten())
804 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
805 if (WrittenVirtual != Method)
806 Diag(WrittenVirtual->getLocation(),
807 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000808 return false;
809 }
810
811 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000812 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000813 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000814 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000815 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817 }
818
Richard Smith7971b692012-01-13 04:54:00 +0000819 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000820 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000821 return false;
822
Richard Smitheb3c10c2011-10-01 02:31:28 +0000823 return true;
824}
825
826/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000827/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000828///
Richard Smithd9f663b2013-04-22 15:31:51 +0000829/// \return true if the body is OK (maybe only as an extension), false if we
830/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000831static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000832 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
833 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000834 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
835 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000836 for (const auto *DclIt : DS->decls()) {
837 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000838 case Decl::StaticAssert:
839 case Decl::Using:
840 case Decl::UsingShadow:
841 case Decl::UsingDirective:
842 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000843 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000844 // - static_assert-declarations
845 // - using-declarations,
846 // - using-directives,
847 continue;
848
849 case Decl::Typedef:
850 case Decl::TypeAlias: {
851 // - typedef declarations and alias-declarations that do not define
852 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000853 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000854 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
855 // Don't allow variably-modified types in constexpr functions.
856 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
857 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
858 << TL.getSourceRange() << TL.getType()
859 << isa<CXXConstructorDecl>(Dcl);
860 return false;
861 }
862 continue;
863 }
864
865 case Decl::Enum:
866 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000867 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000868 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000869 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000870 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000871 ? diag::warn_cxx11_compat_constexpr_type_definition
872 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000873 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000874 continue;
875
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 case Decl::EnumConstant:
877 case Decl::IndirectField:
878 case Decl::ParmVar:
879 // These can only appear with other declarations which are banned in
880 // C++11 and permitted in C++1y, so ignore them.
881 continue;
882
883 case Decl::Var: {
884 // C++1y [dcl.constexpr]p3 allows anything except:
885 // a definition of a variable of non-literal type or of static or
886 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000887 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000888 if (VD->isThisDeclarationADefinition()) {
889 if (VD->isStaticLocal()) {
890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_static)
892 << isa<CXXConstructorDecl>(Dcl)
893 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
894 return false;
895 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000896 if (!VD->getType()->isDependentType() &&
897 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000898 VD->getLocation(), VD->getType(),
899 diag::err_constexpr_local_var_non_literal_type,
900 isa<CXXConstructorDecl>(Dcl)))
901 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000902 if (!VD->getType()->isDependentType() &&
903 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000904 SemaRef.Diag(VD->getLocation(),
905 diag::err_constexpr_local_var_no_init)
906 << isa<CXXConstructorDecl>(Dcl);
907 return false;
908 }
909 }
910 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000911 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000912 ? diag::warn_cxx11_compat_constexpr_local_var
913 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000914 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000915 continue;
916 }
917
918 case Decl::NamespaceAlias:
919 case Decl::Function:
920 // These are disallowed in C++11 and permitted in C++1y. Allow them
921 // everywhere as an extension.
922 if (!Cxx1yLoc.isValid())
923 Cxx1yLoc = DS->getLocStart();
924 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000925
926 default:
927 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928 << isa<CXXConstructorDecl>(Dcl);
929 return false;
930 }
931 }
932
933 return true;
934}
935
936/// Check that the given field is initialized within a constexpr constructor.
937///
938/// \param Dcl The constexpr constructor being checked.
939/// \param Field The field being checked. This may be a member of an anonymous
940/// struct or union nested within the class being checked.
941/// \param Inits All declarations, including anonymous struct/union members and
942/// indirect members, for which any initialization was provided.
943/// \param Diagnosed Set to true if an error is produced.
944static void CheckConstexprCtorInitializer(Sema &SemaRef,
945 const FunctionDecl *Dcl,
946 FieldDecl *Field,
947 llvm::SmallSet<Decl*, 16> &Inits,
948 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000949 if (Field->isInvalidDecl())
950 return;
951
Douglas Gregor556e5862011-10-10 17:22:13 +0000952 if (Field->isUnnamedBitfield())
953 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000954
Richard Smithab44d5b2013-12-10 08:25:00 +0000955 // Anonymous unions with no variant members and empty anonymous structs do not
956 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
957 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000958 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000959 (Field->getType()->isUnionType()
960 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
961 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000962 return;
963
Richard Smitheb3c10c2011-10-01 02:31:28 +0000964 if (!Inits.count(Field)) {
965 if (!Diagnosed) {
966 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
967 Diagnosed = true;
968 }
969 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
970 } else if (Field->isAnonymousStructOrUnion()) {
971 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000972 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000973 // If an anonymous union contains an anonymous struct of which any member
974 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000975 if (!RD->isUnion() || Inits.count(I))
976 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000977 }
978}
979
Richard Smithd9f663b2013-04-22 15:31:51 +0000980/// Check the provided statement is allowed in a constexpr function
981/// definition.
982static bool
983CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000984 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000985 SourceLocation &Cxx1yLoc) {
986 // - its function-body shall be [...] a compound-statement that contains only
987 switch (S->getStmtClass()) {
988 case Stmt::NullStmtClass:
989 // - null statements,
990 return true;
991
992 case Stmt::DeclStmtClass:
993 // - static_assert-declarations
994 // - using-declarations,
995 // - using-directives,
996 // - typedef declarations and alias-declarations that do not define
997 // classes or enumerations,
998 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
999 return false;
1000 return true;
1001
1002 case Stmt::ReturnStmtClass:
1003 // - and exactly one return statement;
1004 if (isa<CXXConstructorDecl>(Dcl)) {
1005 // C++1y allows return statements in constexpr constructors.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009 }
1010
1011 ReturnStmts.push_back(S->getLocStart());
1012 return true;
1013
1014 case Stmt::CompoundStmtClass: {
1015 // C++1y allows compound-statements.
1016 if (!Cxx1yLoc.isValid())
1017 Cxx1yLoc = S->getLocStart();
1018
1019 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001020 for (auto *BodyIt : CompStmt->body()) {
1021 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001022 Cxx1yLoc))
1023 return false;
1024 }
1025 return true;
1026 }
1027
1028 case Stmt::AttributedStmtClass:
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 return true;
1032
1033 case Stmt::IfStmtClass: {
1034 // C++1y allows if-statements.
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037
1038 IfStmt *If = cast<IfStmt>(S);
1039 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 if (If->getElse() &&
1043 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1044 Cxx1yLoc))
1045 return false;
1046 return true;
1047 }
1048
1049 case Stmt::WhileStmtClass:
1050 case Stmt::DoStmtClass:
1051 case Stmt::ForStmtClass:
1052 case Stmt::CXXForRangeStmtClass:
1053 case Stmt::ContinueStmtClass:
1054 // C++1y allows all of these. We don't allow them as extensions in C++11,
1055 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001056 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001057 break;
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 for (Stmt::child_range Children = S->children(); Children; ++Children)
1061 if (*Children &&
1062 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063 Cxx1yLoc))
1064 return false;
1065 return true;
1066
1067 case Stmt::SwitchStmtClass:
1068 case Stmt::CaseStmtClass:
1069 case Stmt::DefaultStmtClass:
1070 case Stmt::BreakStmtClass:
1071 // C++1y allows switch-statements, and since they don't need variable
1072 // mutation, we can reasonably allow them in C++11 as an extension.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 for (Stmt::child_range Children = S->children(); Children; ++Children)
1076 if (*Children &&
1077 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1078 Cxx1yLoc))
1079 return false;
1080 return true;
1081
1082 default:
1083 if (!isa<Expr>(S))
1084 break;
1085
1086 // C++1y allows expression-statements.
1087 if (!Cxx1yLoc.isValid())
1088 Cxx1yLoc = S->getLocStart();
1089 return true;
1090 }
1091
1092 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1093 << isa<CXXConstructorDecl>(Dcl);
1094 return false;
1095}
1096
Richard Smitheb3c10c2011-10-01 02:31:28 +00001097/// Check the body for the given constexpr function declaration only contains
1098/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1099///
1100/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001101bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001102 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001103 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 // The definition of a constexpr function shall satisfy the following
1105 // constraints: [...]
1106 // - its function-body shall be = delete, = default, or a
1107 // compound-statement
1108 //
Richard Smith74388b42012-02-04 00:33:54 +00001109 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001110 // In the definition of a constexpr constructor, [...]
1111 // - its function-body shall not be a function-try-block;
1112 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1113 << isa<CXXConstructorDecl>(Dcl);
1114 return false;
1115 }
1116
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001117 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001118
1119 // - its function-body shall be [...] a compound-statement that contains only
1120 // [... list of cases ...]
1121 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1122 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001123 for (auto *BodyIt : CompBody->body()) {
1124 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001125 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001126 }
1127
Richard Smithd9f663b2013-04-22 15:31:51 +00001128 if (Cxx1yLoc.isValid())
1129 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001130 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001131 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1132 : diag::ext_constexpr_body_invalid_stmt)
1133 << isa<CXXConstructorDecl>(Dcl);
1134
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 if (const CXXConstructorDecl *Constructor
1136 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1137 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001138 // DR1359:
1139 // - every non-variant non-static data member and base class sub-object
1140 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001141 // DR1460:
1142 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001143 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001144 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001145 if (Constructor->getNumCtorInitializers() == 0 &&
1146 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1148 return false;
1149 }
Richard Smithf368fb42011-10-10 16:38:04 +00001150 } else if (!Constructor->isDependentContext() &&
1151 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001152 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1153
1154 // Skip detailed checking if we have enough initializers, and we would
1155 // allow at most one initializer per member.
1156 bool AnyAnonStructUnionMembers = false;
1157 unsigned Fields = 0;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001160 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001161 AnyAnonStructUnionMembers = true;
1162 break;
1163 }
1164 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001165 // DR1460:
1166 // - if the class is a union-like class, but is not a union, for each of
1167 // its anonymous union members having variant members, exactly one of
1168 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001169 if (AnyAnonStructUnionMembers ||
1170 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1171 // Check initialization of non-static data members. Base classes are
1172 // always initialized so do not need to be checked. Dependent bases
1173 // might not have initializers in the member initializer list.
1174 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001175 for (const auto *I: Constructor->inits()) {
1176 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001178 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001179 Inits.insert(ID->chain_begin(), ID->chain_end());
1180 }
1181
1182 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001183 for (auto *I : RD->fields())
1184 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001185 if (Diagnosed)
1186 return false;
1187 }
1188 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001189 } else {
1190 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001191 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001192 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001193 // otherwise if there's no return statement, the function cannot
1194 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001195 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001196 (Dcl->getReturnType()->isVoidType() ||
1197 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001198 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001199 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1200 : diag::err_constexpr_body_no_return);
1201 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001202 }
1203 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001204 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001205 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001206 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1207 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001208 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1209 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001210 }
1211 }
1212
Richard Smith74388b42012-02-04 00:33:54 +00001213 // C++11 [dcl.constexpr]p5:
1214 // if no function argument values exist such that the function invocation
1215 // substitution would produce a constant expression, the program is
1216 // ill-formed; no diagnostic required.
1217 // C++11 [dcl.constexpr]p3:
1218 // - every constructor call and implicit conversion used in initializing the
1219 // return value shall be one of those allowed in a constant expression.
1220 // C++11 [dcl.constexpr]p4:
1221 // - every constructor involved in initializing non-static data members and
1222 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001223 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001224 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001225 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001226 << isa<CXXConstructorDecl>(Dcl);
1227 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1228 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001229 // Don't return false here: we allow this for compatibility in
1230 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001231 }
1232
Richard Smitheb3c10c2011-10-01 02:31:28 +00001233 return true;
1234}
1235
Douglas Gregor61956c42008-10-31 09:07:45 +00001236/// isCurrentClassName - Determine whether the identifier II is the
1237/// name of the class type currently being defined. In the case of
1238/// nested classes, this will only return true if II is the name of
1239/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001240bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1241 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001242 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001243
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001244 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001245 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001246 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001247 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1248 } else
1249 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1250
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001251 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001252 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001253 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001254}
1255
Richard Smithfb8b7b92013-10-15 00:00:26 +00001256/// \brief Determine whether the identifier II is a typo for the name of
1257/// the class type currently being defined. If so, update it to the identifier
1258/// that should have been used.
1259bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1260 assert(getLangOpts().CPlusPlus && "No class names in C!");
1261
1262 if (!getLangOpts().SpellChecking)
1263 return false;
1264
1265 CXXRecordDecl *CurDecl;
1266 if (SS && SS->isSet() && !SS->isInvalid()) {
1267 DeclContext *DC = computeDeclContext(*SS, true);
1268 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1269 } else
1270 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1271
1272 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1273 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1274 < II->getLength()) {
1275 II = CurDecl->getIdentifier();
1276 return true;
1277 }
1278
1279 return false;
1280}
1281
Douglas Gregordc974572012-11-10 07:24:09 +00001282/// \brief Determine whether the given class is a base class of the given
1283/// class, including looking at dependent bases.
1284static bool findCircularInheritance(const CXXRecordDecl *Class,
1285 const CXXRecordDecl *Current) {
1286 SmallVector<const CXXRecordDecl*, 8> Queue;
1287
1288 Class = Class->getCanonicalDecl();
1289 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001290 for (const auto &I : Current->bases()) {
1291 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001292 if (!Base)
1293 continue;
1294
1295 Base = Base->getDefinition();
1296 if (!Base)
1297 continue;
1298
1299 if (Base->getCanonicalDecl() == Class)
1300 return true;
1301
1302 Queue.push_back(Base);
1303 }
1304
1305 if (Queue.empty())
1306 return false;
1307
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001308 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001309 }
1310
1311 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001312}
1313
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001314/// \brief Perform propagation of DLL attributes from a derived class to a
1315/// templated base class for MS compatibility.
1316static void propagateDLLAttrToBaseClassTemplate(
1317 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1318 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1319 if (getDLLAttr(
1320 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1321 // If the base class template has a DLL attribute, don't try to change it.
1322 return;
1323 }
1324
1325 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1326 // If the base class is not already specialized, we can do the propagation.
1327 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1328 NewAttr->setInherited(true);
1329 BaseTemplateSpec->addAttr(NewAttr);
1330 return;
1331 }
1332
1333 bool DifferentAttribute = false;
1334 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1335 if (!SpecializationAttr->isInherited()) {
1336 // The template has previously been specialized or instantiated with an
1337 // explicit attribute. We should not try to change it.
1338 return;
1339 }
1340 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1341 // The specialization already has the right attribute.
1342 return;
1343 }
1344 DifferentAttribute = true;
1345 }
1346
1347 // The template was previously instantiated or explicitly specialized without
1348 // a dll attribute, or the template was previously instantiated with a
1349 // different inherited attribute. It's too late for us to change the
1350 // attribute, so warn that this is unsupported.
1351 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1352 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1353 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1354 if (BaseTemplateSpec->isExplicitSpecialization()) {
1355 S.Diag(BaseTemplateSpec->getLocation(),
1356 diag::note_template_class_explicit_specialization_was_here)
1357 << BaseTemplateSpec;
1358 } else {
1359 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1360 diag::note_template_class_instantiation_was_here)
1361 << BaseTemplateSpec;
1362 }
1363}
1364
Mike Stump11289f42009-09-09 15:08:12 +00001365/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001366///
1367/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1368/// and returns NULL otherwise.
1369CXXBaseSpecifier *
1370Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1371 SourceRange SpecifierRange,
1372 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001373 TypeSourceInfo *TInfo,
1374 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001375 QualType BaseType = TInfo->getType();
1376
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 // C++ [class.union]p1:
1378 // A union shall not have base classes.
1379 if (Class->isUnion()) {
1380 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1381 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001382 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001383 }
1384
Douglas Gregor752a5952011-01-03 22:36:02 +00001385 if (EllipsisLoc.isValid() &&
1386 !TInfo->getType()->containsUnexpandedParameterPack()) {
1387 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1388 << TInfo->getTypeLoc().getSourceRange();
1389 EllipsisLoc = SourceLocation();
1390 }
Douglas Gregor62004702012-11-10 01:18:17 +00001391
1392 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1393
1394 if (BaseType->isDependentType()) {
1395 // Make sure that we don't have circular inheritance among our dependent
1396 // bases. For non-dependent bases, the check for completeness below handles
1397 // this.
1398 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1399 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1400 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001401 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001402 Diag(BaseLoc, diag::err_circular_inheritance)
1403 << BaseType << Context.getTypeDeclType(Class);
1404
1405 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1406 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1407 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001408
1409 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001410 }
1411 }
1412
Mike Stump11289f42009-09-09 15:08:12 +00001413 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001414 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001415 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001416 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001417
1418 // Base specifiers must be record types.
1419 if (!BaseType->isRecordType()) {
1420 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001421 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001422 }
1423
1424 // C++ [class.union]p1:
1425 // A union shall not be used as a base class.
1426 if (BaseType->isUnionType()) {
1427 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001428 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001429 }
1430
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001431 // For the MS ABI, propagate DLL attributes to base class templates.
1432 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1433 if (Attr *ClassAttr = getDLLAttr(Class)) {
1434 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1435 BaseType->getAsCXXRecordDecl())) {
1436 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1437 BaseTemplate, BaseLoc);
1438 }
1439 }
1440 }
1441
Douglas Gregor463421d2009-03-03 04:44:36 +00001442 // C++ [class.derived]p2:
1443 // The class-name in a base-specifier shall not be an incompletely
1444 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001445 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001446 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001447 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001448 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001449 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001450
Eli Friedmanc96d4962009-08-15 21:55:26 +00001451 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001452 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001453 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001454 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001455 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001456 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001457 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001458
David Majnemer9b1754d2013-11-02 12:00:36 +00001459 // A class which contains a flexible array member is not suitable for use as a
1460 // base class:
1461 // - If the layout determines that a base comes before another base,
1462 // the flexible array member would index into the subsequent base.
1463 // - If the layout determines that base comes before the derived class,
1464 // the flexible array member would index into the derived class.
1465 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1466 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1467 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001468 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001469 }
1470
Anders Carlsson65c76d32011-03-25 14:55:14 +00001471 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001472 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001473 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001474 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001475 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001476 << CXXBaseDecl->getDeclName()
1477 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001478 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1479 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001480 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001481 }
1482
John McCall3696dcb2010-08-17 07:23:57 +00001483 if (BaseDecl->isInvalidDecl())
1484 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001485
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001486 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001487 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001488 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001489 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001490}
1491
Douglas Gregor556877c2008-04-13 21:30:24 +00001492/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1493/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001494/// example:
1495/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001496/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001497BaseResult
John McCall48871652010-08-21 09:40:31 +00001498Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001499 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001500 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001501 ParsedType basetype, SourceLocation BaseLoc,
1502 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001503 if (!classdecl)
1504 return true;
1505
Douglas Gregorc40290e2009-03-09 23:48:35 +00001506 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001507 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001508 if (!Class)
1509 return true;
1510
David Majnemer5ef4fe72014-06-13 06:43:46 +00001511 // We haven't yet attached the base specifiers.
1512 Class->setIsParsingBaseSpecifiers();
1513
Richard Smith4c96e992013-02-19 23:47:15 +00001514 // We do not support any C++11 attributes on base-specifiers yet.
1515 // Diagnose any attributes we see.
1516 if (!Attributes.empty()) {
1517 for (AttributeList *Attr = Attributes.getList(); Attr;
1518 Attr = Attr->getNext()) {
1519 if (Attr->isInvalid() ||
1520 Attr->getKind() == AttributeList::IgnoredAttribute)
1521 continue;
1522 Diag(Attr->getLoc(),
1523 Attr->getKind() == AttributeList::UnknownAttribute
1524 ? diag::warn_unknown_attribute_ignored
1525 : diag::err_base_specifier_attribute)
1526 << Attr->getName();
1527 }
1528 }
1529
Craig Topperc3ec1492014-05-26 06:22:03 +00001530 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001531 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001532
Douglas Gregor752a5952011-01-03 22:36:02 +00001533 if (EllipsisLoc.isInvalid() &&
1534 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001535 UPPC_BaseType))
1536 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001537
Douglas Gregor463421d2009-03-03 04:44:36 +00001538 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001539 Virtual, Access, TInfo,
1540 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001541 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001542 else
1543 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001544
Douglas Gregor463421d2009-03-03 04:44:36 +00001545 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001546}
Douglas Gregor556877c2008-04-13 21:30:24 +00001547
Douglas Gregor463421d2009-03-03 04:44:36 +00001548/// \brief Performs the actual work of attaching the given base class
1549/// specifiers to a C++ class.
1550bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1551 unsigned NumBases) {
1552 if (NumBases == 0)
1553 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001554
1555 // Used to keep track of which base types we have already seen, so
1556 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001557 // that the key is always the unqualified canonical type of the base
1558 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001559 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1560
1561 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001562 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001563 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001564 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001565 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001566 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001567 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001568
1569 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1570 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001571 // C++ [class.mi]p3:
1572 // A class shall not be specified as a direct base class of a
1573 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001574 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001575 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001576 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001577 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001578
1579 // Delete the duplicate base class specifier; we're going to
1580 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001581 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001582
1583 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001584 } else {
1585 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001586 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001587 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001588 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1589 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1590 if (Class->isInterface() &&
1591 (!RD->isInterface() ||
1592 KnownBase->getAccessSpecifier() != AS_public)) {
1593 // The Microsoft extension __interface does not permit bases that
1594 // are not themselves public interfaces.
1595 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1596 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1597 << RD->getSourceRange();
1598 Invalid = true;
1599 }
1600 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001601 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001602 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001603 }
1604 }
1605
1606 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001607 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001608
1609 // Delete the remaining (good) base class specifiers, since their
1610 // data has been copied into the CXXRecordDecl.
1611 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001612 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001613
1614 return Invalid;
1615}
1616
1617/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1618/// class, after checking whether there are any duplicate base
1619/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001620void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001621 unsigned NumBases) {
1622 if (!ClassDecl || !Bases || !NumBases)
1623 return;
1624
1625 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001626 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001627}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001628
Douglas Gregor36d1b142009-10-06 17:59:45 +00001629/// \brief Determine whether the type \p Derived is a C++ class that is
1630/// derived from the type \p Base.
1631bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001632 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001633 return false;
John McCalle78aac42010-03-10 03:28:59 +00001634
Douglas Gregor45bb4832013-03-26 23:36:30 +00001635 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001636 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001637 return false;
1638
Douglas Gregor45bb4832013-03-26 23:36:30 +00001639 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001640 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001641 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001642
1643 // If either the base or the derived type is invalid, don't try to
1644 // check whether one is derived from the other.
1645 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1646 return false;
1647
John McCall67da35c2010-02-04 22:26:26 +00001648 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1649 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001650}
1651
1652/// \brief Determine whether the type \p Derived is a C++ class that is
1653/// derived from the type \p Base.
1654bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001655 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001656 return false;
1657
Douglas Gregor45bb4832013-03-26 23:36:30 +00001658 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001659 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001660 return false;
1661
Douglas Gregor45bb4832013-03-26 23:36:30 +00001662 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001663 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001664 return false;
1665
Douglas Gregor36d1b142009-10-06 17:59:45 +00001666 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1667}
1668
Anders Carlssona70cff62010-04-24 19:06:50 +00001669void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001670 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001671 assert(BasePathArray.empty() && "Base path array must be empty!");
1672 assert(Paths.isRecordingPaths() && "Must record paths!");
1673
1674 const CXXBasePath &Path = Paths.front();
1675
1676 // We first go backward and check if we have a virtual base.
1677 // FIXME: It would be better if CXXBasePath had the base specifier for
1678 // the nearest virtual base.
1679 unsigned Start = 0;
1680 for (unsigned I = Path.size(); I != 0; --I) {
1681 if (Path[I - 1].Base->isVirtual()) {
1682 Start = I - 1;
1683 break;
1684 }
1685 }
1686
1687 // Now add all bases.
1688 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001690}
1691
Douglas Gregor88d292c2010-05-13 16:44:06 +00001692/// \brief Determine whether the given base path includes a virtual
1693/// base class.
John McCallcf142162010-08-07 06:22:56 +00001694bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1695 for (CXXCastPath::const_iterator B = BasePath.begin(),
1696 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001697 B != BEnd; ++B)
1698 if ((*B)->isVirtual())
1699 return true;
1700
1701 return false;
1702}
1703
Douglas Gregor36d1b142009-10-06 17:59:45 +00001704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1705/// conversion (where Derived and Base are class types) is
1706/// well-formed, meaning that the conversion is unambiguous (and
1707/// that all of the base classes are accessible). Returns true
1708/// and emits a diagnostic if the code is ill-formed, returns false
1709/// otherwise. Loc is the location where this routine should point to
1710/// if there is an error, and Range is the source range to highlight
1711/// if there is an error.
1712bool
1713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001714 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001715 unsigned AmbigiousBaseConvID,
1716 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001717 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001718 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001719 // First, determine whether the path from Derived to Base is
1720 // ambiguous. This is slightly more expensive than checking whether
1721 // the Derived to Base conversion exists, because here we need to
1722 // explore multiple paths to determine if there is an ambiguity.
1723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1724 /*DetectVirtual=*/false);
1725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1726 assert(DerivationOkay &&
1727 "Can only be used with a derived-to-base conversion");
1728 (void)DerivationOkay;
1729
1730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001731 if (InaccessibleBaseID) {
1732 // Check that the base class can be accessed.
1733 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1734 InaccessibleBaseID)) {
1735 case AR_inaccessible:
1736 return true;
1737 case AR_accessible:
1738 case AR_dependent:
1739 case AR_delayed:
1740 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001741 }
John McCall5b0829a2010-02-10 09:31:12 +00001742 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001743
1744 // Build a base path if necessary.
1745 if (BasePath)
1746 BuildBasePathArray(Paths, *BasePath);
1747 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001748 }
1749
David Majnemer626032f2013-06-22 06:43:58 +00001750 if (AmbigiousBaseConvID) {
1751 // We know that the derived-to-base conversion is ambiguous, and
1752 // we're going to produce a diagnostic. Perform the derived-to-base
1753 // search just one more time to compute all of the possible paths so
1754 // that we can print them out. This is more expensive than any of
1755 // the previous derived-to-base checks we've done, but at this point
1756 // performance isn't as much of an issue.
1757 Paths.clear();
1758 Paths.setRecordingPaths(true);
1759 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1760 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1761 (void)StillOkay;
1762
1763 // Build up a textual representation of the ambiguous paths, e.g.,
1764 // D -> B -> A, that will be used to illustrate the ambiguous
1765 // conversions in the diagnostic. We only print one of the paths
1766 // to each base class subobject.
1767 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1768
1769 Diag(Loc, AmbigiousBaseConvID)
1770 << Derived << Base << PathDisplayStr << Range << Name;
1771 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001772 return true;
1773}
1774
1775bool
1776Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001777 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001778 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001779 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001780 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001781 IgnoreAccess ? 0
1782 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001783 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001784 Loc, Range, DeclarationName(),
1785 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001786}
1787
1788
1789/// @brief Builds a string representing ambiguous paths from a
1790/// specific derived class to different subobjects of the same base
1791/// class.
1792///
1793/// This function builds a string that can be used in error messages
1794/// to show the different paths that one can take through the
1795/// inheritance hierarchy to go from the derived class to different
1796/// subobjects of a base class. The result looks something like this:
1797/// @code
1798/// struct D -> struct B -> struct A
1799/// struct D -> struct C -> struct A
1800/// @endcode
1801std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1802 std::string PathDisplayStr;
1803 std::set<unsigned> DisplayedPaths;
1804 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1805 Path != Paths.end(); ++Path) {
1806 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1807 // We haven't displayed a path to this particular base
1808 // class subobject yet.
1809 PathDisplayStr += "\n ";
1810 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1811 for (CXXBasePath::const_iterator Element = Path->begin();
1812 Element != Path->end(); ++Element)
1813 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1814 }
1815 }
1816
1817 return PathDisplayStr;
1818}
1819
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001820//===----------------------------------------------------------------------===//
1821// C++ class member Handling
1822//===----------------------------------------------------------------------===//
1823
Abramo Bagnarad7340582010-06-05 05:09:32 +00001824/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001825bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1826 SourceLocation ASLoc,
1827 SourceLocation ColonLoc,
1828 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001829 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001830 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001831 ASLoc, ColonLoc);
1832 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001833 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001834}
1835
Richard Smith18f07db2012-08-06 03:25:17 +00001836/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001837void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001838 if (D->isInvalidDecl())
1839 return;
1840
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001841 // We only care about "override" and "final" declarations.
1842 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1843 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001844
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001845 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001846
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001847 // We can't check dependent instance methods.
1848 if (MD && MD->isInstance() &&
1849 (MD->getParent()->hasAnyDependentBases() ||
1850 MD->getType()->isDependentType()))
1851 return;
1852
1853 if (MD && !MD->isVirtual()) {
1854 // If we have a non-virtual method, check if if hides a virtual method.
1855 // (In that case, it's most likely the method has the wrong type.)
1856 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1857 FindHiddenVirtualMethods(MD, OverloadedMethods);
1858
1859 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001860 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1861 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001862 diag::override_keyword_hides_virtual_member_function)
1863 << "override" << (OverloadedMethods.size() > 1);
1864 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001865 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001866 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001867 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1868 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001869 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001870 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1871 MD->setInvalidDecl();
1872 return;
1873 }
1874 // Fall through into the general case diagnostic.
1875 // FIXME: We might want to attempt typo correction here.
1876 }
1877
1878 if (!MD || !MD->isVirtual()) {
1879 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1880 Diag(OA->getLocation(),
1881 diag::override_keyword_only_allowed_on_virtual_member_functions)
1882 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1883 D->dropAttr<OverrideAttr>();
1884 }
1885 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1886 Diag(FA->getLocation(),
1887 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001888 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1889 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001890 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001891 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001892 return;
1893 }
Richard Smith18f07db2012-08-06 03:25:17 +00001894
Richard Smith18f07db2012-08-06 03:25:17 +00001895 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001896 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001897 // does not override a member function of a base class, the program is
1898 // ill-formed.
1899 bool HasOverriddenMethods =
1900 MD->begin_overridden_methods() != MD->end_overridden_methods();
1901 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1902 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1903 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001904}
1905
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001906void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1907 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1908 return;
1909 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1910 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1911 isa<CXXDestructorDecl>(MD))
1912 return;
1913
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001914 SourceLocation Loc = MD->getLocation();
1915 SourceLocation SpellingLoc = Loc;
1916 if (getSourceManager().isMacroArgExpansion(Loc))
1917 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1918 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1919 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001920 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001921
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001922 if (MD->size_overridden_methods() > 0) {
1923 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1924 << MD->getDeclName();
1925 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1926 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1927 }
1928}
1929
Richard Smith18f07db2012-08-06 03:25:17 +00001930/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001931/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001932/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001933bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1934 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001935 FinalAttr *FA = Old->getAttr<FinalAttr>();
1936 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001937 return false;
1938
1939 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001940 << New->getDeclName()
1941 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001942 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1943 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001944}
1945
Daniel Jasper0baec5492012-06-06 08:32:04 +00001946static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001947 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1948 // FIXME: Destruction of ObjC lifetime types has side-effects.
1949 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1950 return !RD->isCompleteDefinition() ||
1951 !RD->hasTrivialDefaultConstructor() ||
1952 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001953 return false;
1954}
1955
John McCall5e77d762013-04-16 07:28:30 +00001956static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001957 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001958 if (it->isDeclspecPropertyAttribute())
1959 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001960 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001961}
1962
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001963/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1964/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001965/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001966/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1967/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001968NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001969Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001970 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001971 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001972 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001973 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001974 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1975 DeclarationName Name = NameInfo.getName();
1976 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001977
1978 // For anonymous bitfields, the location should point to the type.
1979 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001980 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001981
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001982 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001983
John McCallb1cd7da2010-06-04 08:34:12 +00001984 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001985 assert(!DS.isFriendSpecified());
1986
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001987 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001988
John McCalldb632ac2012-09-25 07:32:39 +00001989 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1990 // The Microsoft extension __interface only permits public member functions
1991 // and prohibits constructors, destructors, operators, non-public member
1992 // functions, static methods and data members.
1993 unsigned InvalidDecl;
1994 bool ShowDeclName = true;
1995 if (!isFunc)
1996 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1997 else if (AS != AS_public)
1998 InvalidDecl = 2;
1999 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2000 InvalidDecl = 3;
2001 else switch (Name.getNameKind()) {
2002 case DeclarationName::CXXConstructorName:
2003 InvalidDecl = 4;
2004 ShowDeclName = false;
2005 break;
2006
2007 case DeclarationName::CXXDestructorName:
2008 InvalidDecl = 5;
2009 ShowDeclName = false;
2010 break;
2011
2012 case DeclarationName::CXXOperatorName:
2013 case DeclarationName::CXXConversionFunctionName:
2014 InvalidDecl = 6;
2015 break;
2016
2017 default:
2018 InvalidDecl = 0;
2019 break;
2020 }
2021
2022 if (InvalidDecl) {
2023 if (ShowDeclName)
2024 Diag(Loc, diag::err_invalid_member_in_interface)
2025 << (InvalidDecl-1) << Name;
2026 else
2027 Diag(Loc, diag::err_invalid_member_in_interface)
2028 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002029 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002030 }
2031 }
2032
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002033 // C++ 9.2p6: A member shall not be declared to have automatic storage
2034 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002035 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2036 // data members and cannot be applied to names declared const or static,
2037 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002038 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002039 case DeclSpec::SCS_unspecified:
2040 case DeclSpec::SCS_typedef:
2041 case DeclSpec::SCS_static:
2042 break;
2043 case DeclSpec::SCS_mutable:
2044 if (isFunc) {
2045 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Richard Smithb4a9e862013-04-12 22:46:28 +00002047 // FIXME: It would be nicer if the keyword was ignored only for this
2048 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002049 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002050 }
2051 break;
2052 default:
2053 Diag(DS.getStorageClassSpecLoc(),
2054 diag::err_storageclass_invalid_for_member);
2055 D.getMutableDeclSpec().ClearStorageClassSpecs();
2056 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002057 }
2058
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002059 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2060 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002061 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002062
David Blaikie35506f82013-01-30 01:22:18 +00002063 if (DS.isConstexprSpecified() && isInstField) {
2064 SemaDiagnosticBuilder B =
2065 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2066 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2067 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002068 B << 0 << 0;
2069 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2070 B << FixItHint::CreateRemoval(ConstexprLoc);
2071 else {
2072 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2073 D.getMutableDeclSpec().ClearConstexprSpec();
2074 const char *PrevSpec;
2075 unsigned DiagID;
2076 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2077 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2078 (void)Failed;
2079 assert(!Failed && "Making a constexpr member const shouldn't fail");
2080 }
David Blaikie35506f82013-01-30 01:22:18 +00002081 } else {
2082 B << 1;
2083 const char *PrevSpec;
2084 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002085 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002086 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2087 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002088 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002089 "This is the only DeclSpec that should fail to be applied");
2090 B << 1;
2091 } else {
2092 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2093 isInstField = false;
2094 }
2095 }
2096 }
2097
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002098 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002099 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002100 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002101
2102 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002103 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002104 Diag(Loc, diag::err_bad_variable_name)
2105 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002106 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002107 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002108
Benjamin Kramer365082d2012-05-19 16:34:46 +00002109 IdentifierInfo *II = Name.getAsIdentifierInfo();
2110
Douglas Gregor7c26c042011-09-21 14:40:46 +00002111 // Member field could not be with "template" keyword.
2112 // So TemplateParameterLists should be empty in this case.
2113 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002114 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002115 if (TemplateParams->size()) {
2116 // There is no such thing as a member field template.
2117 Diag(D.getIdentifierLoc(), diag::err_template_member)
2118 << II
2119 << SourceRange(TemplateParams->getTemplateLoc(),
2120 TemplateParams->getRAngleLoc());
2121 } else {
2122 // There is an extraneous 'template<>' for this member.
2123 Diag(TemplateParams->getTemplateLoc(),
2124 diag::err_template_member_noparams)
2125 << II
2126 << SourceRange(TemplateParams->getTemplateLoc(),
2127 TemplateParams->getRAngleLoc());
2128 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002129 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002130 }
2131
Douglas Gregora007d362010-10-13 22:19:53 +00002132 if (SS.isSet() && !SS.isInvalid()) {
2133 // The user provided a superfluous scope specifier inside a class
2134 // definition:
2135 //
2136 // class X {
2137 // int X::member;
2138 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002139 if (DeclContext *DC = computeDeclContext(SS, false))
2140 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002141 else
2142 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2143 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002144
Douglas Gregora007d362010-10-13 22:19:53 +00002145 SS.clear();
2146 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002147
John McCall5e77d762013-04-16 07:28:30 +00002148 AttributeList *MSPropertyAttr =
2149 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002150 if (MSPropertyAttr) {
2151 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2152 BitWidth, InitStyle, AS, MSPropertyAttr);
2153 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002154 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002155 isInstField = false;
2156 } else {
2157 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2158 BitWidth, InitStyle, AS);
2159 assert(Member && "HandleField never returns null");
2160 }
2161 } else {
Nico Webera089c7c2015-01-16 21:09:43 +00002162 assert(InitStyle == ICIS_NoInit ||
2163 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002164
2165 Member = HandleDeclarator(S, D, TemplateParameterLists);
2166 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002167 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002168
2169 // Non-instance-fields can't have a bitfield.
2170 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002171 if (Member->isInvalidDecl()) {
2172 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002173 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002174 // C++ 9.6p3: A bit-field shall not be a static member.
2175 // "static member 'A' cannot be a bit-field"
2176 Diag(Loc, diag::err_static_not_bitfield)
2177 << Name << BitWidth->getSourceRange();
2178 } else if (isa<TypedefDecl>(Member)) {
2179 // "typedef member 'x' cannot be a bit-field"
2180 Diag(Loc, diag::err_typedef_not_bitfield)
2181 << Name << BitWidth->getSourceRange();
2182 } else {
2183 // A function typedef ("typedef int f(); f a;").
2184 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2185 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002186 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002187 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
Craig Topperc3ec1492014-05-26 06:22:03 +00002190 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002191 Member->setInvalidDecl();
2192 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002193
2194 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002195
Larisse Voufo39a1e502013-08-06 01:03:05 +00002196 // If we have declared a member function template or static data member
2197 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002198 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2199 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002200 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2201 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002202 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002203
Richard Smith18f07db2012-08-06 03:25:17 +00002204 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002205 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002206 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002207 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2208 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002209
Douglas Gregorf2f08062011-03-08 17:10:18 +00002210 if (VS.getLastLocation().isValid()) {
2211 // Update the end location of a method that has a virt-specifiers.
2212 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2213 MD->setRangeEnd(VS.getLastLocation());
2214 }
Richard Smith18f07db2012-08-06 03:25:17 +00002215
Anders Carlssonc87f8612011-01-20 06:29:02 +00002216 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002217
Douglas Gregor92751d42008-11-17 22:58:34 +00002218 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002219
Daniel Jasper0baec5492012-06-06 08:32:04 +00002220 if (isInstField) {
2221 FieldDecl *FD = cast<FieldDecl>(Member);
2222 FieldCollector->Add(FD);
2223
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002224 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002225 // Remember all explicit private FieldDecls that have a name, no side
2226 // effects and are not part of a dependent type declaration.
2227 if (!FD->isImplicit() && FD->getDeclName() &&
2228 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002229 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002230 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002231 !InitializationHasSideEffects(*FD))
2232 UnusedPrivateFields.insert(FD);
2233 }
2234 }
2235
John McCall48871652010-08-21 09:40:31 +00002236 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002237}
2238
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002239namespace {
2240 class UninitializedFieldVisitor
2241 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2242 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002243 // List of Decls to generate a warning on. Also remove Decls that become
2244 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002245 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002246 // List of base classes of the record. Classes are removed after their
2247 // initializers.
2248 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002249 // Vector of decls to be removed from the Decl set prior to visiting the
2250 // nodes. These Decls may have been initialized in the prior initializer.
2251 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002252 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002253 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002254 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002255 // InitList is true, special case initialization of FieldDecls matching
2256 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002257 bool InitList;
2258 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002259 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2260
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002261 public:
2262 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002263 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002264 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2265 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2266 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2267 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002268
Richard Trieufa1d0a72014-10-17 20:56:10 +00002269 // Returns true if the use of ME is not an uninitialized use.
2270 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2271 bool CheckReferenceOnly) {
2272 llvm::SmallVector<FieldDecl*, 4> Fields;
2273 bool ReferenceField = false;
2274 while (ME) {
2275 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2276 if (!FD)
2277 return false;
2278 Fields.push_back(FD);
2279 if (FD->getType()->isReferenceType())
2280 ReferenceField = true;
2281 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2282 }
2283
2284 // Binding a reference to an unintialized field is not an
2285 // uninitialized use.
2286 if (CheckReferenceOnly && !ReferenceField)
2287 return true;
2288
2289 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2290 // Discard the first field since it is the field decl that is being
2291 // initialized.
2292 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2293 UsedFieldIndex.push_back((*I)->getFieldIndex());
2294 }
2295
2296 for (auto UsedIter = UsedFieldIndex.begin(),
2297 UsedEnd = UsedFieldIndex.end(),
2298 OrigIter = InitFieldIndex.begin(),
2299 OrigEnd = InitFieldIndex.end();
2300 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2301 if (*UsedIter < *OrigIter)
2302 return true;
2303 if (*UsedIter > *OrigIter)
2304 break;
2305 }
2306
2307 return false;
2308 }
2309
Richard Trieu2d779b92014-10-01 03:44:58 +00002310 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2311 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002312 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2313 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002314
Richard Trieu1bc22c12013-09-13 03:20:53 +00002315 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2316 // or union.
2317 MemberExpr *FieldME = ME;
2318
Richard Trieu2d779b92014-10-01 03:44:58 +00002319 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2320
Richard Trieu1bc22c12013-09-13 03:20:53 +00002321 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002322 while (MemberExpr *SubME =
2323 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002324
Richard Trieufa1d0a72014-10-17 20:56:10 +00002325 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002326 return;
2327
Richard Trieufa1d0a72014-10-17 20:56:10 +00002328 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002329 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002330 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002331
Richard Trieu2d779b92014-10-01 03:44:58 +00002332 if (!FieldME->getType().isPODType(S.Context))
2333 AllPODFields = false;
2334
Richard Trieu3630c392014-11-21 03:10:30 +00002335 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002336 }
2337
Richard Trieu3630c392014-11-21 03:10:30 +00002338 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002339 return;
2340
Richard Trieu2d779b92014-10-01 03:44:58 +00002341 if (AddressOf && AllPODFields)
2342 return;
2343
Richard Trieu406e65c2013-09-20 03:03:06 +00002344 ValueDecl* FoundVD = FieldME->getMemberDecl();
2345
Richard Trieu3630c392014-11-21 03:10:30 +00002346 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2347 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2348 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2349 }
2350
2351 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2352 QualType T = BaseCast->getType();
2353 if (T->isPointerType() &&
2354 BaseClasses.count(T->getPointeeType())) {
2355 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2356 << T->getPointeeType() << FoundVD;
2357 }
2358 }
2359 }
2360
Richard Trieuef64e942013-10-25 00:56:00 +00002361 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002362 return;
2363
Richard Trieuef64e942013-10-25 00:56:00 +00002364 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002365
Richard Trieufa1d0a72014-10-17 20:56:10 +00002366 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2367 // Special checking for initializer lists.
2368 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2369 return;
2370 }
2371 } else {
2372 // Prevent double warnings on use of unbounded references.
2373 if (CheckReferenceOnly && !IsReference)
2374 return;
2375 }
Richard Trieuef64e942013-10-25 00:56:00 +00002376
2377 unsigned diag = IsReference
2378 ? diag::warn_reference_field_is_uninit
2379 : diag::warn_field_is_uninit;
2380 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2381 if (Constructor)
2382 S.Diag(Constructor->getLocation(),
2383 diag::note_uninit_in_this_constructor)
2384 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2385
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002386 }
2387
Richard Trieu2d779b92014-10-01 03:44:58 +00002388 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002389 E = E->IgnoreParens();
2390
2391 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002392 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2393 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002394 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002395 }
2396
2397 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002398 Visit(CO->getCond());
2399 HandleValue(CO->getTrueExpr(), AddressOf);
2400 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002401 return;
2402 }
2403
2404 if (BinaryConditionalOperator *BCO =
2405 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002406 Visit(BCO->getCond());
2407 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002408 return;
2409 }
2410
Richard Trieuabf6ec42014-08-27 22:15:10 +00002411 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002412 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002413 return;
2414 }
2415
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2417 switch (BO->getOpcode()) {
2418 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002419 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002420 case(BO_PtrMemD):
2421 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002422 HandleValue(BO->getLHS(), AddressOf);
2423 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002424 return;
2425 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002426 Visit(BO->getLHS());
2427 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002428 return;
2429 }
2430 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002431
2432 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002433 }
2434
Richard Trieufa1d0a72014-10-17 20:56:10 +00002435 void CheckInitListExpr(InitListExpr *ILE) {
2436 InitFieldIndex.push_back(0);
2437 for (auto Child : ILE->children()) {
2438 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2439 CheckInitListExpr(SubList);
2440 } else {
2441 Visit(Child);
2442 }
2443 ++InitFieldIndex.back();
2444 }
2445 InitFieldIndex.pop_back();
2446 }
2447
Richard Trieu8d08a272014-08-28 03:23:47 +00002448 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002449 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002450 // Remove Decls that may have been initialized in the previous
2451 // initializer.
2452 for (ValueDecl* VD : DeclsToRemove)
2453 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002454 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002455
Richard Trieu8d08a272014-08-28 03:23:47 +00002456 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002457 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2458
2459 if (ILE && Field) {
2460 InitList = true;
2461 InitListFieldDecl = Field;
2462 InitFieldIndex.clear();
2463 CheckInitListExpr(ILE);
2464 } else {
2465 InitList = false;
2466 Visit(E);
2467 }
2468
Richard Trieu8d08a272014-08-28 03:23:47 +00002469 if (Field)
2470 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002471 if (BaseClass)
2472 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002473 }
2474
Richard Trieu1bc22c12013-09-13 03:20:53 +00002475 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002476 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002477 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002478 }
2479
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002480 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002481 if (E->getCastKind() == CK_LValueToRValue) {
2482 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2483 return;
2484 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002485
2486 Inherited::VisitImplicitCastExpr(E);
2487 }
2488
Richard Trieu1bc22c12013-09-13 03:20:53 +00002489 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002490 if (E->getConstructor()->isCopyConstructor()) {
2491 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002492 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2493 if (ILE->getNumInits() == 1)
2494 ArgExpr = ILE->getInit(0);
2495 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2496 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002497 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002498 HandleValue(ArgExpr, false /*AddressOf*/);
2499 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002500 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002501 Inherited::VisitCXXConstructExpr(E);
2502 }
2503
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002504 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2505 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002506 if (isa<MemberExpr>(Callee)) {
2507 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002508 for (auto Arg : E->arguments())
2509 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002510 return;
2511 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002512
2513 Inherited::VisitCXXMemberCallExpr(E);
2514 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002515
Richard Trieu11fd0792014-08-26 04:30:55 +00002516 void VisitCallExpr(CallExpr *E) {
2517 // Treat std::move as a use.
2518 if (E->getNumArgs() == 1) {
2519 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002520 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2521 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002522 HandleValue(E->getArg(0), false /*AddressOf*/);
2523 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002524 }
2525 }
2526 }
2527
2528 Inherited::VisitCallExpr(E);
2529 }
2530
Richard Trieud4a01362014-10-31 21:10:22 +00002531 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2532 Expr *Callee = E->getCallee();
2533
2534 if (isa<UnresolvedLookupExpr>(Callee))
2535 return Inherited::VisitCXXOperatorCallExpr(E);
2536
2537 Visit(Callee);
2538 for (auto Arg : E->arguments())
2539 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2540 }
2541
Richard Trieu406e65c2013-09-20 03:03:06 +00002542 void VisitBinaryOperator(BinaryOperator *E) {
2543 // If a field assignment is detected, remove the field from the
2544 // uninitiailized field set.
2545 if (E->getOpcode() == BO_Assign)
2546 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2547 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002548 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002549 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002550
Richard Trieu52b8b602014-09-25 01:15:40 +00002551 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002552 HandleValue(E->getLHS(), false /*AddressOf*/);
2553 Visit(E->getRHS());
2554 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002555 }
2556
Richard Trieu406e65c2013-09-20 03:03:06 +00002557 Inherited::VisitBinaryOperator(E);
2558 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002559
2560 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002561 if (E->isIncrementDecrementOp()) {
2562 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2563 return;
2564 }
2565 if (E->getOpcode() == UO_AddrOf) {
2566 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2567 HandleValue(ME->getBase(), true /*AddressOf*/);
2568 return;
2569 }
2570 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002571
2572 Inherited::VisitUnaryOperator(E);
2573 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002574 };
Richard Trieuef64e942013-10-25 00:56:00 +00002575
2576 // Diagnose value-uses of fields to initialize themselves, e.g.
2577 // foo(foo)
2578 // where foo is not also a parameter to the constructor.
2579 // Also diagnose across field uninitialized use such as
2580 // x(y), y(x)
2581 // TODO: implement -Wuninitialized and fold this into that framework.
2582 static void DiagnoseUninitializedFields(
2583 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2584
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002585 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2586 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002587 return;
2588 }
2589
2590 if (Constructor->isInvalidDecl())
2591 return;
2592
2593 const CXXRecordDecl *RD = Constructor->getParent();
2594
Richard Trieu353a4b42014-10-22 05:21:59 +00002595 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002596 return;
2597
Richard Trieuef64e942013-10-25 00:56:00 +00002598 // Holds fields that are uninitialized.
2599 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2600
2601 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002602 for (auto *I : RD->decls()) {
2603 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002604 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002605 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002606 UninitializedFields.insert(IFD->getAnonField());
2607 }
2608 }
2609
Richard Trieu3630c392014-11-21 03:10:30 +00002610 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2611 for (auto I : RD->bases())
2612 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2613
2614 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002615 return;
2616
2617 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002618 UninitializedFields,
2619 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002620
Aaron Ballman0ad78302014-03-13 17:34:31 +00002621 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002622 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002623 break;
2624
Aaron Ballman0ad78302014-03-13 17:34:31 +00002625 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002626 if (!InitExpr)
2627 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002628
Richard Trieu8d08a272014-08-28 03:23:47 +00002629 if (CXXDefaultInitExpr *Default =
2630 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2631 InitExpr = Default->getExpr();
2632 if (!InitExpr)
2633 continue;
2634 // In class initializers will point to the constructor.
2635 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002636 FieldInit->getAnyMember(),
2637 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002638 } else {
2639 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002640 FieldInit->getAnyMember(),
2641 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002642 }
Richard Trieuef64e942013-10-25 00:56:00 +00002643 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002644 }
2645} // namespace
2646
Richard Smith74108172014-01-17 03:11:34 +00002647/// \brief Enter a new C++ default initializer scope. After calling this, the
2648/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2649/// parsing or instantiating the initializer failed.
2650void Sema::ActOnStartCXXInClassMemberInitializer() {
2651 // Create a synthetic function scope to represent the call to the constructor
2652 // that notionally surrounds a use of this initializer.
2653 PushFunctionScope();
2654}
2655
2656/// \brief This is invoked after parsing an in-class initializer for a
2657/// non-static C++ class member, and after instantiating an in-class initializer
2658/// in a class template. Such actions are deferred until the class is complete.
2659void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2660 SourceLocation InitLoc,
2661 Expr *InitExpr) {
2662 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002663 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002664
David Majnemer87ff66c2014-12-13 11:34:16 +00002665 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2666 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002667 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002668
2669 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002670 D->setInvalidDecl();
2671 if (FD)
2672 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002673 return;
2674 }
2675
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002676 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2677 FD->setInvalidDecl();
2678 FD->removeInClassInitializer();
2679 return;
2680 }
2681
Richard Smith938f40b2011-06-11 17:19:42 +00002682 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002683 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002684 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002685 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002686 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002687 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002688 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2689 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002690 if (Init.isInvalid()) {
2691 FD->setInvalidDecl();
2692 return;
2693 }
Richard Smith938f40b2011-06-11 17:19:42 +00002694 }
2695
Richard Smith945f8d32013-01-14 22:39:08 +00002696 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002697 // The initialization of each base and member constitutes a
2698 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002699 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002700 if (Init.isInvalid()) {
2701 FD->setInvalidDecl();
2702 return;
2703 }
2704
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002705 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002706
2707 FD->setInClassInitializer(InitExpr);
2708}
2709
Douglas Gregor15e77a22009-12-31 09:10:24 +00002710/// \brief Find the direct and/or virtual base specifiers that
2711/// correspond to the given base type, for use in base initialization
2712/// within a constructor.
2713static bool FindBaseInitializer(Sema &SemaRef,
2714 CXXRecordDecl *ClassDecl,
2715 QualType BaseType,
2716 const CXXBaseSpecifier *&DirectBaseSpec,
2717 const CXXBaseSpecifier *&VirtualBaseSpec) {
2718 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002719 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002720 for (const auto &Base : ClassDecl->bases()) {
2721 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002722 // We found a direct base of this type. That's what we're
2723 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002724 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002725 break;
2726 }
2727 }
2728
2729 // Check for a virtual base class.
2730 // FIXME: We might be able to short-circuit this if we know in advance that
2731 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002732 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002733 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2734 // We haven't found a base yet; search the class hierarchy for a
2735 // virtual base class.
2736 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2737 /*DetectVirtual=*/false);
2738 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2739 BaseType, Paths)) {
2740 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2741 Path != Paths.end(); ++Path) {
2742 if (Path->back().Base->isVirtual()) {
2743 VirtualBaseSpec = Path->back().Base;
2744 break;
2745 }
2746 }
2747 }
2748 }
2749
2750 return DirectBaseSpec || VirtualBaseSpec;
2751}
2752
Sebastian Redla74948d2011-09-24 17:48:25 +00002753/// \brief Handle a C++ member initializer using braced-init-list syntax.
2754MemInitResult
2755Sema::ActOnMemInitializer(Decl *ConstructorD,
2756 Scope *S,
2757 CXXScopeSpec &SS,
2758 IdentifierInfo *MemberOrBase,
2759 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002760 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002761 SourceLocation IdLoc,
2762 Expr *InitList,
2763 SourceLocation EllipsisLoc) {
2764 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002765 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002766 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002767}
2768
2769/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002770MemInitResult
John McCall48871652010-08-21 09:40:31 +00002771Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002772 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002773 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002774 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002775 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002776 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002777 SourceLocation IdLoc,
2778 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002779 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002780 SourceLocation RParenLoc,
2781 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002782 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002783 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002784 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002785 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002786}
2787
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002788namespace {
2789
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002790// Callback to only accept typo corrections that can be a valid C++ member
2791// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002792class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002793public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002794 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2795 : ClassDecl(ClassDecl) {}
2796
Craig Toppera798a9d2014-03-02 09:32:10 +00002797 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002798 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2799 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2800 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002801 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002802 }
2803 return false;
2804 }
2805
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002806private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002807 CXXRecordDecl *ClassDecl;
2808};
2809
2810}
2811
Sebastian Redla74948d2011-09-24 17:48:25 +00002812/// \brief Handle a C++ member initializer.
2813MemInitResult
2814Sema::BuildMemInitializer(Decl *ConstructorD,
2815 Scope *S,
2816 CXXScopeSpec &SS,
2817 IdentifierInfo *MemberOrBase,
2818 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002819 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002820 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002821 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002822 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002823 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2824 if (!Res.isUsable())
2825 return true;
2826 Init = Res.get();
2827
Douglas Gregor71a57182009-06-22 23:20:33 +00002828 if (!ConstructorD)
2829 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002830
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002831 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002832
2833 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002834 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002835 if (!Constructor) {
2836 // The user wrote a constructor initializer on a function that is
2837 // not a C++ constructor. Ignore the error for now, because we may
2838 // have more member initializers coming; we'll diagnose it just
2839 // once in ActOnMemInitializers.
2840 return true;
2841 }
2842
2843 CXXRecordDecl *ClassDecl = Constructor->getParent();
2844
2845 // C++ [class.base.init]p2:
2846 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002847 // constructor's class and, if not found in that scope, are looked
2848 // up in the scope containing the constructor's definition.
2849 // [Note: if the constructor's class contains a member with the
2850 // same name as a direct or virtual base class of the class, a
2851 // mem-initializer-id naming the member or base class and composed
2852 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002853 // mem-initializer-id for the hidden base class may be specified
2854 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002855 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002856 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002857 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002858 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002859 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002860 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2861 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002862 if (EllipsisLoc.isValid())
2863 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002864 << MemberOrBase
2865 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002866
Sebastian Redla9351792012-02-11 23:51:47 +00002867 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002868 }
Francois Pichetd583da02010-12-04 09:14:42 +00002869 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002870 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002871 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002872 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002873 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002874
2875 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002876 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002877 } else if (DS.getTypeSpecType() == TST_decltype) {
2878 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002879 } else {
2880 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2881 LookupParsedName(R, S, &SS);
2882
2883 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2884 if (!TyD) {
2885 if (R.isAmbiguous()) return true;
2886
John McCallda6841b2010-04-09 19:01:14 +00002887 // We don't want access-control diagnostics here.
2888 R.suppressDiagnostics();
2889
Douglas Gregora3b624a2010-01-19 06:46:48 +00002890 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2891 bool NotUnknownSpecialization = false;
2892 DeclContext *DC = computeDeclContext(SS, false);
2893 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2894 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2895
2896 if (!NotUnknownSpecialization) {
2897 // When the scope specifier can refer to a member of an unknown
2898 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002899 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2900 SS.getWithLocInContext(Context),
2901 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002902 if (BaseType.isNull())
2903 return true;
2904
Douglas Gregora3b624a2010-01-19 06:46:48 +00002905 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002906 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002907 }
2908 }
2909
Douglas Gregor15e77a22009-12-31 09:10:24 +00002910 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002911 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002912 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002913 (Corr = CorrectTypo(
2914 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2915 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2916 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002917 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002918 // We have found a non-static data member with a similar
2919 // name to what was typed; complain and initialize that
2920 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002921 diagnoseTypo(Corr,
2922 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2923 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002924 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002925 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002926 const CXXBaseSpecifier *DirectBaseSpec;
2927 const CXXBaseSpecifier *VirtualBaseSpec;
2928 if (FindBaseInitializer(*this, ClassDecl,
2929 Context.getTypeDeclType(Type),
2930 DirectBaseSpec, VirtualBaseSpec)) {
2931 // We have found a direct or virtual base class with a
2932 // similar name to what was typed; complain and initialize
2933 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002934 diagnoseTypo(Corr,
2935 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2936 << MemberOrBase << false,
2937 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002938
Richard Smithf9b15102013-08-17 00:46:16 +00002939 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2940 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002941 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002942 diag::note_base_class_specified_here)
2943 << BaseSpec->getType()
2944 << BaseSpec->getSourceRange();
2945
Douglas Gregor15e77a22009-12-31 09:10:24 +00002946 TyD = Type;
2947 }
2948 }
2949 }
2950
Douglas Gregora3b624a2010-01-19 06:46:48 +00002951 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002952 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002953 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002954 return true;
2955 }
John McCallb5a0d312009-12-21 10:41:20 +00002956 }
2957
Douglas Gregora3b624a2010-01-19 06:46:48 +00002958 if (BaseType.isNull()) {
2959 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00002960 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00002961 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002962 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002963 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2964 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002965 }
2966 }
Mike Stump11289f42009-09-09 15:08:12 +00002967
John McCallbcd03502009-12-07 02:54:59 +00002968 if (!TInfo)
2969 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002970
Sebastian Redla9351792012-02-11 23:51:47 +00002971 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002972}
2973
Chandler Carruth599deef2011-09-03 01:14:15 +00002974/// Checks a member initializer expression for cases where reference (or
2975/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002976static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2977 Expr *Init,
2978 SourceLocation IdLoc) {
2979 QualType MemberTy = Member->getType();
2980
2981 // We only handle pointers and references currently.
2982 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2983 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2984 return;
2985
2986 const bool IsPointer = MemberTy->isPointerType();
2987 if (IsPointer) {
2988 if (const UnaryOperator *Op
2989 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2990 // The only case we're worried about with pointers requires taking the
2991 // address.
2992 if (Op->getOpcode() != UO_AddrOf)
2993 return;
2994
2995 Init = Op->getSubExpr();
2996 } else {
2997 // We only handle address-of expression initializers for pointers.
2998 return;
2999 }
3000 }
3001
Richard Smithe3b28bc2013-06-12 21:51:50 +00003002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003003 // We only warn when referring to a non-reference parameter declaration.
3004 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3005 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003006 return;
3007
3008 S.Diag(Init->getExprLoc(),
3009 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3010 : diag::warn_bind_ref_member_to_parameter)
3011 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003012 } else {
3013 // Other initializers are fine.
3014 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003015 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003016
3017 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3018 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003019}
3020
John McCallfaf5fb42010-08-26 23:41:50 +00003021MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003022Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003023 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003024 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3025 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3026 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003027 "Member must be a FieldDecl or IndirectFieldDecl");
3028
Sebastian Redla9351792012-02-11 23:51:47 +00003029 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003030 return true;
3031
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003032 if (Member->isInvalidDecl())
3033 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003034
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003035 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003036 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003037 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003038 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003039 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003040 } else {
3041 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003042 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003043 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003044
Sebastian Redla9351792012-02-11 23:51:47 +00003045 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003046
Sebastian Redla9351792012-02-11 23:51:47 +00003047 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003048 // Can't check initialization for a member of dependent type or when
3049 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003050 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003051 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003052 bool InitList = false;
3053 if (isa<InitListExpr>(Init)) {
3054 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003055 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003056 }
3057
Chandler Carruthd44c3102010-12-06 09:23:57 +00003058 // Initialize the member.
3059 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003060 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3061 : InitializedEntity::InitializeMember(IndirectMember,
3062 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003063 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003064 InitList ? InitializationKind::CreateDirectList(IdLoc)
3065 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3066 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003067
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003068 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003069 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3070 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003071 if (MemberInit.isInvalid())
3072 return true;
3073
Richard Smith736a9472013-06-12 20:42:33 +00003074 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3075
Richard Smith945f8d32013-01-14 22:39:08 +00003076 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003077 // The initialization of each base and member constitutes a
3078 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003079 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003080 if (MemberInit.isInvalid())
3081 return true;
3082
Richard Smithd59b8322012-12-19 01:39:02 +00003083 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003084 }
3085
Chandler Carruthd44c3102010-12-06 09:23:57 +00003086 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003087 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3088 InitRange.getBegin(), Init,
3089 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003090 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003091 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3092 InitRange.getBegin(), Init,
3093 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003094 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003095}
3096
John McCallfaf5fb42010-08-26 23:41:50 +00003097MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003098Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003099 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003100 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003101 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003102 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003103 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003104 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003105
Sebastian Redl0501c632012-02-12 16:37:36 +00003106 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003107 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003108 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3109 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003110 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003111 }
3112
Sebastian Redla9351792012-02-11 23:51:47 +00003113 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003114 // Initialize the object.
3115 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3116 QualType(ClassDecl->getTypeForDecl(), 0));
3117 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003118 InitList ? InitializationKind::CreateDirectList(NameLoc)
3119 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3120 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003121 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003122 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003123 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003124 if (DelegationInit.isInvalid())
3125 return true;
3126
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003127 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3128 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003129
Richard Smith945f8d32013-01-14 22:39:08 +00003130 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003131 // The initialization of each base and member constitutes a
3132 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003133 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3134 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003135 if (DelegationInit.isInvalid())
3136 return true;
3137
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003138 // If we are in a dependent context, template instantiation will
3139 // perform this type-checking again. Just save the arguments that we
3140 // received in a ParenListExpr.
3141 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3142 // of the information that we have about the base
3143 // initializer. However, deconstructing the ASTs is a dicey process,
3144 // and this approach is far more likely to get the corner cases right.
3145 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003146 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003147
Sebastian Redla9351792012-02-11 23:51:47 +00003148 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003149 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003150 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003151}
3152
3153MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003154Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003155 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003156 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003157 SourceLocation BaseLoc
3158 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003159
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003160 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3161 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3162 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3163
3164 // C++ [class.base.init]p2:
3165 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003166 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003167 // of that class, the mem-initializer is ill-formed. A
3168 // mem-initializer-list can initialize a base class using any
3169 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003170 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003171
Sebastian Redla9351792012-02-11 23:51:47 +00003172 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003173 if (EllipsisLoc.isValid()) {
3174 // This is a pack expansion.
3175 if (!BaseType->containsUnexpandedParameterPack()) {
3176 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003177 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003178
Douglas Gregor44e7df62011-01-04 00:32:56 +00003179 EllipsisLoc = SourceLocation();
3180 }
3181 } else {
3182 // Check for any unexpanded parameter packs.
3183 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3184 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003185
Sebastian Redla9351792012-02-11 23:51:47 +00003186 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003187 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003188 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003189
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003190 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003191 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3192 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003193 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003194 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3195 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003196 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003197
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003198 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3199 VirtualBaseSpec);
3200
3201 // C++ [base.class.init]p2:
3202 // Unless the mem-initializer-id names a nonstatic data member of the
3203 // constructor's class or a direct or virtual base of that class, the
3204 // mem-initializer is ill-formed.
3205 if (!DirectBaseSpec && !VirtualBaseSpec) {
3206 // If the class has any dependent bases, then it's possible that
3207 // one of those types will resolve to the same type as
3208 // BaseType. Therefore, just treat this as a dependent base
3209 // class initialization. FIXME: Should we try to check the
3210 // initialization anyway? It seems odd.
3211 if (ClassDecl->hasAnyDependentBases())
3212 Dependent = true;
3213 else
3214 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3215 << BaseType << Context.getTypeDeclType(ClassDecl)
3216 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3217 }
3218 }
3219
3220 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003221 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003222
Sebastian Redla74948d2011-09-24 17:48:25 +00003223 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3224 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003225 InitRange.getBegin(), Init,
3226 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003227 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003228
3229 // C++ [base.class.init]p2:
3230 // If a mem-initializer-id is ambiguous because it designates both
3231 // a direct non-virtual base class and an inherited virtual base
3232 // class, the mem-initializer is ill-formed.
3233 if (DirectBaseSpec && VirtualBaseSpec)
3234 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003235 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003236
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003237 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003238 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003239 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003240
3241 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003242 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003243 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003244 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003245 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003246 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003247 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003248
3249 InitializedEntity BaseEntity =
3250 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3251 InitializationKind Kind =
3252 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3253 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3254 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003255 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003256 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003257 if (BaseInit.isInvalid())
3258 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003259
Richard Smith945f8d32013-01-14 22:39:08 +00003260 // C++11 [class.base.init]p7:
3261 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003262 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003263 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003264 if (BaseInit.isInvalid())
3265 return true;
3266
3267 // If we are in a dependent context, template instantiation will
3268 // perform this type-checking again. Just save the arguments that we
3269 // received in a ParenListExpr.
3270 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3271 // of the information that we have about the base
3272 // initializer. However, deconstructing the ASTs is a dicey process,
3273 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003274 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003275 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003276
Alexis Hunt1d792652011-01-08 20:30:50 +00003277 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003278 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003279 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003280 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003281 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003282}
3283
Sebastian Redl22653ba2011-08-30 19:58:05 +00003284// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003285static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3286 if (T.isNull()) T = E->getType();
3287 QualType TargetType = SemaRef.BuildReferenceType(
3288 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003289 SourceLocation ExprLoc = E->getLocStart();
3290 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3291 TargetType, ExprLoc);
3292
3293 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3294 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003295 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003296}
3297
Anders Carlsson1b00e242010-04-23 03:10:23 +00003298/// ImplicitInitializerKind - How an implicit base or member initializer should
3299/// initialize its base or member.
3300enum ImplicitInitializerKind {
3301 IIK_Default,
3302 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003303 IIK_Move,
3304 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003305};
3306
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003307static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003308BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003309 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003310 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003311 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003312 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003313 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003314 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3315 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003316
John McCalldadc5752010-08-24 06:29:42 +00003317 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003318
3319 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003320 case IIK_Inherit: {
3321 const CXXRecordDecl *Inherited =
3322 Constructor->getInheritedConstructor()->getParent();
3323 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3324 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3325 // C++11 [class.inhctor]p8:
3326 // Each expression in the expression-list is of the form
3327 // static_cast<T&&>(p), where p is the name of the corresponding
3328 // constructor parameter and T is the declared type of p.
3329 SmallVector<Expr*, 16> Args;
3330 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3331 ParmVarDecl *PD = Constructor->getParamDecl(I);
3332 ExprResult ArgExpr =
3333 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3334 VK_LValue, SourceLocation());
3335 if (ArgExpr.isInvalid())
3336 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003337 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003338 }
3339
3340 InitializationKind InitKind = InitializationKind::CreateDirect(
3341 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003342 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003343 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3344 break;
3345 }
3346 }
3347 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003348 case IIK_Default: {
3349 InitializationKind InitKind
3350 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003351 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3352 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003353 break;
3354 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003355
Sebastian Redl22653ba2011-08-30 19:58:05 +00003356 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003357 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003358 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003359 ParmVarDecl *Param = Constructor->getParamDecl(0);
3360 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003361
Anders Carlsson1b00e242010-04-23 03:10:23 +00003362 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003363 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003364 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003365 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003366 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003367
Eli Friedmanfa0df832012-02-02 03:46:19 +00003368 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3369
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003370 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003371 QualType ArgTy =
3372 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3373 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003374
Sebastian Redl22653ba2011-08-30 19:58:05 +00003375 if (Moving) {
3376 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3377 }
3378
John McCallcf142162010-08-07 06:22:56 +00003379 CXXCastPath BasePath;
3380 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003381 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3382 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003383 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003384 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003385
Anders Carlsson1b00e242010-04-23 03:10:23 +00003386 InitializationKind InitKind
3387 = InitializationKind::CreateDirect(Constructor->getLocation(),
3388 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003389 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3390 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003391 break;
3392 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003393 }
John McCallb268a282010-08-23 23:25:46 +00003394
Douglas Gregora40433a2010-12-07 00:41:46 +00003395 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003396 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003397 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003398
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003399 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003400 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003401 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3402 SourceLocation()),
3403 BaseSpec->isVirtual(),
3404 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003405 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003406 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003407 SourceLocation());
3408
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003409 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003410}
3411
Sebastian Redl22653ba2011-08-30 19:58:05 +00003412static bool RefersToRValueRef(Expr *MemRef) {
3413 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3414 return Referenced->getType()->isRValueReferenceType();
3415}
3416
Anders Carlsson3c1db572010-04-23 02:15:47 +00003417static bool
3418BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003419 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003420 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003421 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003422 if (Field->isInvalidDecl())
3423 return true;
3424
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003425 SourceLocation Loc = Constructor->getLocation();
3426
Sebastian Redl22653ba2011-08-30 19:58:05 +00003427 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3428 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003429 ParmVarDecl *Param = Constructor->getParamDecl(0);
3430 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003431
3432 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003433 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3434 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003435
Anders Carlsson423f5d82010-04-23 16:04:08 +00003436 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003437 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003438 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003439 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003440
Eli Friedmanfa0df832012-02-02 03:46:19 +00003441 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3442
Sebastian Redl22653ba2011-08-30 19:58:05 +00003443 if (Moving) {
3444 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3445 }
3446
Douglas Gregor94f9a482010-05-05 05:51:00 +00003447 // Build a reference to this field within the parameter.
3448 CXXScopeSpec SS;
3449 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3450 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003451 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3452 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003453 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003454 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003455 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003456 ParamType, Loc,
3457 /*IsArrow=*/false,
3458 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003459 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003460 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003461 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003462 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003463 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003464 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003465
3466 // C++11 [class.copy]p15:
3467 // - if a member m has rvalue reference type T&&, it is direct-initialized
3468 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003469 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003470 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003471 }
3472
Douglas Gregor94f9a482010-05-05 05:51:00 +00003473 // When the field we are copying is an array, create index variables for
3474 // each dimension of the array. We use these index variables to subscript
3475 // the source array, and other clients (e.g., CodeGen) will perform the
3476 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003477 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003478 QualType BaseType = Field->getType();
3479 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003480 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003481 while (const ConstantArrayType *Array
3482 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003483 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003484 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003485 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003486 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003487 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003488 llvm::raw_svector_ostream OS(Str);
3489 OS << "__i" << IndexVariables.size();
3490 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3491 }
3492 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003493 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003494 IterationVarName, SizeType,
3495 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003496 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003497 IndexVariables.push_back(IterationVar);
3498
3499 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003500 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003501 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003502 assert(!IterationVarRef.isInvalid() &&
3503 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003504 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003505 assert(!IterationVarRef.isInvalid() &&
3506 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003507
Douglas Gregor94f9a482010-05-05 05:51:00 +00003508 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003509 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3510 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003511 Loc);
3512 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003513 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003514
Douglas Gregor94f9a482010-05-05 05:51:00 +00003515 BaseType = Array->getElementType();
3516 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003517
3518 // The array subscript expression is an lvalue, which is wrong for moving.
3519 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003520 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003521
Douglas Gregor94f9a482010-05-05 05:51:00 +00003522 // Construct the entity that we will be initializing. For an array, this
3523 // will be first element in the array, which may require several levels
3524 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003525 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003526 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003527 if (Indirect)
3528 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3529 else
3530 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003531 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3532 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3533 0,
3534 Entities.back()));
3535
3536 // Direct-initialize to use the copy constructor.
3537 InitializationKind InitKind =
3538 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3539
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003540 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003541 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003542
John McCalldadc5752010-08-24 06:29:42 +00003543 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003544 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003545 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003546 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003547 if (MemberInit.isInvalid())
3548 return true;
3549
Douglas Gregor493627b2011-08-10 15:22:55 +00003550 if (Indirect) {
3551 assert(IndexVariables.size() == 0 &&
3552 "Indirect field improperly initialized");
3553 CXXMemberInit
3554 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3555 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003556 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003557 Loc);
3558 } else
3559 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003560 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003561 Loc,
3562 IndexVariables.data(),
3563 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003564 return false;
3565 }
3566
Richard Smithc2bc61b2013-03-18 21:12:30 +00003567 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3568 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003569
Anders Carlsson3c1db572010-04-23 02:15:47 +00003570 QualType FieldBaseElementType =
3571 SemaRef.Context.getBaseElementType(Field->getType());
3572
Anders Carlsson3c1db572010-04-23 02:15:47 +00003573 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003574 InitializedEntity InitEntity
3575 = Indirect? InitializedEntity::InitializeMember(Indirect)
3576 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003577 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003578 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003579
3580 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3581 ExprResult MemberInit =
3582 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003583
Douglas Gregora40433a2010-12-07 00:41:46 +00003584 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003585 if (MemberInit.isInvalid())
3586 return true;
3587
Douglas Gregor493627b2011-08-10 15:22:55 +00003588 if (Indirect)
3589 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3590 Indirect, Loc,
3591 Loc,
3592 MemberInit.get(),
3593 Loc);
3594 else
3595 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3596 Field, Loc, Loc,
3597 MemberInit.get(),
3598 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003599 return false;
3600 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003601
Alexis Hunt8b455182011-05-17 00:19:05 +00003602 if (!Field->getParent()->isUnion()) {
3603 if (FieldBaseElementType->isReferenceType()) {
3604 SemaRef.Diag(Constructor->getLocation(),
3605 diag::err_uninitialized_member_in_ctor)
3606 << (int)Constructor->isImplicit()
3607 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3608 << 0 << Field->getDeclName();
3609 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3610 return true;
3611 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003612
Alexis Hunt8b455182011-05-17 00:19:05 +00003613 if (FieldBaseElementType.isConstQualified()) {
3614 SemaRef.Diag(Constructor->getLocation(),
3615 diag::err_uninitialized_member_in_ctor)
3616 << (int)Constructor->isImplicit()
3617 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3618 << 1 << Field->getDeclName();
3619 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3620 return true;
3621 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003622 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003623
David Blaikiebbafb8a2012-03-11 07:00:24 +00003624 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003625 FieldBaseElementType->isObjCRetainableType() &&
3626 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3627 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003628 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003629 // Default-initialize Objective-C pointers to NULL.
3630 CXXMemberInit
3631 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3632 Loc, Loc,
3633 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3634 Loc);
3635 return false;
3636 }
3637
Anders Carlsson3c1db572010-04-23 02:15:47 +00003638 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003639 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003640 return false;
3641}
John McCallbc83b3f2010-05-20 23:23:51 +00003642
3643namespace {
3644struct BaseAndFieldInfo {
3645 Sema &S;
3646 CXXConstructorDecl *Ctor;
3647 bool AnyErrorsInInits;
3648 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003649 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003650 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003651 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003652
3653 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3654 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003655 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3656 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003657 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003658 else if (Generated && Ctor->isMoveConstructor())
3659 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003660 else if (Ctor->getInheritedConstructor())
3661 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003662 else
3663 IIK = IIK_Default;
3664 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003665
3666 bool isImplicitCopyOrMove() const {
3667 switch (IIK) {
3668 case IIK_Copy:
3669 case IIK_Move:
3670 return true;
3671
3672 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003673 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003674 return false;
3675 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003676
3677 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003678 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003679
3680 bool addFieldInitializer(CXXCtorInitializer *Init) {
3681 AllToInit.push_back(Init);
3682
3683 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003684 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003685 S.UnusedPrivateFields.remove(Init->getAnyMember());
3686
3687 return false;
3688 }
John McCallbc83b3f2010-05-20 23:23:51 +00003689
Richard Smithab44d5b2013-12-10 08:25:00 +00003690 bool isInactiveUnionMember(FieldDecl *Field) {
3691 RecordDecl *Record = Field->getParent();
3692 if (!Record->isUnion())
3693 return false;
3694
Richard Smith8d183852013-12-10 20:56:03 +00003695 if (FieldDecl *Active =
3696 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003697 return Active != Field->getCanonicalDecl();
3698
3699 // In an implicit copy or move constructor, ignore any in-class initializer.
3700 if (isImplicitCopyOrMove())
3701 return true;
3702
3703 // If there's no explicit initialization, the field is active only if it
3704 // has an in-class initializer...
3705 if (Field->hasInClassInitializer())
3706 return false;
3707 // ... or it's an anonymous struct or union whose class has an in-class
3708 // initializer.
3709 if (!Field->isAnonymousStructOrUnion())
3710 return true;
3711 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3712 return !FieldRD->hasInClassInitializer();
3713 }
3714
3715 /// \brief Determine whether the given field is, or is within, a union member
3716 /// that is inactive (because there was an initializer given for a different
3717 /// member of the union, or because the union was not initialized at all).
3718 bool isWithinInactiveUnionMember(FieldDecl *Field,
3719 IndirectFieldDecl *Indirect) {
3720 if (!Indirect)
3721 return isInactiveUnionMember(Field);
3722
Aaron Ballman29c94602014-03-07 18:36:15 +00003723 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003724 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003725 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003726 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003727 }
3728 return false;
3729 }
3730};
Richard Smithc94ec842011-09-19 13:34:43 +00003731}
3732
Douglas Gregor10f939c2011-11-02 23:04:16 +00003733/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3734/// array type.
3735static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3736 if (T->isIncompleteArrayType())
3737 return true;
3738
3739 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3740 if (!ArrayT->getSize())
3741 return true;
3742
3743 T = ArrayT->getElementType();
3744 }
3745
3746 return false;
3747}
3748
Richard Smith938f40b2011-06-11 17:19:42 +00003749static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003750 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003751 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003752 if (Field->isInvalidDecl())
3753 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003754
Chandler Carruth139e9622010-06-30 02:59:29 +00003755 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003756 if (CXXCtorInitializer *Init =
3757 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003758 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003759
Richard Smithab44d5b2013-12-10 08:25:00 +00003760 // C++11 [class.base.init]p8:
3761 // if the entity is a non-static data member that has a
3762 // brace-or-equal-initializer and either
3763 // -- the constructor's class is a union and no other variant member of that
3764 // union is designated by a mem-initializer-id or
3765 // -- the constructor's class is not a union, and, if the entity is a member
3766 // of an anonymous union, no other member of that union is designated by
3767 // a mem-initializer-id,
3768 // the entity is initialized as specified in [dcl.init].
3769 //
3770 // We also apply the same rules to handle anonymous structs within anonymous
3771 // unions.
3772 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3773 return false;
3774
Douglas Gregor7db3e952011-11-28 20:03:15 +00003775 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003776 ExprResult DIE =
3777 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3778 if (DIE.isInvalid())
3779 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003780 CXXCtorInitializer *Init;
3781 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003782 Init = new (SemaRef.Context)
3783 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3784 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003785 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003786 Init = new (SemaRef.Context)
3787 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3788 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003789 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003790 }
3791
Douglas Gregor10f939c2011-11-02 23:04:16 +00003792 // Don't initialize incomplete or zero-length arrays.
3793 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3794 return false;
3795
John McCallbc83b3f2010-05-20 23:23:51 +00003796 // Don't try to build an implicit initializer if there were semantic
3797 // errors in any of the initializers (and therefore we might be
3798 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003799 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003800 return false;
3801
Craig Topperc3ec1492014-05-26 06:22:03 +00003802 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003803 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3804 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003805 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003806
Richard Smith0a8cfc72012-08-07 21:30:42 +00003807 if (!Init)
3808 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003809
Richard Smith0a8cfc72012-08-07 21:30:42 +00003810 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003811}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003812
3813bool
3814Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3815 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003816 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003817 Constructor->setNumCtorInitializers(1);
3818 CXXCtorInitializer **initializer =
3819 new (Context) CXXCtorInitializer*[1];
3820 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3821 Constructor->setCtorInitializers(initializer);
3822
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003823 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003824 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003825 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3826 }
3827
Alexis Hunte2622992011-05-05 00:05:47 +00003828 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003829
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003830 DiagnoseUninitializedFields(*this, Constructor);
3831
Alexis Hunt61bc1732011-05-01 07:04:31 +00003832 return false;
3833}
Douglas Gregor493627b2011-08-10 15:22:55 +00003834
David Blaikie3fc2f912013-01-17 05:26:25 +00003835bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3836 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003837 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003838 // Just store the initializers as written, they will be checked during
3839 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003840 if (!Initializers.empty()) {
3841 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003842 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003843 new (Context) CXXCtorInitializer*[Initializers.size()];
3844 memcpy(baseOrMemberInitializers, Initializers.data(),
3845 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003846 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003847 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003848
3849 // Let template instantiation know whether we had errors.
3850 if (AnyErrors)
3851 Constructor->setInvalidDecl();
3852
Anders Carlssondb0a9652010-04-02 06:26:44 +00003853 return false;
3854 }
3855
John McCallbc83b3f2010-05-20 23:23:51 +00003856 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003857
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003858 // We need to build the initializer AST according to order of construction
3859 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003860 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003861 if (!ClassDecl)
3862 return true;
3863
Eli Friedman9cf6b592009-11-09 19:20:36 +00003864 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003865
David Blaikie3fc2f912013-01-17 05:26:25 +00003866 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003867 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003868
Anders Carlssondb0a9652010-04-02 06:26:44 +00003869 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003870 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003871 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003872 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003873
3874 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003875 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003876 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003877 if (FD && FD->getParent()->isUnion())
3878 Info.ActiveUnionMember.insert(std::make_pair(
3879 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3880 }
3881 } else if (FieldDecl *FD = Member->getMember()) {
3882 if (FD->getParent()->isUnion())
3883 Info.ActiveUnionMember.insert(std::make_pair(
3884 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3885 }
3886 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003887 }
3888
Anders Carlsson43c64af2010-04-21 19:52:01 +00003889 // Keep track of the direct virtual bases.
3890 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003891 for (auto &I : ClassDecl->bases()) {
3892 if (I.isVirtual())
3893 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003894 }
3895
Anders Carlssondb0a9652010-04-02 06:26:44 +00003896 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003897 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003898 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003899 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003900 // [class.base.init]p7, per DR257:
3901 // A mem-initializer where the mem-initializer-id names a virtual base
3902 // class is ignored during execution of a constructor of any class that
3903 // is not the most derived class.
3904 if (ClassDecl->isAbstract()) {
3905 // FIXME: Provide a fixit to remove the base specifier. This requires
3906 // tracking the location of the associated comma for a base specifier.
3907 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003908 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003909 DiagnoseAbstractType(ClassDecl);
3910 }
3911
John McCallbc83b3f2010-05-20 23:23:51 +00003912 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003913 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3914 // [class.base.init]p8, per DR257:
3915 // If a given [...] base class is not named by a mem-initializer-id
3916 // [...] and the entity is not a virtual base class of an abstract
3917 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003918 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003919 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003920 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003921 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003922 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003923 HadError = true;
3924 continue;
3925 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003926
John McCallbc83b3f2010-05-20 23:23:51 +00003927 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003928 }
3929 }
Mike Stump11289f42009-09-09 15:08:12 +00003930
John McCallbc83b3f2010-05-20 23:23:51 +00003931 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003932 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003933 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003934 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003935 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003936
Alexis Hunt1d792652011-01-08 20:30:50 +00003937 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003938 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003939 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003940 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003941 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003942 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003943 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003944 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003945 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003946 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003947 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003948
John McCallbc83b3f2010-05-20 23:23:51 +00003949 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003950 }
3951 }
Mike Stump11289f42009-09-09 15:08:12 +00003952
John McCallbc83b3f2010-05-20 23:23:51 +00003953 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003954 for (auto *Mem : ClassDecl->decls()) {
3955 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003956 // C++ [class.bit]p2:
3957 // A declaration for a bit-field that omits the identifier declares an
3958 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3959 // initialized.
3960 if (F->isUnnamedBitfield())
3961 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003962
Sebastian Redl22653ba2011-08-30 19:58:05 +00003963 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003964 // handle anonymous struct/union fields based on their individual
3965 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003966 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003967 continue;
3968
3969 if (CollectFieldInitializer(*this, Info, F))
3970 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003971 continue;
3972 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003973
3974 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003975 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003976 continue;
3977
Aaron Ballman629afae2014-03-07 19:56:05 +00003978 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003979 if (F->getType()->isIncompleteArrayType()) {
3980 assert(ClassDecl->hasFlexibleArrayMember() &&
3981 "Incomplete array type is not valid");
3982 continue;
3983 }
3984
Douglas Gregor493627b2011-08-10 15:22:55 +00003985 // Initialize each field of an anonymous struct individually.
3986 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3987 HadError = true;
3988
3989 continue;
3990 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003991 }
Mike Stump11289f42009-09-09 15:08:12 +00003992
David Blaikie3fc2f912013-01-17 05:26:25 +00003993 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003994 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003995 Constructor->setNumCtorInitializers(NumInitializers);
3996 CXXCtorInitializer **baseOrMemberInitializers =
3997 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003998 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003999 NumInitializers * sizeof(CXXCtorInitializer*));
4000 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004001
John McCalla6309952010-03-16 21:39:52 +00004002 // Constructors implicitly reference the base and member
4003 // destructors.
4004 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4005 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004006 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004007
4008 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004009}
4010
David Blaikieb61b8152013-01-17 08:49:22 +00004011static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004012 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004013 const RecordDecl *RD = RT->getDecl();
4014 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004015 for (auto *Field : RD->fields())
4016 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004017 return;
4018 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004019 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004020 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004021}
4022
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004023static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4024 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004025}
4026
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004027static const void *GetKeyForMember(ASTContext &Context,
4028 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004029 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004030 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004031
Richard Smithcd45dbc2014-04-19 03:48:30 +00004032 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004033}
4034
David Blaikie3fc2f912013-01-17 05:26:25 +00004035static void DiagnoseBaseOrMemInitializerOrder(
4036 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4037 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004038 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004039 return;
Mike Stump11289f42009-09-09 15:08:12 +00004040
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004041 // Don't check initializers order unless the warning is enabled at the
4042 // location of at least one initializer.
4043 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004044 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004045 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004046 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4047 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004048 ShouldCheckOrder = true;
4049 break;
4050 }
4051 }
4052 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004053 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004054
John McCallbb7b6582010-04-10 07:37:23 +00004055 // Build the list of bases and members in the order that they'll
4056 // actually be initialized. The explicit initializers should be in
4057 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004058 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004059
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004060 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4061
John McCallbb7b6582010-04-10 07:37:23 +00004062 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004063 for (const auto &VBase : ClassDecl->vbases())
4064 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCallbb7b6582010-04-10 07:37:23 +00004066 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004067 for (const auto &Base : ClassDecl->bases()) {
4068 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004069 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004070 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004071 }
Mike Stump11289f42009-09-09 15:08:12 +00004072
John McCallbb7b6582010-04-10 07:37:23 +00004073 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004074 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004075 if (Field->isUnnamedBitfield())
4076 continue;
4077
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004078 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004079 }
4080
John McCallbb7b6582010-04-10 07:37:23 +00004081 unsigned NumIdealInits = IdealInitKeys.size();
4082 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004083
Craig Topperc3ec1492014-05-26 06:22:03 +00004084 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004085 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004086 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004087 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004088
4089 // Scan forward to try to find this initializer in the idealized
4090 // initializers list.
4091 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4092 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004093 break;
John McCallbb7b6582010-04-10 07:37:23 +00004094
4095 // If we didn't find this initializer, it must be because we
4096 // scanned past it on a previous iteration. That can only
4097 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004098 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004099 Sema::SemaDiagnosticBuilder D =
4100 SemaRef.Diag(PrevInit->getSourceLocation(),
4101 diag::warn_initializer_out_of_order);
4102
Francois Pichetd583da02010-12-04 09:14:42 +00004103 if (PrevInit->isAnyMemberInitializer())
4104 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004105 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004106 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004107
Francois Pichetd583da02010-12-04 09:14:42 +00004108 if (Init->isAnyMemberInitializer())
4109 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004110 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004111 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004112
4113 // Move back to the initializer's location in the ideal list.
4114 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4115 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004116 break;
John McCallbb7b6582010-04-10 07:37:23 +00004117
4118 assert(IdealIndex != NumIdealInits &&
4119 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004120 }
John McCallbb7b6582010-04-10 07:37:23 +00004121
4122 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004123 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004124}
4125
John McCall23eebd92010-04-10 09:28:51 +00004126namespace {
4127bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004128 CXXCtorInitializer *Init,
4129 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004130 if (!PrevInit) {
4131 PrevInit = Init;
4132 return false;
4133 }
4134
Douglas Gregorea306a12013-03-25 23:28:23 +00004135 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004136 S.Diag(Init->getSourceLocation(),
4137 diag::err_multiple_mem_initialization)
4138 << Field->getDeclName()
4139 << Init->getSourceRange();
4140 else {
John McCall424cec92011-01-19 06:33:43 +00004141 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004142 assert(BaseClass && "neither field nor base");
4143 S.Diag(Init->getSourceLocation(),
4144 diag::err_multiple_base_initialization)
4145 << QualType(BaseClass, 0)
4146 << Init->getSourceRange();
4147 }
4148 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4149 << 0 << PrevInit->getSourceRange();
4150
4151 return true;
4152}
4153
Alexis Hunt1d792652011-01-08 20:30:50 +00004154typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004155typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4156
4157bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004158 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004159 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004160 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004161 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004162 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004163
4164 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004165 if (Parent->isUnion()) {
4166 UnionEntry &En = Unions[Parent];
4167 if (En.first && En.first != Child) {
4168 S.Diag(Init->getSourceLocation(),
4169 diag::err_multiple_mem_union_initialization)
4170 << Field->getDeclName()
4171 << Init->getSourceRange();
4172 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4173 << 0 << En.second->getSourceRange();
4174 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004175 }
4176 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004177 En.first = Child;
4178 En.second = Init;
4179 }
David Blaikie0f65d592011-11-17 06:01:57 +00004180 if (!Parent->isAnonymousStructOrUnion())
4181 return false;
John McCall23eebd92010-04-10 09:28:51 +00004182 }
4183
4184 Child = Parent;
4185 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004186 }
John McCall23eebd92010-04-10 09:28:51 +00004187
4188 return false;
4189}
4190}
4191
Anders Carlssone857b292010-04-02 03:37:03 +00004192/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004193void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004194 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004195 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004196 bool AnyErrors) {
4197 if (!ConstructorDecl)
4198 return;
4199
4200 AdjustDeclIfTemplate(ConstructorDecl);
4201
4202 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004203 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004204
4205 if (!Constructor) {
4206 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4207 return;
4208 }
4209
John McCall23eebd92010-04-10 09:28:51 +00004210 // Mapping for the duplicate initializers check.
4211 // For member initializers, this is keyed with a FieldDecl*.
4212 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004213 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004214
4215 // Mapping for the inconsistent anonymous-union initializers check.
4216 RedundantUnionMap MemberUnions;
4217
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004218 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004219 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004220 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004221
Abramo Bagnara341d7832010-05-26 18:09:23 +00004222 // Set the source order index.
4223 Init->setSourceOrder(i);
4224
Francois Pichetd583da02010-12-04 09:14:42 +00004225 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004226 const void *Key = GetKeyForMember(Context, Init);
4227 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004228 CheckRedundantUnionInit(*this, Init, MemberUnions))
4229 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004230 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004231 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004232 if (CheckRedundantInit(*this, Init, Members[Key]))
4233 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004234 } else {
4235 assert(Init->isDelegatingInitializer());
4236 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004237 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004238 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004239 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004240 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004241 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004242 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004243 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004244 // Return immediately as the initializer is set.
4245 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004246 }
Anders Carlssone857b292010-04-02 03:37:03 +00004247 }
4248
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004249 if (HadError)
4250 return;
4251
David Blaikie3fc2f912013-01-17 05:26:25 +00004252 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004253
David Blaikie3fc2f912013-01-17 05:26:25 +00004254 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004255
Richard Trieuef64e942013-10-25 00:56:00 +00004256 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004257}
4258
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004259void
John McCalla6309952010-03-16 21:39:52 +00004260Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4261 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004262 // Ignore dependent contexts. Also ignore unions, since their members never
4263 // have destructors implicitly called.
4264 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004265 return;
John McCall1064d7e2010-03-16 05:22:47 +00004266
4267 // FIXME: all the access-control diagnostics are positioned on the
4268 // field/base declaration. That's probably good; that said, the
4269 // user might reasonably want to know why the destructor is being
4270 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004271
Anders Carlssondee9a302009-11-17 04:44:12 +00004272 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004273 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004274 if (Field->isInvalidDecl())
4275 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004276
4277 // Don't destroy incomplete or zero-length arrays.
4278 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4279 continue;
4280
Anders Carlssondee9a302009-11-17 04:44:12 +00004281 QualType FieldType = Context.getBaseElementType(Field->getType());
4282
4283 const RecordType* RT = FieldType->getAs<RecordType>();
4284 if (!RT)
4285 continue;
4286
4287 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004288 if (FieldClassDecl->isInvalidDecl())
4289 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004290 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004291 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004292 // The destructor for an implicit anonymous union member is never invoked.
4293 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4294 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004295
Douglas Gregore71edda2010-07-01 22:47:18 +00004296 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004297 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004298 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004299 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004300 << Field->getDeclName()
4301 << FieldType);
4302
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004303 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004304 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004305 }
4306
John McCall1064d7e2010-03-16 05:22:47 +00004307 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4308
Anders Carlssondee9a302009-11-17 04:44:12 +00004309 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004310 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004311 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004312 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004313
4314 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004315 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004316 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004317
John McCall1064d7e2010-03-16 05:22:47 +00004318 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004319 // If our base class is invalid, we probably can't get its dtor anyway.
4320 if (BaseClassDecl->isInvalidDecl())
4321 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004322 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004323 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004324
Douglas Gregore71edda2010-07-01 22:47:18 +00004325 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004326 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004327
4328 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004329 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004330 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004331 << Base.getType()
4332 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004333 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004334
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004335 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004336 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004337 }
4338
4339 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004340 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004341 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004342 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004343
4344 // Ignore direct virtual bases.
4345 if (DirectVirtualBases.count(RT))
4346 continue;
4347
John McCall1064d7e2010-03-16 05:22:47 +00004348 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004349 // If our base class is invalid, we probably can't get its dtor anyway.
4350 if (BaseClassDecl->isInvalidDecl())
4351 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004352 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004353 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004354
Douglas Gregore71edda2010-07-01 22:47:18 +00004355 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004356 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004357 if (CheckDestructorAccess(
4358 ClassDecl->getLocation(), Dtor,
4359 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004360 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004361 Context.getTypeDeclType(ClassDecl)) ==
4362 AR_accessible) {
4363 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004364 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004365 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004366 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004367 }
John McCall1064d7e2010-03-16 05:22:47 +00004368
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004369 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004370 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004371 }
4372}
4373
John McCall48871652010-08-21 09:40:31 +00004374void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004375 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004376 return;
Mike Stump11289f42009-09-09 15:08:12 +00004377
Mike Stump11289f42009-09-09 15:08:12 +00004378 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004379 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004380 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004381 DiagnoseUninitializedFields(*this, Constructor);
4382 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004383}
4384
Mike Stump11289f42009-09-09 15:08:12 +00004385bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004386 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004387 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4388 unsigned DiagID;
4389 AbstractDiagSelID SelID;
4390
4391 public:
4392 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4393 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004394
Craig Toppera798a9d2014-03-02 09:32:10 +00004395 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004396 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004397 if (SelID == -1)
4398 S.Diag(Loc, DiagID) << T;
4399 else
4400 S.Diag(Loc, DiagID) << SelID << T;
4401 }
4402 } Diagnoser(DiagID, SelID);
4403
4404 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004405}
4406
Anders Carlssoneabf7702009-08-27 00:13:57 +00004407bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004408 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004409 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004410 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004411
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004412 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004413 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004414
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004415 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004416 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004417 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004418 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004419
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004420 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004421 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004422 }
Mike Stump11289f42009-09-09 15:08:12 +00004423
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004424 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004425 if (!RT)
4426 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004427
John McCall67da35c2010-02-04 22:26:26 +00004428 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004429
John McCall02db245d2010-08-18 09:41:07 +00004430 // We can't answer whether something is abstract until it has a
4431 // definition. If it's currently being defined, we'll walk back
4432 // over all the declarations when we have a full definition.
4433 const CXXRecordDecl *Def = RD->getDefinition();
4434 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004435 return false;
4436
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004437 if (!RD->isAbstract())
4438 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004439
Douglas Gregorae298422012-05-04 17:09:59 +00004440 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004441 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004442
John McCall02db245d2010-08-18 09:41:07 +00004443 return true;
4444}
4445
4446void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4447 // Check if we've already emitted the list of pure virtual functions
4448 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004449 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004450 return;
Mike Stump11289f42009-09-09 15:08:12 +00004451
Richard Smithbc46e432013-07-22 02:56:56 +00004452 // If the diagnostic is suppressed, don't emit the notes. We're only
4453 // going to emit them once, so try to attach them to a diagnostic we're
4454 // actually going to show.
4455 if (Diags.isLastDiagnosticIgnored())
4456 return;
4457
Douglas Gregor4165bd62010-03-23 23:47:56 +00004458 CXXFinalOverriderMap FinalOverriders;
4459 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004460
Anders Carlssona2f74f32010-06-03 01:00:02 +00004461 // Keep a set of seen pure methods so we won't diagnose the same method
4462 // more than once.
4463 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4464
Douglas Gregor4165bd62010-03-23 23:47:56 +00004465 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4466 MEnd = FinalOverriders.end();
4467 M != MEnd;
4468 ++M) {
4469 for (OverridingMethods::iterator SO = M->second.begin(),
4470 SOEnd = M->second.end();
4471 SO != SOEnd; ++SO) {
4472 // C++ [class.abstract]p4:
4473 // A class is abstract if it contains or inherits at least one
4474 // pure virtual function for which the final overrider is pure
4475 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004476
Douglas Gregor4165bd62010-03-23 23:47:56 +00004477 //
4478 if (SO->second.size() != 1)
4479 continue;
4480
4481 if (!SO->second.front().Method->isPure())
4482 continue;
4483
David Blaikie82e95a32014-11-19 07:49:47 +00004484 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004485 continue;
4486
Douglas Gregor4165bd62010-03-23 23:47:56 +00004487 Diag(SO->second.front().Method->getLocation(),
4488 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004489 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004490 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004491 }
4492
4493 if (!PureVirtualClassDiagSet)
4494 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4495 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004496}
4497
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004498namespace {
John McCall02db245d2010-08-18 09:41:07 +00004499struct AbstractUsageInfo {
4500 Sema &S;
4501 CXXRecordDecl *Record;
4502 CanQualType AbstractType;
4503 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004504
John McCall02db245d2010-08-18 09:41:07 +00004505 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4506 : S(S), Record(Record),
4507 AbstractType(S.Context.getCanonicalType(
4508 S.Context.getTypeDeclType(Record))),
4509 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004510
John McCall02db245d2010-08-18 09:41:07 +00004511 void DiagnoseAbstractType() {
4512 if (Invalid) return;
4513 S.DiagnoseAbstractType(Record);
4514 Invalid = true;
4515 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004516
John McCall02db245d2010-08-18 09:41:07 +00004517 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4518};
4519
4520struct CheckAbstractUsage {
4521 AbstractUsageInfo &Info;
4522 const NamedDecl *Ctx;
4523
4524 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4525 : Info(Info), Ctx(Ctx) {}
4526
4527 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4528 switch (TL.getTypeLocClass()) {
4529#define ABSTRACT_TYPELOC(CLASS, PARENT)
4530#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004531 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004532#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004533 }
John McCall02db245d2010-08-18 09:41:07 +00004534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535
John McCall02db245d2010-08-18 09:41:07 +00004536 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004537 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004538 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4539 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004540 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004541
4542 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004543 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004544 }
John McCall02db245d2010-08-18 09:41:07 +00004545 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004546
John McCall02db245d2010-08-18 09:41:07 +00004547 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4548 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4549 }
Mike Stump11289f42009-09-09 15:08:12 +00004550
John McCall02db245d2010-08-18 09:41:07 +00004551 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4552 // Visit the type parameters from a permissive context.
4553 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4554 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4555 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4556 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4557 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4558 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004559 }
John McCall02db245d2010-08-18 09:41:07 +00004560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
John McCall02db245d2010-08-18 09:41:07 +00004562 // Visit pointee types from a permissive context.
4563#define CheckPolymorphic(Type) \
4564 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4565 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4566 }
4567 CheckPolymorphic(PointerTypeLoc)
4568 CheckPolymorphic(ReferenceTypeLoc)
4569 CheckPolymorphic(MemberPointerTypeLoc)
4570 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004571 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004572
John McCall02db245d2010-08-18 09:41:07 +00004573 /// Handle all the types we haven't given a more specific
4574 /// implementation for above.
4575 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4576 // Every other kind of type that we haven't called out already
4577 // that has an inner type is either (1) sugar or (2) contains that
4578 // inner type in some way as a subobject.
4579 if (TypeLoc Next = TL.getNextTypeLoc())
4580 return Visit(Next, Sel);
4581
4582 // If there's no inner type and we're in a permissive context,
4583 // don't diagnose.
4584 if (Sel == Sema::AbstractNone) return;
4585
4586 // Check whether the type matches the abstract type.
4587 QualType T = TL.getType();
4588 if (T->isArrayType()) {
4589 Sel = Sema::AbstractArrayType;
4590 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004591 }
John McCall02db245d2010-08-18 09:41:07 +00004592 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4593 if (CT != Info.AbstractType) return;
4594
4595 // It matched; do some magic.
4596 if (Sel == Sema::AbstractArrayType) {
4597 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4598 << T << TL.getSourceRange();
4599 } else {
4600 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4601 << Sel << T << TL.getSourceRange();
4602 }
4603 Info.DiagnoseAbstractType();
4604 }
4605};
4606
4607void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4608 Sema::AbstractDiagSelID Sel) {
4609 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4610}
4611
4612}
4613
4614/// Check for invalid uses of an abstract type in a method declaration.
4615static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4616 CXXMethodDecl *MD) {
4617 // No need to do the check on definitions, which require that
4618 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004619 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004620 return;
4621
4622 // For safety's sake, just ignore it if we don't have type source
4623 // information. This should never happen for non-implicit methods,
4624 // but...
4625 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4626 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4627}
4628
4629/// Check for invalid uses of an abstract type within a class definition.
4630static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4631 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004632 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004633 if (D->isImplicit()) continue;
4634
4635 // Methods and method templates.
4636 if (isa<CXXMethodDecl>(D)) {
4637 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4638 } else if (isa<FunctionTemplateDecl>(D)) {
4639 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4640 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4641
4642 // Fields and static variables.
4643 } else if (isa<FieldDecl>(D)) {
4644 FieldDecl *FD = cast<FieldDecl>(D);
4645 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4646 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4647 } else if (isa<VarDecl>(D)) {
4648 VarDecl *VD = cast<VarDecl>(D);
4649 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4650 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4651
4652 // Nested classes and class templates.
4653 } else if (isa<CXXRecordDecl>(D)) {
4654 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4655 } else if (isa<ClassTemplateDecl>(D)) {
4656 CheckAbstractClassUsage(Info,
4657 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4658 }
4659 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004660}
4661
Hans Wennborg853ae942014-05-30 16:59:42 +00004662/// \brief Check class-level dllimport/dllexport attribute.
4663static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4664 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004665
4666 // MSVC inherits DLL attributes to partial class template specializations.
4667 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4668 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4669 if (Attr *TemplateAttr =
4670 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4671 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4672 A->setInherited(true);
4673 ClassAttr = A;
4674 }
4675 }
4676 }
4677
Hans Wennborg853ae942014-05-30 16:59:42 +00004678 if (!ClassAttr)
4679 return;
4680
Hans Wennborg8313c762014-11-03 16:09:16 +00004681 if (!Class->isExternallyVisible()) {
4682 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4683 << Class << ClassAttr;
4684 return;
4685 }
4686
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004687 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4688 !ClassAttr->isInherited()) {
4689 // Diagnose dll attributes on members of class with dll attribute.
4690 for (Decl *Member : Class->decls()) {
4691 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4692 continue;
4693 InheritableAttr *MemberAttr = getDLLAttr(Member);
4694 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4695 continue;
4696
4697 S.Diag(MemberAttr->getLocation(),
4698 diag::err_attribute_dll_member_of_dll_class)
4699 << MemberAttr << ClassAttr;
4700 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4701 Member->setInvalidDecl();
4702 }
4703 }
4704
4705 if (Class->getDescribedClassTemplate())
4706 // Don't inherit dll attribute until the template is instantiated.
4707 return;
4708
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004709 // The class is either imported or exported.
4710 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4711 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004712
Hans Wennborgfd76d912015-01-15 21:18:30 +00004713 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4714
4715 // Don't dllexport explicit class template instantiation declarations.
4716 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4717 Class->dropAttr<DLLExportAttr>();
4718 return;
4719 }
4720
Hans Wennborg853ae942014-05-30 16:59:42 +00004721 // Force declaration of implicit members so they can inherit the attribute.
4722 S.ForceDeclarationOfImplicitMembers(Class);
4723
4724 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4725 // seem to be true in practice?
4726
Hans Wennborg853ae942014-05-30 16:59:42 +00004727 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004728 VarDecl *VD = dyn_cast<VarDecl>(Member);
4729 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4730
4731 // Only methods and static fields inherit the attributes.
4732 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004733 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004734
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004735 if (MD) {
4736 // Don't process deleted methods.
4737 if (MD->isDeleted())
4738 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004739
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004740 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4741 // Current MSVC versions don't export the move assignment operators, so
4742 // don't attempt to import them if we have a definition.
4743 continue;
4744 }
4745
4746 if (MD->isInlined() && ClassImported &&
4747 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4748 // MinGW does not import inline functions.
4749 continue;
4750 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004751 }
4752
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004753 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004754 auto *NewAttr =
4755 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4756 NewAttr->setInherited(true);
4757 Member->addAttr(NewAttr);
4758 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004759
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004760 if (MD && ClassExported) {
4761 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004762 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004763
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004764 // .. except for certain kinds of template specializations.
4765 if (TSK == TSK_ExplicitInstantiationDeclaration)
4766 continue;
4767 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4768 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004769
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004770 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004771
4772 // The function will be passed to the consumer when its definition is
4773 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004774 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4775 MD->isCopyAssignmentOperator() ||
4776 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004777 // Synthesize and instantiate non-trivial implicit methods, explicitly
4778 // defaulted methods, and the copy and move assignment operators. The
4779 // latter are exported even if they are trivial, because the address of
4780 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004781 S.MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004782
4783 // There is no later point when we will see the definition of this
4784 // function, so pass it to the consumer now.
4785 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004786 }
4787 }
4788 }
4789}
4790
Douglas Gregorc99f1552009-12-03 18:33:45 +00004791/// \brief Perform semantic checks on a class definition that has been
4792/// completing, introducing implicitly-declared members, checking for
4793/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004794void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004795 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004796 return;
4797
John McCall02db245d2010-08-18 09:41:07 +00004798 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4799 AbstractUsageInfo Info(*this, Record);
4800 CheckAbstractClassUsage(Info, Record);
4801 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004802
4803 // If this is not an aggregate type and has no user-declared constructor,
4804 // complain about any non-static data members of reference or const scalar
4805 // type, since they will never get initializers.
4806 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004807 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4808 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004809 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004810 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004811 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004812 continue;
4813
Douglas Gregor454a5b62010-04-15 00:00:53 +00004814 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004815 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004816 if (!Complained) {
4817 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4818 << Record->getTagKind() << Record;
4819 Complained = true;
4820 }
4821
4822 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4823 << F->getType()->isReferenceType()
4824 << F->getDeclName();
4825 }
4826 }
4827 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004828
Anders Carlssone771e762011-01-25 18:08:22 +00004829 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004830 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004831
4832 if (Record->getIdentifier()) {
4833 // C++ [class.mem]p13:
4834 // If T is the name of a class, then each of the following shall have a
4835 // name different from T:
4836 // - every member of every anonymous union that is a member of class T.
4837 //
4838 // C++ [class.mem]p14:
4839 // In addition, if class T has a user-declared constructor (12.1), every
4840 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004841 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4842 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4843 ++I) {
4844 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004845 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4846 isa<IndirectFieldDecl>(D)) {
4847 Diag(D->getLocation(), diag::err_member_name_of_class)
4848 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004849 break;
4850 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004851 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004852 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004853
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004854 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004855 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004856 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004857 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4858 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004859 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4860 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4861 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004862
David Majnemera5433082013-10-18 00:33:31 +00004863 if (Record->isAbstract()) {
4864 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4865 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4866 << FA->isSpelledAsSealed();
4867 DiagnoseAbstractType(Record);
4868 }
David Blaikie348df502012-09-21 03:21:07 +00004869 }
4870
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004871 bool HasMethodWithOverrideControl = false,
4872 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004873 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004874 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004875 // See if a method overloads virtual methods in a base
4876 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004877 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004878 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004879 if (M->hasAttr<OverrideAttr>())
4880 HasMethodWithOverrideControl = true;
4881 else if (M->size_overridden_methods() > 0)
4882 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004883 // Check whether the explicitly-defaulted special members are valid.
4884 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004885 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004886
4887 // For an explicitly defaulted or deleted special member, we defer
4888 // determining triviality until the class is complete. That time is now!
4889 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004890 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004891 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004892 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004893
4894 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004895 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004896 }
4897 }
4898 }
4899 }
4900
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004901 if (HasMethodWithOverrideControl &&
4902 HasOverridingMethodWithoutOverrideControl) {
4903 // At least one method has the 'override' control declared.
4904 // Diagnose all other overridden methods which do not have 'override' specified on them.
4905 for (auto *M : Record->methods())
4906 DiagnoseAbsenceOfOverrideControl(M);
4907 }
Sebastian Redl08905022011-02-05 19:23:19 +00004908
John McCall95833f32014-02-27 20:30:49 +00004909 // ms_struct is a request to use the same ABI rules as MSVC. Check
4910 // whether this class uses any C++ features that are implemented
4911 // completely differently in MSVC, and if so, emit a diagnostic.
4912 // That diagnostic defaults to an error, but we allow projects to
4913 // map it down to a warning (or ignore it). It's a fairly common
4914 // practice among users of the ms_struct pragma to mass-annotate
4915 // headers, sweeping up a bunch of types that the project doesn't
4916 // really rely on MSVC-compatible layout for. We must therefore
4917 // support "ms_struct except for C++ stuff" as a secondary ABI.
4918 if (Record->isMsStruct(Context) &&
4919 (Record->isPolymorphic() || Record->getNumBases())) {
4920 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004921 }
4922
Richard Smithc2bc61b2013-03-18 21:12:30 +00004923 // Declare inheriting constructors. We do this eagerly here because:
4924 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004925 // constructors from different classes.
4926 // - The lazy declaration of the other implicit constructors is so as to not
4927 // waste space and performance on classes that are not meant to be
4928 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004929 // have inheriting constructors.
4930 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004931
4932 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004933}
4934
Richard Smith41c35d62013-11-27 03:39:20 +00004935/// Look up the special member function that would be called by a special
4936/// member function for a subobject of class type.
4937///
4938/// \param Class The class type of the subobject.
4939/// \param CSM The kind of special member function.
4940/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4941/// \param ConstRHS True if this is a copy operation with a const object
4942/// on its RHS, that is, if the argument to the outer special member
4943/// function is 'const' and this is not a field marked 'mutable'.
4944static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4945 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4946 unsigned FieldQuals, bool ConstRHS) {
4947 unsigned LHSQuals = 0;
4948 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4949 LHSQuals = FieldQuals;
4950
4951 unsigned RHSQuals = FieldQuals;
4952 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4953 RHSQuals = 0;
4954 else if (ConstRHS)
4955 RHSQuals |= Qualifiers::Const;
4956
4957 return S.LookupSpecialMember(Class, CSM,
4958 RHSQuals & Qualifiers::Const,
4959 RHSQuals & Qualifiers::Volatile,
4960 false,
4961 LHSQuals & Qualifiers::Const,
4962 LHSQuals & Qualifiers::Volatile);
4963}
4964
Richard Smithb5800092012-06-10 05:43:50 +00004965/// Is the special member function which would be selected to perform the
4966/// specified operation on the specified class type a constexpr constructor?
4967static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4968 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004969 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004970 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004971 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004972 if (!SMOR || !SMOR->getMethod())
4973 // A constructor we wouldn't select can't be "involved in initializing"
4974 // anything.
4975 return true;
4976 return SMOR->getMethod()->isConstexpr();
4977}
4978
4979/// Determine whether the specified special member function would be constexpr
4980/// if it were implicitly defined.
4981static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4982 Sema::CXXSpecialMember CSM,
4983 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004984 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004985 return false;
4986
4987 // C++11 [dcl.constexpr]p4:
4988 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004989 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004990 switch (CSM) {
4991 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004992 // Since default constructor lookup is essentially trivial (and cannot
4993 // involve, for instance, template instantiation), we compute whether a
4994 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4995 //
4996 // This is important for performance; we need to know whether the default
4997 // constructor is constexpr to determine whether the type is a literal type.
4998 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4999
Richard Smithb5800092012-06-10 05:43:50 +00005000 case Sema::CXXCopyConstructor:
5001 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005002 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005003 break;
5004
5005 case Sema::CXXCopyAssignment:
5006 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005007 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005008 return false;
5009 // In C++1y, we need to perform overload resolution.
5010 Ctor = false;
5011 break;
5012
Richard Smithb5800092012-06-10 05:43:50 +00005013 case Sema::CXXDestructor:
5014 case Sema::CXXInvalid:
5015 return false;
5016 }
5017
5018 // -- if the class is a non-empty union, or for each non-empty anonymous
5019 // union member of a non-union class, exactly one non-static data member
5020 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005021 //
5022 // If we squint, this is guaranteed, since exactly one non-static data member
5023 // will be initialized (if the constructor isn't deleted), we just don't know
5024 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005025 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005026 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005027
5028 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005029 if (Ctor && ClassDecl->getNumVBases())
5030 return false;
5031
5032 // C++1y [class.copy]p26:
5033 // -- [the class] is a literal type, and
5034 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005035 return false;
5036
5037 // -- every constructor involved in initializing [...] base class
5038 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005039 // -- the assignment operator selected to copy/move each direct base
5040 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005041 for (const auto &B : ClassDecl->bases()) {
5042 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005043 if (!BaseType) continue;
5044
5045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005046 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005047 return false;
5048 }
5049
5050 // -- every constructor involved in initializing non-static data members
5051 // [...] shall be a constexpr constructor;
5052 // -- every non-static data member and base class sub-object shall be
5053 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005054 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005055 // thereof), the assignment operator selected to copy/move that member is
5056 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005057 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005058 if (F->isInvalidDecl())
5059 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005060 QualType BaseType = S.Context.getBaseElementType(F->getType());
5061 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005062 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005063 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5064 BaseType.getCVRQualifiers(),
5065 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005066 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005067 }
5068 }
5069
5070 // All OK, it's constexpr!
5071 return true;
5072}
5073
Richard Smithd3b5c9082012-07-27 04:22:15 +00005074static Sema::ImplicitExceptionSpecification
5075computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5076 switch (S.getSpecialMember(MD)) {
5077 case Sema::CXXDefaultConstructor:
5078 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5079 case Sema::CXXCopyConstructor:
5080 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5081 case Sema::CXXCopyAssignment:
5082 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5083 case Sema::CXXMoveConstructor:
5084 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5085 case Sema::CXXMoveAssignment:
5086 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5087 case Sema::CXXDestructor:
5088 return S.ComputeDefaultedDtorExceptionSpec(MD);
5089 case Sema::CXXInvalid:
5090 break;
5091 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005092 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5093 "only special members have implicit exception specs");
5094 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005095}
5096
Reid Kleckner78af0702013-08-27 23:08:25 +00005097static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5098 CXXMethodDecl *MD) {
5099 FunctionProtoType::ExtProtoInfo EPI;
5100
5101 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005102 EPI.ExceptionSpec.Type = EST_Unevaluated;
5103 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005104
5105 // Set the calling convention to the default for C++ instance methods.
5106 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5107 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5108 /*IsCXXMethod=*/true));
5109 return EPI;
5110}
5111
Richard Smithd3b5c9082012-07-27 04:22:15 +00005112void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5113 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5114 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5115 return;
5116
Richard Smith7f782272012-07-30 23:48:14 +00005117 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005118 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005119
Richard Smith7f782272012-07-30 23:48:14 +00005120 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005121 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005122
5123 // A user-provided destructor can be defined outside the class. When that
5124 // happens, be sure to update the exception specification on both
5125 // declarations.
5126 const FunctionProtoType *CanonicalFPT =
5127 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5128 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005129 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005130}
5131
Richard Smithb9e90b12012-05-15 04:39:51 +00005132void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5133 CXXRecordDecl *RD = MD->getParent();
5134 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005135
Richard Smithb9e90b12012-05-15 04:39:51 +00005136 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5137 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005138
5139 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005140 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005141 bool First = MD == MD->getCanonicalDecl();
5142
5143 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005144
5145 // C++11 [dcl.fct.def.default]p1:
5146 // A function that is explicitly defaulted shall
5147 // -- be a special member function (checked elsewhere),
5148 // -- have the same type (except for ref-qualifiers, and except that a
5149 // copy operation can take a non-const reference) as an implicit
5150 // declaration, and
5151 // -- not have default arguments.
5152 unsigned ExpectedParams = 1;
5153 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5154 ExpectedParams = 0;
5155 if (MD->getNumParams() != ExpectedParams) {
5156 // This also checks for default arguments: a copy or move constructor with a
5157 // default argument is classified as a default constructor, and assignment
5158 // operations and destructors can't have default arguments.
5159 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5160 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005161 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005162 } else if (MD->isVariadic()) {
5163 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5164 << CSM << MD->getSourceRange();
5165 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005166 }
5167
Richard Smithb9e90b12012-05-15 04:39:51 +00005168 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005169
Richard Smithb5800092012-06-10 05:43:50 +00005170 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005171 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005172 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005173 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005174 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005175
Richard Smithb9e90b12012-05-15 04:39:51 +00005176 QualType ReturnType = Context.VoidTy;
5177 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5178 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005179 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005180 QualType ExpectedReturnType =
5181 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5182 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5183 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5184 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5185 HadError = true;
5186 }
5187
5188 // A defaulted special member cannot have cv-qualifiers.
5189 if (Type->getTypeQuals()) {
5190 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005191 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005192 HadError = true;
5193 }
5194 }
5195
5196 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005197 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005198 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005199 if (ExpectedParams && ArgType->isReferenceType()) {
5200 // Argument must be reference to possibly-const T.
5201 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005202 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005203
5204 if (ReferentType.isVolatileQualified()) {
5205 Diag(MD->getLocation(),
5206 diag::err_defaulted_special_member_volatile_param) << CSM;
5207 HadError = true;
5208 }
5209
Richard Smithb5800092012-06-10 05:43:50 +00005210 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005211 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5212 Diag(MD->getLocation(),
5213 diag::err_defaulted_special_member_copy_const_param)
5214 << (CSM == CXXCopyAssignment);
5215 // FIXME: Explain why this special member can't be const.
5216 } else {
5217 Diag(MD->getLocation(),
5218 diag::err_defaulted_special_member_move_const_param)
5219 << (CSM == CXXMoveAssignment);
5220 }
5221 HadError = true;
5222 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005223 } else if (ExpectedParams) {
5224 // A copy assignment operator can take its argument by value, but a
5225 // defaulted one cannot.
5226 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005227 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005228 HadError = true;
5229 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005230
Richard Smithcc36f692011-12-22 02:22:31 +00005231 // C++11 [dcl.fct.def.default]p2:
5232 // An explicitly-defaulted function may be declared constexpr only if it
5233 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005234 // Do not apply this rule to members of class templates, since core issue 1358
5235 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005236 // functions which cannot be constexpr (for non-constructors in C++11 and for
5237 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005238 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5239 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005240 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005241 : isa<CXXConstructorDecl>(MD)) &&
5242 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005243 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5244 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005245 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005246 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005247 }
Richard Smithbd305122012-12-11 01:14:52 +00005248
Richard Smithcc36f692011-12-22 02:22:31 +00005249 // and may have an explicit exception-specification only if it is compatible
5250 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005251 if (Type->hasExceptionSpec()) {
5252 // Delay the check if this is the first declaration of the special member,
5253 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005254 if (First) {
5255 // If the exception specification needs to be instantiated, do so now,
5256 // before we clobber it with an EST_Unevaluated specification below.
5257 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5258 InstantiateExceptionSpec(MD->getLocStart(), MD);
5259 Type = MD->getType()->getAs<FunctionProtoType>();
5260 }
Richard Smithbd305122012-12-11 01:14:52 +00005261 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005262 } else
Richard Smithbd305122012-12-11 01:14:52 +00005263 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5264 }
Richard Smithcc36f692011-12-22 02:22:31 +00005265
5266 // If a function is explicitly defaulted on its first declaration,
5267 if (First) {
5268 // -- it is implicitly considered to be constexpr if the implicit
5269 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005270 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005271
Richard Smithb9e90b12012-05-15 04:39:51 +00005272 // -- it is implicitly considered to have the same exception-specification
5273 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005274 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005275 EPI.ExceptionSpec.Type = EST_Unevaluated;
5276 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005277 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005278 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005279 ExpectedParams),
5280 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005281 }
5282
Richard Smithb9e90b12012-05-15 04:39:51 +00005283 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005284 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005285 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005286 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005287 // C++11 [dcl.fct.def.default]p4:
5288 // [For a] user-provided explicitly-defaulted function [...] if such a
5289 // function is implicitly defined as deleted, the program is ill-formed.
5290 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005291 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005292 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005293 }
5294 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005295
Richard Smithb9e90b12012-05-15 04:39:51 +00005296 if (HadError)
5297 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005298}
5299
Richard Smithbd305122012-12-11 01:14:52 +00005300/// Check whether the exception specification provided for an
5301/// explicitly-defaulted special member matches the exception specification
5302/// that would have been generated for an implicit special member, per
5303/// C++11 [dcl.fct.def.default]p2.
5304void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5305 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005306 // If the exception specification was explicitly specified but hadn't been
5307 // parsed when the method was defaulted, grab it now.
5308 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5309 SpecifiedType =
5310 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5311
Richard Smithbd305122012-12-11 01:14:52 +00005312 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005313 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5314 /*IsCXXMethod=*/true);
5315 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005316 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5317 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005318 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005319 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005320
5321 // Ensure that it matches.
5322 CheckEquivalentExceptionSpec(
5323 PDiag(diag::err_incorrect_defaulted_exception_spec)
5324 << getSpecialMember(MD), PDiag(),
5325 ImplicitType, SourceLocation(),
5326 SpecifiedType, MD->getLocation());
5327}
5328
Alp Tokerae3a9442013-10-18 05:54:19 +00005329void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005330 decltype(DelayedExceptionSpecChecks) Checks;
5331 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005332
Richard Smith88f45492014-11-22 03:09:05 +00005333 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005334 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5335
5336 // Perform any deferred checking of exception specifications for virtual
5337 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005338 for (auto &Check : Checks)
5339 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005340
5341 // Check that any explicitly-defaulted methods have exception specifications
5342 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005343 for (auto &Spec : Specs)
5344 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005345}
5346
Richard Smithd951a1d2012-02-18 02:02:13 +00005347namespace {
5348struct SpecialMemberDeletionInfo {
5349 Sema &S;
5350 CXXMethodDecl *MD;
5351 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005352 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005353
5354 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005355 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005356 SourceLocation Loc;
5357
5358 bool AllFieldsAreConst;
5359
5360 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005361 Sema::CXXSpecialMember CSM, bool Diagnose)
5362 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005363 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005364 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005365 AllFieldsAreConst(true) {
5366 switch (CSM) {
5367 case Sema::CXXDefaultConstructor:
5368 case Sema::CXXCopyConstructor:
5369 IsConstructor = true;
5370 break;
5371 case Sema::CXXMoveConstructor:
5372 IsConstructor = true;
5373 IsMove = true;
5374 break;
5375 case Sema::CXXCopyAssignment:
5376 IsAssignment = true;
5377 break;
5378 case Sema::CXXMoveAssignment:
5379 IsAssignment = true;
5380 IsMove = true;
5381 break;
5382 case Sema::CXXDestructor:
5383 break;
5384 case Sema::CXXInvalid:
5385 llvm_unreachable("invalid special member kind");
5386 }
5387
5388 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005389 if (const ReferenceType *RT =
5390 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5391 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005392 }
5393 }
5394
5395 bool inUnion() const { return MD->getParent()->isUnion(); }
5396
5397 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005398 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005399 unsigned Quals, bool IsMutable) {
5400 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5401 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005402 }
5403
Richard Smith852265f2012-03-30 20:53:28 +00005404 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005405
Richard Smith852265f2012-03-30 20:53:28 +00005406 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005407 bool shouldDeleteForField(FieldDecl *FD);
5408 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005409
Richard Smithaf136f82012-07-18 03:51:16 +00005410 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5411 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005412 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5413 Sema::SpecialMemberOverloadResult *SMOR,
5414 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005415
5416 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005417};
5418}
5419
John McCalld4274212012-04-09 20:53:23 +00005420/// Is the given special member inaccessible when used on the given
5421/// sub-object.
5422bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5423 CXXMethodDecl *target) {
5424 /// If we're operating on a base class, the object type is the
5425 /// type of this special member.
5426 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005427 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005428 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5429 objectTy = S.Context.getTypeDeclType(MD->getParent());
5430 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5431
5432 // If we're operating on a field, the object type is the type of the field.
5433 } else {
5434 objectTy = S.Context.getTypeDeclType(target->getParent());
5435 }
5436
5437 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5438}
5439
Richard Smith852265f2012-03-30 20:53:28 +00005440/// Check whether we should delete a special member due to the implicit
5441/// definition containing a call to a special member of a subobject.
5442bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5443 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5444 bool IsDtorCallInCtor) {
5445 CXXMethodDecl *Decl = SMOR->getMethod();
5446 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5447
5448 int DiagKind = -1;
5449
5450 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5451 DiagKind = !Decl ? 0 : 1;
5452 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5453 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005454 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005455 DiagKind = 3;
5456 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5457 !Decl->isTrivial()) {
5458 // A member of a union must have a trivial corresponding special member.
5459 // As a weird special case, a destructor call from a union's constructor
5460 // must be accessible and non-deleted, but need not be trivial. Such a
5461 // destructor is never actually called, but is semantically checked as
5462 // if it were.
5463 DiagKind = 4;
5464 }
5465
5466 if (DiagKind == -1)
5467 return false;
5468
5469 if (Diagnose) {
5470 if (Field) {
5471 S.Diag(Field->getLocation(),
5472 diag::note_deleted_special_member_class_subobject)
5473 << CSM << MD->getParent() << /*IsField*/true
5474 << Field << DiagKind << IsDtorCallInCtor;
5475 } else {
5476 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5477 S.Diag(Base->getLocStart(),
5478 diag::note_deleted_special_member_class_subobject)
5479 << CSM << MD->getParent() << /*IsField*/false
5480 << Base->getType() << DiagKind << IsDtorCallInCtor;
5481 }
5482
5483 if (DiagKind == 1)
5484 S.NoteDeletedFunction(Decl);
5485 // FIXME: Explain inaccessibility if DiagKind == 3.
5486 }
5487
5488 return true;
5489}
5490
Richard Smith921bd202012-02-26 09:11:52 +00005491/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005492/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005493bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005494 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005495 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005496 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005497
5498 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005499 // -- any direct or virtual base class, or non-static data member with no
5500 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005501 // either M has no default constructor or overload resolution as applied
5502 // to M's default constructor results in an ambiguity or in a function
5503 // that is deleted or inaccessible
5504 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5505 // -- a direct or virtual base class B that cannot be copied/moved because
5506 // overload resolution, as applied to B's corresponding special member,
5507 // results in an ambiguity or a function that is deleted or inaccessible
5508 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005509 // C++11 [class.dtor]p5:
5510 // -- any direct or virtual base class [...] has a type with a destructor
5511 // that is deleted or inaccessible
5512 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005513 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005514 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5515 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005516 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005517
Richard Smith852265f2012-03-30 20:53:28 +00005518 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5519 // -- any direct or virtual base class or non-static data member has a
5520 // type with a destructor that is deleted or inaccessible
5521 if (IsConstructor) {
5522 Sema::SpecialMemberOverloadResult *SMOR =
5523 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5524 false, false, false, false, false);
5525 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5526 return true;
5527 }
5528
Richard Smith921bd202012-02-26 09:11:52 +00005529 return false;
5530}
5531
5532/// Check whether we should delete a special member function due to the class
5533/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005534bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005535 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005536 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005537}
5538
5539/// Check whether we should delete a special member function due to the class
5540/// having a particular non-static data member.
5541bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5542 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5543 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5544
5545 if (CSM == Sema::CXXDefaultConstructor) {
5546 // For a default constructor, all references must be initialized in-class
5547 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005548 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5549 if (Diagnose)
5550 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5551 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005552 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005553 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005554 // C++11 [class.ctor]p5: any non-variant non-static data member of
5555 // const-qualified type (or array thereof) with no
5556 // brace-or-equal-initializer does not have a user-provided default
5557 // constructor.
5558 if (!inUnion() && FieldType.isConstQualified() &&
5559 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005560 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5561 if (Diagnose)
5562 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005563 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005564 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005565 }
5566
5567 if (inUnion() && !FieldType.isConstQualified())
5568 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005569 } else if (CSM == Sema::CXXCopyConstructor) {
5570 // For a copy constructor, data members must not be of rvalue reference
5571 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005572 if (FieldType->isRValueReferenceType()) {
5573 if (Diagnose)
5574 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5575 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005576 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005577 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005578 } else if (IsAssignment) {
5579 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005580 if (FieldType->isReferenceType()) {
5581 if (Diagnose)
5582 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5583 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005584 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005585 }
5586 if (!FieldRecord && FieldType.isConstQualified()) {
5587 // C++11 [class.copy]p23:
5588 // -- a non-static data member of const non-class type (or array thereof)
5589 if (Diagnose)
5590 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005591 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005592 return true;
5593 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005594 }
5595
5596 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005597 // Some additional restrictions exist on the variant members.
5598 if (!inUnion() && FieldRecord->isUnion() &&
5599 FieldRecord->isAnonymousStructOrUnion()) {
5600 bool AllVariantFieldsAreConst = true;
5601
Richard Smith5704fe82012-03-29 19:00:10 +00005602 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005603 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005604 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005605
5606 if (!UnionFieldType.isConstQualified())
5607 AllVariantFieldsAreConst = false;
5608
Richard Smith921bd202012-02-26 09:11:52 +00005609 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5610 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005611 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005612 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005613 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005614 }
5615
5616 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005617 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005618 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005619 if (Diagnose)
5620 S.Diag(FieldRecord->getLocation(),
5621 diag::note_deleted_default_ctor_all_const)
5622 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005623 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005624 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005625
Richard Smith5704fe82012-03-29 19:00:10 +00005626 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005627 // This is technically non-conformant, but sanity demands it.
5628 return false;
5629 }
5630
Richard Smithaf136f82012-07-18 03:51:16 +00005631 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5632 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005633 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005634 }
5635
5636 return false;
5637}
5638
5639/// C++11 [class.ctor] p5:
5640/// A defaulted default constructor for a class X is defined as deleted if
5641/// X is a union and all of its variant members are of const-qualified type.
5642bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005643 // This is a silly definition, because it gives an empty union a deleted
5644 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005645 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005646 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005647 if (Diagnose)
5648 S.Diag(MD->getParent()->getLocation(),
5649 diag::note_deleted_default_ctor_all_const)
5650 << MD->getParent() << /*not anonymous union*/0;
5651 return true;
5652 }
5653 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005654}
5655
5656/// Determine whether a defaulted special member function should be defined as
5657/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5658/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005659bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5660 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005661 if (MD->isInvalidDecl())
5662 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005663 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005664 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005665 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005666 return false;
5667
Richard Smithd951a1d2012-02-18 02:02:13 +00005668 // C++11 [expr.lambda.prim]p19:
5669 // The closure type associated with a lambda-expression has a
5670 // deleted (8.4.3) default constructor and a deleted copy
5671 // assignment operator.
5672 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005673 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5674 if (Diagnose)
5675 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005676 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005677 }
5678
Richard Smith6f1e2c62012-04-02 20:59:25 +00005679 // For an anonymous struct or union, the copy and assignment special members
5680 // will never be used, so skip the check. For an anonymous union declared at
5681 // namespace scope, the constructor and destructor are used.
5682 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5683 RD->isAnonymousStructOrUnion())
5684 return false;
5685
Richard Smith852265f2012-03-30 20:53:28 +00005686 // C++11 [class.copy]p7, p18:
5687 // If the class definition declares a move constructor or move assignment
5688 // operator, an implicitly declared copy constructor or copy assignment
5689 // operator is defined as deleted.
5690 if (MD->isImplicit() &&
5691 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005692 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005693
5694 // In Microsoft mode, a user-declared move only causes the deletion of the
5695 // corresponding copy operation, not both copy operations.
5696 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005697 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005698 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005699
5700 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005701 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005702 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005703 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005704 break;
5705 }
5706 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005707 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005708 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005709 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005710 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005711
5712 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005713 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005714 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005715 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005716 break;
5717 }
5718 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005719 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005720 }
5721
5722 if (UserDeclaredMove) {
5723 Diag(UserDeclaredMove->getLocation(),
5724 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005725 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005726 << UserDeclaredMove->isMoveAssignmentOperator();
5727 return true;
5728 }
5729 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005730
Richard Smith6f1e2c62012-04-02 20:59:25 +00005731 // Do access control from the special member function
5732 ContextRAII MethodContext(*this, MD);
5733
Richard Smith921bd202012-02-26 09:11:52 +00005734 // C++11 [class.dtor]p5:
5735 // -- for a virtual destructor, lookup of the non-array deallocation function
5736 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005737 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005738 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005739 DeclarationName Name =
5740 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5741 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005742 OperatorDelete, false)) {
5743 if (Diagnose)
5744 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005745 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005746 }
Richard Smith921bd202012-02-26 09:11:52 +00005747 }
5748
Richard Smith852265f2012-03-30 20:53:28 +00005749 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005750
Aaron Ballman574705e2014-03-13 15:41:46 +00005751 for (auto &BI : RD->bases())
5752 if (!BI.isVirtual() &&
5753 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005754 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005755
Richard Smithd1627032013-07-22 18:06:23 +00005756 // Per DR1611, do not consider virtual bases of constructors of abstract
5757 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005758 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005759 for (auto &BI : RD->vbases())
5760 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005761 return true;
5762 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005763
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005764 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005765 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005766 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005767 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005768
Richard Smithd951a1d2012-02-18 02:02:13 +00005769 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005770 return true;
5771
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005772 if (getLangOpts().CUDA) {
5773 // We should delete the special member in CUDA mode if target inference
5774 // failed.
5775 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5776 Diagnose);
5777 }
5778
Alexis Huntea6f0322011-05-11 22:34:38 +00005779 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005780}
5781
Richard Smith92f241f2012-12-08 02:53:02 +00005782/// Perform lookup for a special member of the specified kind, and determine
5783/// whether it is trivial. If the triviality can be determined without the
5784/// lookup, skip it. This is intended for use when determining whether a
5785/// special member of a containing object is trivial, and thus does not ever
5786/// perform overload resolution for default constructors.
5787///
5788/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5789/// member that was most likely to be intended to be trivial, if any.
5790static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5791 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005792 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005793 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005794 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005795
5796 switch (CSM) {
5797 case Sema::CXXInvalid:
5798 llvm_unreachable("not a special member");
5799
5800 case Sema::CXXDefaultConstructor:
5801 // C++11 [class.ctor]p5:
5802 // A default constructor is trivial if:
5803 // - all the [direct subobjects] have trivial default constructors
5804 //
5805 // Note, no overload resolution is performed in this case.
5806 if (RD->hasTrivialDefaultConstructor())
5807 return true;
5808
5809 if (Selected) {
5810 // If there's a default constructor which could have been trivial, dig it
5811 // out. Otherwise, if there's any user-provided default constructor, point
5812 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005813 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005814 if (RD->needsImplicitDefaultConstructor())
5815 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005816 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005817 if (!CI->isDefaultConstructor())
5818 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005819 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005820 if (!DefCtor->isUserProvided())
5821 break;
5822 }
5823
5824 *Selected = DefCtor;
5825 }
5826
5827 return false;
5828
5829 case Sema::CXXDestructor:
5830 // C++11 [class.dtor]p5:
5831 // A destructor is trivial if:
5832 // - all the direct [subobjects] have trivial destructors
5833 if (RD->hasTrivialDestructor())
5834 return true;
5835
5836 if (Selected) {
5837 if (RD->needsImplicitDestructor())
5838 S.DeclareImplicitDestructor(RD);
5839 *Selected = RD->getDestructor();
5840 }
5841
5842 return false;
5843
5844 case Sema::CXXCopyConstructor:
5845 // C++11 [class.copy]p12:
5846 // A copy constructor is trivial if:
5847 // - the constructor selected to copy each direct [subobject] is trivial
5848 if (RD->hasTrivialCopyConstructor()) {
5849 if (Quals == Qualifiers::Const)
5850 // We must either select the trivial copy constructor or reach an
5851 // ambiguity; no need to actually perform overload resolution.
5852 return true;
5853 } else if (!Selected) {
5854 return false;
5855 }
5856 // In C++98, we are not supposed to perform overload resolution here, but we
5857 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5858 // cases like B as having a non-trivial copy constructor:
5859 // struct A { template<typename T> A(T&); };
5860 // struct B { mutable A a; };
5861 goto NeedOverloadResolution;
5862
5863 case Sema::CXXCopyAssignment:
5864 // C++11 [class.copy]p25:
5865 // A copy assignment operator is trivial if:
5866 // - the assignment operator selected to copy each direct [subobject] is
5867 // trivial
5868 if (RD->hasTrivialCopyAssignment()) {
5869 if (Quals == Qualifiers::Const)
5870 return true;
5871 } else if (!Selected) {
5872 return false;
5873 }
5874 // In C++98, we are not supposed to perform overload resolution here, but we
5875 // treat that as a language defect.
5876 goto NeedOverloadResolution;
5877
5878 case Sema::CXXMoveConstructor:
5879 case Sema::CXXMoveAssignment:
5880 NeedOverloadResolution:
5881 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005882 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005883
5884 // The standard doesn't describe how to behave if the lookup is ambiguous.
5885 // We treat it as not making the member non-trivial, just like the standard
5886 // mandates for the default constructor. This should rarely matter, because
5887 // the member will also be deleted.
5888 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5889 return true;
5890
5891 if (!SMOR->getMethod()) {
5892 assert(SMOR->getKind() ==
5893 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5894 return false;
5895 }
5896
5897 // We deliberately don't check if we found a deleted special member. We're
5898 // not supposed to!
5899 if (Selected)
5900 *Selected = SMOR->getMethod();
5901 return SMOR->getMethod()->isTrivial();
5902 }
5903
5904 llvm_unreachable("unknown special method kind");
5905}
5906
Benjamin Kramer3e350262013-02-15 12:30:38 +00005907static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005908 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005909 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005910 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005911
5912 // Look for constructor templates.
5913 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5914 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5915 if (CXXConstructorDecl *CD =
5916 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5917 return CD;
5918 }
5919
Craig Topperc3ec1492014-05-26 06:22:03 +00005920 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005921}
5922
5923/// The kind of subobject we are checking for triviality. The values of this
5924/// enumeration are used in diagnostics.
5925enum TrivialSubobjectKind {
5926 /// The subobject is a base class.
5927 TSK_BaseClass,
5928 /// The subobject is a non-static data member.
5929 TSK_Field,
5930 /// The object is actually the complete object.
5931 TSK_CompleteObject
5932};
5933
5934/// Check whether the special member selected for a given type would be trivial.
5935static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005936 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005937 Sema::CXXSpecialMember CSM,
5938 TrivialSubobjectKind Kind,
5939 bool Diagnose) {
5940 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5941 if (!SubRD)
5942 return true;
5943
5944 CXXMethodDecl *Selected;
5945 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005946 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005947 return true;
5948
5949 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005950 if (ConstRHS)
5951 SubType.addConst();
5952
Richard Smith92f241f2012-12-08 02:53:02 +00005953 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5954 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5955 << Kind << SubType.getUnqualifiedType();
5956 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5957 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5958 } else if (!Selected)
5959 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5960 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5961 else if (Selected->isUserProvided()) {
5962 if (Kind == TSK_CompleteObject)
5963 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5964 << Kind << SubType.getUnqualifiedType() << CSM;
5965 else {
5966 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5967 << Kind << SubType.getUnqualifiedType() << CSM;
5968 S.Diag(Selected->getLocation(), diag::note_declared_at);
5969 }
5970 } else {
5971 if (Kind != TSK_CompleteObject)
5972 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5973 << Kind << SubType.getUnqualifiedType() << CSM;
5974
5975 // Explain why the defaulted or deleted special member isn't trivial.
5976 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5977 }
5978 }
5979
5980 return false;
5981}
5982
5983/// Check whether the members of a class type allow a special member to be
5984/// trivial.
5985static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5986 Sema::CXXSpecialMember CSM,
5987 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005988 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005989 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5990 continue;
5991
5992 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5993
5994 // Pretend anonymous struct or union members are members of this class.
5995 if (FI->isAnonymousStructOrUnion()) {
5996 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5997 CSM, ConstArg, Diagnose))
5998 return false;
5999 continue;
6000 }
6001
6002 // C++11 [class.ctor]p5:
6003 // A default constructor is trivial if [...]
6004 // -- no non-static data member of its class has a
6005 // brace-or-equal-initializer
6006 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6007 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006008 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006009 return false;
6010 }
6011
6012 // Objective C ARC 4.3.5:
6013 // [...] nontrivally ownership-qualified types are [...] not trivially
6014 // default constructible, copy constructible, move constructible, copy
6015 // assignable, move assignable, or destructible [...]
6016 if (S.getLangOpts().ObjCAutoRefCount &&
6017 FieldType.hasNonTrivialObjCLifetime()) {
6018 if (Diagnose)
6019 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6020 << RD << FieldType.getObjCLifetime();
6021 return false;
6022 }
6023
Richard Smith41c35d62013-11-27 03:39:20 +00006024 bool ConstRHS = ConstArg && !FI->isMutable();
6025 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6026 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006027 return false;
6028 }
6029
6030 return true;
6031}
6032
6033/// Diagnose why the specified class does not have a trivial special member of
6034/// the given kind.
6035void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6036 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006037
Richard Smith41c35d62013-11-27 03:39:20 +00006038 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6039 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006040 TSK_CompleteObject, /*Diagnose*/true);
6041}
6042
6043/// Determine whether a defaulted or deleted special member function is trivial,
6044/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6045/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6046bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6047 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006048 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6049
6050 CXXRecordDecl *RD = MD->getParent();
6051
6052 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006053
Richard Smith2002bfe2013-11-04 02:02:27 +00006054 // C++11 [class.copy]p12, p25: [DR1593]
6055 // A [special member] is trivial if [...] its parameter-type-list is
6056 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006057 switch (CSM) {
6058 case CXXDefaultConstructor:
6059 case CXXDestructor:
6060 // Trivial default constructors and destructors cannot have parameters.
6061 break;
6062
6063 case CXXCopyConstructor:
6064 case CXXCopyAssignment: {
6065 // Trivial copy operations always have const, non-volatile parameter types.
6066 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006067 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006068 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6069 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6070 if (Diagnose)
6071 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6072 << Param0->getSourceRange() << Param0->getType()
6073 << Context.getLValueReferenceType(
6074 Context.getRecordType(RD).withConst());
6075 return false;
6076 }
6077 break;
6078 }
6079
6080 case CXXMoveConstructor:
6081 case CXXMoveAssignment: {
6082 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006083 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006084 const RValueReferenceType *RT =
6085 Param0->getType()->getAs<RValueReferenceType>();
6086 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6087 if (Diagnose)
6088 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6089 << Param0->getSourceRange() << Param0->getType()
6090 << Context.getRValueReferenceType(Context.getRecordType(RD));
6091 return false;
6092 }
6093 break;
6094 }
6095
6096 case CXXInvalid:
6097 llvm_unreachable("not a special member");
6098 }
6099
Richard Smith92f241f2012-12-08 02:53:02 +00006100 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6101 if (Diagnose)
6102 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6103 diag::note_nontrivial_default_arg)
6104 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6105 return false;
6106 }
6107 if (MD->isVariadic()) {
6108 if (Diagnose)
6109 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6110 return false;
6111 }
6112
6113 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6114 // A copy/move [constructor or assignment operator] is trivial if
6115 // -- the [member] selected to copy/move each direct base class subobject
6116 // is trivial
6117 //
6118 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6119 // A [default constructor or destructor] is trivial if
6120 // -- all the direct base classes have trivial [default constructors or
6121 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006122 for (const auto &BI : RD->bases())
6123 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006124 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006125 return false;
6126
6127 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6128 // A copy/move [constructor or assignment operator] for a class X is
6129 // trivial if
6130 // -- for each non-static data member of X that is of class type (or array
6131 // thereof), the constructor selected to copy/move that member is
6132 // trivial
6133 //
6134 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6135 // A [default constructor or destructor] is trivial if
6136 // -- for all of the non-static data members of its class that are of class
6137 // type (or array thereof), each such class has a trivial [default
6138 // constructor or destructor]
6139 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6140 return false;
6141
6142 // C++11 [class.dtor]p5:
6143 // A destructor is trivial if [...]
6144 // -- the destructor is not virtual
6145 if (CSM == CXXDestructor && MD->isVirtual()) {
6146 if (Diagnose)
6147 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6148 return false;
6149 }
6150
6151 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6152 // A [special member] for class X is trivial if [...]
6153 // -- class X has no virtual functions and no virtual base classes
6154 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6155 if (!Diagnose)
6156 return false;
6157
6158 if (RD->getNumVBases()) {
6159 // Check for virtual bases. We already know that the corresponding
6160 // member in all bases is trivial, so vbases must all be direct.
6161 CXXBaseSpecifier &BS = *RD->vbases_begin();
6162 assert(BS.isVirtual());
6163 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6164 return false;
6165 }
6166
6167 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006168 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006169 if (MI->isVirtual()) {
6170 SourceLocation MLoc = MI->getLocStart();
6171 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6172 return false;
6173 }
6174 }
6175
6176 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6177 }
6178
6179 // Looks like it's trivial!
6180 return true;
6181}
6182
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006183/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006184namespace {
6185 struct FindHiddenVirtualMethodData {
6186 Sema *S;
6187 CXXMethodDecl *Method;
6188 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006189 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006190 };
6191}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006192
David Blaikie282c92a2012-10-19 00:53:08 +00006193/// \brief Check whether any most overriden method from MD in Methods
6194static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006195 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006196 if (MD->size_overridden_methods() == 0)
6197 return Methods.count(MD->getCanonicalDecl());
6198 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6199 E = MD->end_overridden_methods();
6200 I != E; ++I)
6201 if (CheckMostOverridenMethods(*I, Methods))
6202 return true;
6203 return false;
6204}
6205
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006206/// \brief Member lookup function that determines whether a given C++
6207/// method overloads virtual methods in a base class without overriding any,
6208/// to be used with CXXRecordDecl::lookupInBases().
6209static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6210 CXXBasePath &Path,
6211 void *UserData) {
6212 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6213
6214 FindHiddenVirtualMethodData &Data
6215 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6216
6217 DeclarationName Name = Data.Method->getDeclName();
6218 assert(Name.getNameKind() == DeclarationName::Identifier);
6219
6220 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006221 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006222 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006223 !Path.Decls.empty();
6224 Path.Decls = Path.Decls.slice(1)) {
6225 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006226 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006227 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006228 foundSameNameMethod = true;
6229 // Interested only in hidden virtual methods.
6230 if (!MD->isVirtual())
6231 continue;
6232 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006233 // don't warn about the other overloaded methods. Clang deviates from GCC
6234 // by only diagnosing overloads of inherited virtual functions that do not
6235 // override any other virtual functions in the base. GCC's
6236 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6237 // function from a base class. These cases may be better served by a
6238 // warning (not specific to virtual functions) on call sites when the call
6239 // would select a different function from the base class, were it visible.
6240 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006241 if (!Data.S->IsOverload(Data.Method, MD, false))
6242 return true;
6243 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006244 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006245 overloadedMethods.push_back(MD);
6246 }
6247 }
6248
6249 if (foundSameNameMethod)
6250 Data.OverloadedMethods.append(overloadedMethods.begin(),
6251 overloadedMethods.end());
6252 return foundSameNameMethod;
6253}
6254
David Blaikie282c92a2012-10-19 00:53:08 +00006255/// \brief Add the most overriden methods from MD to Methods
6256static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006257 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006258 if (MD->size_overridden_methods() == 0)
6259 Methods.insert(MD->getCanonicalDecl());
6260 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6261 E = MD->end_overridden_methods();
6262 I != E; ++I)
6263 AddMostOverridenMethods(*I, Methods);
6264}
6265
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006266/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006267/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006268void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6269 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006270 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006271 return;
6272
6273 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6274 /*bool RecordPaths=*/false,
6275 /*bool DetectVirtual=*/false);
6276 FindHiddenVirtualMethodData Data;
6277 Data.Method = MD;
6278 Data.S = this;
6279
6280 // Keep the base methods that were overriden or introduced in the subclass
6281 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006282 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006283 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6284 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6285 NamedDecl *ND = *I;
6286 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006287 ND = shad->getTargetDecl();
6288 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6289 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006290 }
6291
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006292 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6293 OverloadedMethods = Data.OverloadedMethods;
6294}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006295
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006296void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6297 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6298 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6299 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6300 PartialDiagnostic PD = PDiag(
6301 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6302 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6303 Diag(overloadedMD->getLocation(), PD);
6304 }
6305}
6306
6307/// \brief Diagnose methods which overload virtual methods in a base class
6308/// without overriding any.
6309void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6310 if (MD->isInvalidDecl())
6311 return;
6312
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006313 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006314 return;
6315
6316 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6317 FindHiddenVirtualMethods(MD, OverloadedMethods);
6318 if (!OverloadedMethods.empty()) {
6319 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6320 << MD << (OverloadedMethods.size() > 1);
6321
6322 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006323 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006324}
6325
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006326void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006327 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006328 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006329 SourceLocation RBrac,
6330 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006331 if (!TagDecl)
6332 return;
Mike Stump11289f42009-09-09 15:08:12 +00006333
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006334 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006335
Rafael Espindola06e1b132012-07-12 04:32:30 +00006336 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6337 if (l->getKind() != AttributeList::AT_Visibility)
6338 continue;
6339 l->setInvalid();
6340 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6341 l->getName();
6342 }
6343
David Blaikie751c5582011-09-22 02:58:26 +00006344 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006345 // strict aliasing violation!
6346 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006347 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006348
Douglas Gregor0be31a22010-07-02 17:43:08 +00006349 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006350 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006351}
6352
Douglas Gregor05379422008-11-03 17:51:48 +00006353/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6354/// special functions, such as the default constructor, copy
6355/// constructor, or destructor, to the given C++ class (C++
6356/// [special]p1). This routine can only be executed just before the
6357/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006358void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006359 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006360 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006361
Richard Smith6b02d462012-12-08 08:32:28 +00006362 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006363 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006364
Richard Smith6b02d462012-12-08 08:32:28 +00006365 // If the properties or semantics of the copy constructor couldn't be
6366 // determined while the class was being declared, force a declaration
6367 // of it now.
6368 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6369 DeclareImplicitCopyConstructor(ClassDecl);
6370 }
6371
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006372 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006373 ++ASTContext::NumImplicitMoveConstructors;
6374
Richard Smith6b02d462012-12-08 08:32:28 +00006375 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6376 DeclareImplicitMoveConstructor(ClassDecl);
6377 }
6378
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006379 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6380 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006381
6382 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006383 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006384 // it shows up in the right place in the vtable and that we diagnose
6385 // problems with the implicit exception specification.
6386 if (ClassDecl->isDynamicClass() ||
6387 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006388 DeclareImplicitCopyAssignment(ClassDecl);
6389 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006390
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006391 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006392 ++ASTContext::NumImplicitMoveAssignmentOperators;
6393
6394 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006395 if (ClassDecl->isDynamicClass() ||
6396 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006397 DeclareImplicitMoveAssignment(ClassDecl);
6398 }
6399
Douglas Gregor7454c562010-07-02 20:37:36 +00006400 if (!ClassDecl->hasUserDeclaredDestructor()) {
6401 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006402
6403 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006404 // have to declare the destructor immediately. This ensures that, e.g., it
6405 // shows up in the right place in the vtable and that we diagnose problems
6406 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006407 if (ClassDecl->isDynamicClass() ||
6408 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006409 DeclareImplicitDestructor(ClassDecl);
6410 }
Douglas Gregor05379422008-11-03 17:51:48 +00006411}
6412
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006413unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006414 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006415 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006416
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006417 // The order of template parameters is not important here. All names
6418 // get added to the same scope.
6419 SmallVector<TemplateParameterList *, 4> ParameterLists;
6420
6421 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6422 D = TD->getTemplatedDecl();
6423
6424 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6425 ParameterLists.push_back(PSD->getTemplateParameters());
6426
6427 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6428 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6429 ParameterLists.push_back(DD->getTemplateParameterList(i));
6430
6431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6432 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6433 ParameterLists.push_back(FTD->getTemplateParameters());
6434 }
6435 }
6436
6437 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6438 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6439 ParameterLists.push_back(TD->getTemplateParameterList(i));
6440
6441 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6442 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6443 ParameterLists.push_back(CTD->getTemplateParameters());
6444 }
6445 }
6446
6447 unsigned Count = 0;
6448 for (TemplateParameterList *Params : ParameterLists) {
6449 if (Params->size() > 0)
6450 // Ignore explicit specializations; they don't contribute to the template
6451 // depth.
6452 ++Count;
6453 for (NamedDecl *Param : *Params) {
6454 if (Param->getDeclName()) {
6455 S->AddDecl(Param);
6456 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006457 }
6458 }
6459 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006460
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006461 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006462}
6463
John McCall48871652010-08-21 09:40:31 +00006464void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006465 if (!RecordD) return;
6466 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006467 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006468 PushDeclContext(S, Record);
6469}
6470
John McCall48871652010-08-21 09:40:31 +00006471void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006472 if (!RecordD) return;
6473 PopDeclContext();
6474}
6475
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006476/// This is used to implement the constant expression evaluation part of the
6477/// attribute enable_if extension. There is nothing in standard C++ which would
6478/// require reentering parameters.
6479void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6480 if (!Param)
6481 return;
6482
6483 S->AddDecl(Param);
6484 if (Param->getDeclName())
6485 IdResolver.AddDecl(Param);
6486}
6487
Douglas Gregor4d87df52008-12-16 21:30:33 +00006488/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6489/// parsing a top-level (non-nested) C++ class, and we are now
6490/// parsing those parts of the given Method declaration that could
6491/// not be parsed earlier (C++ [class.mem]p2), such as default
6492/// arguments. This action should enter the scope of the given
6493/// Method declaration as if we had just parsed the qualified method
6494/// name. However, it should not bring the parameters into scope;
6495/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006496void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006497}
6498
6499/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6500/// C++ method declaration. We're (re-)introducing the given
6501/// function parameter into scope for use in parsing later parts of
6502/// the method declaration. For example, we could see an
6503/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006504void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006505 if (!ParamD)
6506 return;
Mike Stump11289f42009-09-09 15:08:12 +00006507
John McCall48871652010-08-21 09:40:31 +00006508 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006509
6510 // If this parameter has an unparsed default argument, clear it out
6511 // to make way for the parsed default argument.
6512 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006513 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006514
John McCall48871652010-08-21 09:40:31 +00006515 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006516 if (Param->getDeclName())
6517 IdResolver.AddDecl(Param);
6518}
6519
6520/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6521/// processing the delayed method declaration for Method. The method
6522/// declaration is now considered finished. There may be a separate
6523/// ActOnStartOfFunctionDef action later (not necessarily
6524/// immediately!) for this method, if it was also defined inside the
6525/// class body.
John McCall48871652010-08-21 09:40:31 +00006526void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006527 if (!MethodD)
6528 return;
Mike Stump11289f42009-09-09 15:08:12 +00006529
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006530 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006531
John McCall48871652010-08-21 09:40:31 +00006532 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006533
6534 // Now that we have our default arguments, check the constructor
6535 // again. It could produce additional diagnostics or affect whether
6536 // the class has implicitly-declared destructors, among other
6537 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006538 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6539 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006540
6541 // Check the default arguments, which we may have added.
6542 if (!Method->isInvalidDecl())
6543 CheckCXXDefaultArguments(Method);
6544}
6545
Douglas Gregor831c93f2008-11-05 20:51:48 +00006546/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006547/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006548/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006549/// emit diagnostics and set the invalid bit to true. In any case, the type
6550/// will be updated to reflect a well-formed type for the constructor and
6551/// returned.
6552QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006553 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006554 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006555
6556 // C++ [class.ctor]p3:
6557 // A constructor shall not be virtual (10.3) or static (9.4). A
6558 // constructor can be invoked for a const, volatile or const
6559 // volatile object. A constructor shall not be declared const,
6560 // volatile, or const volatile (9.3.2).
6561 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006562 if (!D.isInvalidType())
6563 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6564 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6565 << SourceRange(D.getIdentifierLoc());
6566 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006567 }
John McCall8e7d6562010-08-26 03:08:43 +00006568 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006569 if (!D.isInvalidType())
6570 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6571 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6572 << SourceRange(D.getIdentifierLoc());
6573 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006574 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006575 }
Mike Stump11289f42009-09-09 15:08:12 +00006576
David Majnemer03f705f2014-07-08 18:18:04 +00006577 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6578 diagnoseIgnoredQualifiers(
6579 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6580 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6581 D.getDeclSpec().getRestrictSpecLoc(),
6582 D.getDeclSpec().getAtomicSpecLoc());
6583 D.setInvalidType();
6584 }
6585
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006586 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006587 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006588 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006589 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6590 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006591 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006592 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6593 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006594 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006595 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6596 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006597 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006598 }
Mike Stump11289f42009-09-09 15:08:12 +00006599
Douglas Gregordb9d6642011-01-26 05:01:58 +00006600 // C++0x [class.ctor]p4:
6601 // A constructor shall not be declared with a ref-qualifier.
6602 if (FTI.hasRefQualifier()) {
6603 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6604 << FTI.RefQualifierIsLValueRef
6605 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6606 D.setInvalidType();
6607 }
6608
Douglas Gregor831c93f2008-11-05 20:51:48 +00006609 // Rebuild the function type "R" without any type qualifiers (in
6610 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006611 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006612 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006613 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006614 return R;
6615
6616 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6617 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006618 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006619
6620 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006621}
6622
Douglas Gregor4d87df52008-12-16 21:30:33 +00006623/// CheckConstructor - Checks a fully-formed constructor for
6624/// well-formedness, issuing any diagnostics required. Returns true if
6625/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006626void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006627 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006628 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6629 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006630 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006631
6632 // C++ [class.copy]p3:
6633 // A declaration of a constructor for a class X is ill-formed if
6634 // its first parameter is of type (optionally cv-qualified) X and
6635 // either there are no other parameters or else all other
6636 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006637 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006638 ((Constructor->getNumParams() == 1) ||
6639 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006640 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6641 Constructor->getTemplateSpecializationKind()
6642 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006643 QualType ParamType = Constructor->getParamDecl(0)->getType();
6644 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6645 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006646 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006647 const char *ConstRef
6648 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6649 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006650 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006651 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006652
6653 // FIXME: Rather that making the constructor invalid, we should endeavor
6654 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006655 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006656 }
6657 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006658}
6659
John McCalldeb646e2010-08-04 01:04:25 +00006660/// CheckDestructor - Checks a fully-formed destructor definition for
6661/// well-formedness, issuing any diagnostics required. Returns true
6662/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006663bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006664 CXXRecordDecl *RD = Destructor->getParent();
6665
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006666 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006667 SourceLocation Loc;
6668
6669 if (!Destructor->isImplicit())
6670 Loc = Destructor->getLocation();
6671 else
6672 Loc = RD->getLocation();
6673
6674 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006675 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006676 DeclarationName Name =
6677 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006678 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006679 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006680 // If there's no class-specific operator delete, look up the global
6681 // non-array delete.
6682 if (!OperatorDelete)
6683 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006684
Eli Friedmanfa0df832012-02-02 03:46:19 +00006685 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006686
6687 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006688 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006689
6690 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006691}
6692
Douglas Gregor831c93f2008-11-05 20:51:48 +00006693/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6694/// the well-formednes of the destructor declarator @p D with type @p
6695/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006696/// emit diagnostics and set the declarator to invalid. Even if this happens,
6697/// will be updated to reflect a well-formed type for the destructor and
6698/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006699QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006700 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006701 // C++ [class.dtor]p1:
6702 // [...] A typedef-name that names a class is a class-name
6703 // (7.1.3); however, a typedef-name that names a class shall not
6704 // be used as the identifier in the declarator for a destructor
6705 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006706 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006707 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006708 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006709 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006710 else if (const TemplateSpecializationType *TST =
6711 DeclaratorType->getAs<TemplateSpecializationType>())
6712 if (TST->isTypeAlias())
6713 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6714 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006715
6716 // C++ [class.dtor]p2:
6717 // A destructor is used to destroy objects of its class type. A
6718 // destructor takes no parameters, and no return type can be
6719 // specified for it (not even void). The address of a destructor
6720 // shall not be taken. A destructor shall not be static. A
6721 // destructor can be invoked for a const, volatile or const
6722 // volatile object. A destructor shall not be declared const,
6723 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006724 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006725 if (!D.isInvalidType())
6726 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6727 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006728 << SourceRange(D.getIdentifierLoc())
6729 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6730
John McCall8e7d6562010-08-26 03:08:43 +00006731 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006732 }
David Majnemer03f705f2014-07-08 18:18:04 +00006733 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006734 // Destructors don't have return types, but the parser will
6735 // happily parse something like:
6736 //
6737 // class X {
6738 // float ~X();
6739 // };
6740 //
6741 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006742 if (D.getDeclSpec().hasTypeSpecifier())
6743 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6744 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6745 << SourceRange(D.getIdentifierLoc());
6746 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6747 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6748 SourceLocation(),
6749 D.getDeclSpec().getConstSpecLoc(),
6750 D.getDeclSpec().getVolatileSpecLoc(),
6751 D.getDeclSpec().getRestrictSpecLoc(),
6752 D.getDeclSpec().getAtomicSpecLoc());
6753 D.setInvalidType();
6754 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006755 }
Mike Stump11289f42009-09-09 15:08:12 +00006756
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006757 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006758 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006759 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006760 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6761 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006762 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006763 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6764 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006765 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006766 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6767 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006768 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006769 }
6770
Douglas Gregordb9d6642011-01-26 05:01:58 +00006771 // C++0x [class.dtor]p2:
6772 // A destructor shall not be declared with a ref-qualifier.
6773 if (FTI.hasRefQualifier()) {
6774 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6775 << FTI.RefQualifierIsLValueRef
6776 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6777 D.setInvalidType();
6778 }
6779
Douglas Gregor831c93f2008-11-05 20:51:48 +00006780 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006781 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006782 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6783
6784 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006785 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006786 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006787 }
6788
Mike Stump11289f42009-09-09 15:08:12 +00006789 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006790 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006791 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006792 D.setInvalidType();
6793 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006794
6795 // Rebuild the function type "R" without any type qualifiers or
6796 // parameters (in case any of the errors above fired) and with
6797 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006798 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006799 if (!D.isInvalidType())
6800 return R;
6801
Douglas Gregor95755162010-07-01 05:10:53 +00006802 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006803 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6804 EPI.Variadic = false;
6805 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006806 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006807 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006808}
6809
Richard Smitha865a162014-12-19 02:07:47 +00006810static void extendLeft(SourceRange &R, const SourceRange &Before) {
6811 if (Before.isInvalid())
6812 return;
6813 R.setBegin(Before.getBegin());
6814 if (R.getEnd().isInvalid())
6815 R.setEnd(Before.getEnd());
6816}
6817
6818static void extendRight(SourceRange &R, const SourceRange &After) {
6819 if (After.isInvalid())
6820 return;
6821 if (R.getBegin().isInvalid())
6822 R.setBegin(After.getBegin());
6823 R.setEnd(After.getEnd());
6824}
6825
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006826/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6827/// well-formednes of the conversion function declarator @p D with
6828/// type @p R. If there are any errors in the declarator, this routine
6829/// will emit diagnostics and return true. Otherwise, it will return
6830/// false. Either way, the type @p R will be updated to reflect a
6831/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006832void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006833 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006834 // C++ [class.conv.fct]p1:
6835 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006836 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006837 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006838 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006839 if (!D.isInvalidType())
6840 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006841 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6842 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006843 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006844 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006845 }
John McCall212fa2e2010-04-13 00:04:31 +00006846
Richard Smitha865a162014-12-19 02:07:47 +00006847 TypeSourceInfo *ConvTSI = nullptr;
6848 QualType ConvType =
6849 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006850
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006851 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006852 // Conversion functions don't have return types, but the parser will
6853 // happily parse something like:
6854 //
6855 // class X {
6856 // float operator bool();
6857 // };
6858 //
6859 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006860 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6861 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6862 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006863 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006864 }
6865
John McCall212fa2e2010-04-13 00:04:31 +00006866 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6867
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006868 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006869 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006870 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6871
6872 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006873 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006874 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006875 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006876 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006877 D.setInvalidType();
6878 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006879
John McCall212fa2e2010-04-13 00:04:31 +00006880 // Diagnose "&operator bool()" and other such nonsense. This
6881 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006882 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006883 bool NeedsTypedef = false;
6884 SourceRange Before, After;
6885
6886 // Walk the chunks and extract information on them for our diagnostic.
6887 bool PastFunctionChunk = false;
6888 for (auto &Chunk : D.type_objects()) {
6889 switch (Chunk.Kind) {
6890 case DeclaratorChunk::Function:
6891 if (!PastFunctionChunk) {
6892 if (Chunk.Fun.HasTrailingReturnType) {
6893 TypeSourceInfo *TRT = nullptr;
6894 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6895 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6896 }
6897 PastFunctionChunk = true;
6898 break;
6899 }
6900 // Fall through.
6901 case DeclaratorChunk::Array:
6902 NeedsTypedef = true;
6903 extendRight(After, Chunk.getSourceRange());
6904 break;
6905
6906 case DeclaratorChunk::Pointer:
6907 case DeclaratorChunk::BlockPointer:
6908 case DeclaratorChunk::Reference:
6909 case DeclaratorChunk::MemberPointer:
6910 extendLeft(Before, Chunk.getSourceRange());
6911 break;
6912
6913 case DeclaratorChunk::Paren:
6914 extendLeft(Before, Chunk.Loc);
6915 extendRight(After, Chunk.EndLoc);
6916 break;
6917 }
6918 }
6919
6920 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6921 After.isValid() ? After.getBegin() :
6922 D.getIdentifierLoc();
6923 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6924 DB << Before << After;
6925
6926 if (!NeedsTypedef) {
6927 DB << /*don't need a typedef*/0;
6928
6929 // If we can provide a correct fix-it hint, do so.
6930 if (After.isInvalid() && ConvTSI) {
6931 SourceLocation InsertLoc =
6932 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6933 DB << FixItHint::CreateInsertion(InsertLoc, " ")
6934 << FixItHint::CreateInsertionFromRange(
6935 InsertLoc, CharSourceRange::getTokenRange(Before))
6936 << FixItHint::CreateRemoval(Before);
6937 }
6938 } else if (!Proto->getReturnType()->isDependentType()) {
6939 DB << /*typedef*/1 << Proto->getReturnType();
6940 } else if (getLangOpts().CPlusPlus11) {
6941 DB << /*alias template*/2 << Proto->getReturnType();
6942 } else {
6943 DB << /*might not be fixable*/3;
6944 }
6945
6946 // Recover by incorporating the other type chunks into the result type.
6947 // Note, this does *not* change the name of the function. This is compatible
6948 // with the GCC extension:
6949 // struct S { &operator int(); } s;
6950 // int &r = s.operator int(); // ok in GCC
6951 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00006952 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006953 }
6954
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006955 // C++ [class.conv.fct]p4:
6956 // The conversion-type-id shall not represent a function type nor
6957 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006958 if (ConvType->isArrayType()) {
6959 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6960 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006961 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006962 } else if (ConvType->isFunctionType()) {
6963 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6964 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006965 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006966 }
6967
6968 // Rebuild the function type "R" without any parameters (in case any
6969 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006970 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006971 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006972 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006973
Douglas Gregor5fb53972009-01-14 15:45:31 +00006974 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006975 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006976 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006977 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006978 diag::warn_cxx98_compat_explicit_conversion_functions :
6979 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006980 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006981}
6982
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006983/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6984/// the declaration of the given C++ conversion function. This routine
6985/// is responsible for recording the conversion function in the C++
6986/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006987Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006988 assert(Conversion && "Expected to receive a conversion function declaration");
6989
Douglas Gregor4287b372008-12-12 08:25:50 +00006990 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006991
6992 // Make sure we aren't redeclaring the conversion function.
6993 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006994
6995 // C++ [class.conv.fct]p1:
6996 // [...] A conversion function is never used to convert a
6997 // (possibly cv-qualified) object to the (possibly cv-qualified)
6998 // same object type (or a reference to it), to a (possibly
6999 // cv-qualified) base class of that type (or a reference to it),
7000 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007001 // FIXME: Suppress this warning if the conversion function ends up being a
7002 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007003 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007004 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007005 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007006 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007007 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7008 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007009 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007010 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007011 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7012 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007013 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007014 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007015 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007016 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007017 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007018 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007019 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007020 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007021 }
7022
Douglas Gregor457104e2010-09-29 04:25:11 +00007023 if (FunctionTemplateDecl *ConversionTemplate
7024 = Conversion->getDescribedFunctionTemplate())
7025 return ConversionTemplate;
7026
John McCall48871652010-08-21 09:40:31 +00007027 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007028}
7029
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007030//===----------------------------------------------------------------------===//
7031// Namespace Handling
7032//===----------------------------------------------------------------------===//
7033
Richard Smith45bb8852012-10-04 22:13:39 +00007034/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7035/// reopened.
7036static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7037 SourceLocation Loc,
7038 IdentifierInfo *II, bool *IsInline,
7039 NamespaceDecl *PrevNS) {
7040 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007041
Richard Smithf501cc32012-10-05 01:46:25 +00007042 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7043 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7044 // inline namespaces, with the intention of bringing names into namespace std.
7045 //
7046 // We support this just well enough to get that case working; this is not
7047 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007048 if (*IsInline && II && II->getName().startswith("__atomic") &&
7049 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007050 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007051 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7052 NS = NS->getPreviousDecl())
7053 NS->setInline(*IsInline);
7054 // Patch up the lookup table for the containing namespace. This isn't really
7055 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007056 for (auto *I : PrevNS->decls())
7057 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007058 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7059 return;
7060 }
7061
7062 if (PrevNS->isInline())
7063 // The user probably just forgot the 'inline', so suggest that it
7064 // be added back.
7065 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7066 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7067 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007068 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007069
7070 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7071 *IsInline = PrevNS->isInline();
7072}
John McCallb1be5232010-08-26 09:15:37 +00007073
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007074/// ActOnStartNamespaceDef - This is called at the start of a namespace
7075/// definition.
John McCall48871652010-08-21 09:40:31 +00007076Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007077 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007078 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007079 SourceLocation IdentLoc,
7080 IdentifierInfo *II,
7081 SourceLocation LBrace,
7082 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007083 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7084 // For anonymous namespace, take the location of the left brace.
7085 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007086 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007087 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007088 bool IsStd = false;
7089 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007090 Scope *DeclRegionScope = NamespcScope->getParent();
7091
Craig Topperc3ec1492014-05-26 06:22:03 +00007092 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007093 if (II) {
7094 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007095 // The identifier in an original-namespace-definition shall not
7096 // have been previously defined in the declarative region in
7097 // which the original-namespace-definition appears. The
7098 // identifier in an original-namespace-definition is the name of
7099 // the namespace. Subsequently in that declarative region, it is
7100 // treated as an original-namespace-name.
7101 //
7102 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007103 // look through using directives, just look for any ordinary names.
7104
7105 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007106 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7107 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007108 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007109 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7110 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7111 ++I) {
7112 if ((*I)->getIdentifierNamespace() & IDNS) {
7113 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007114 break;
7115 }
7116 }
7117
Douglas Gregore57e7522012-01-07 09:11:48 +00007118 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7119
7120 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007121 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007122 if (IsInline != PrevNS->isInline())
7123 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7124 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007125 } else if (PrevDecl) {
7126 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007127 Diag(Loc, diag::err_redefinition_different_kind)
7128 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007129 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007130 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007131 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007132 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007133 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007134 // This is the first "real" definition of the namespace "std", so update
7135 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007136 PrevNS = getStdNamespace();
7137 IsStd = true;
7138 AddToKnown = !IsInline;
7139 } else {
7140 // We've seen this namespace for the first time.
7141 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007142 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007143 } else {
John McCall4fa53422009-10-01 00:25:31 +00007144 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007145
7146 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007147 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007148 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007149 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007150 } else {
7151 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007152 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007153 }
7154
Richard Smith45bb8852012-10-04 22:13:39 +00007155 if (PrevNS && IsInline != PrevNS->isInline())
7156 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7157 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007158 }
7159
7160 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7161 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007162 if (IsInvalid)
7163 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007164
7165 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007166
Douglas Gregore57e7522012-01-07 09:11:48 +00007167 // FIXME: Should we be merging attributes?
7168 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007169 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007170
7171 if (IsStd)
7172 StdNamespace = Namespc;
7173 if (AddToKnown)
7174 KnownNamespaces[Namespc] = false;
7175
7176 if (II) {
7177 PushOnScopeChains(Namespc, DeclRegionScope);
7178 } else {
7179 // Link the anonymous namespace into its parent.
7180 DeclContext *Parent = CurContext->getRedeclContext();
7181 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7182 TU->setAnonymousNamespace(Namespc);
7183 } else {
7184 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007185 }
John McCall4fa53422009-10-01 00:25:31 +00007186
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007187 CurContext->addDecl(Namespc);
7188
John McCall4fa53422009-10-01 00:25:31 +00007189 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7190 // behaves as if it were replaced by
7191 // namespace unique { /* empty body */ }
7192 // using namespace unique;
7193 // namespace unique { namespace-body }
7194 // where all occurrences of 'unique' in a translation unit are
7195 // replaced by the same identifier and this identifier differs
7196 // from all other identifiers in the entire program.
7197
7198 // We just create the namespace with an empty name and then add an
7199 // implicit using declaration, just like the standard suggests.
7200 //
7201 // CodeGen enforces the "universally unique" aspect by giving all
7202 // declarations semantically contained within an anonymous
7203 // namespace internal linkage.
7204
Douglas Gregore57e7522012-01-07 09:11:48 +00007205 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007206 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007207 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007208 /* 'using' */ LBrace,
7209 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007210 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007211 /* identifier */ SourceLocation(),
7212 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007213 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007214 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007215 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007216 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007217 }
7218
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007219 ActOnDocumentableDecl(Namespc);
7220
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007221 // Although we could have an invalid decl (i.e. the namespace name is a
7222 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007223 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7224 // for the namespace has the declarations that showed up in that particular
7225 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007226 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007227 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007228}
7229
Sebastian Redla6602e92009-11-23 15:34:23 +00007230/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7231/// is a namespace alias, returns the namespace it points to.
7232static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7233 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7234 return AD->getNamespace();
7235 return dyn_cast_or_null<NamespaceDecl>(D);
7236}
7237
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007238/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7239/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007240void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007241 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7242 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007243 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007244 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007245 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007246 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007247}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007248
John McCall28a0cf72010-08-25 07:42:41 +00007249CXXRecordDecl *Sema::getStdBadAlloc() const {
7250 return cast_or_null<CXXRecordDecl>(
7251 StdBadAlloc.get(Context.getExternalSource()));
7252}
7253
7254NamespaceDecl *Sema::getStdNamespace() const {
7255 return cast_or_null<NamespaceDecl>(
7256 StdNamespace.get(Context.getExternalSource()));
7257}
7258
Douglas Gregorcdf87022010-06-29 17:53:46 +00007259/// \brief Retrieve the special "std" namespace, which may require us to
7260/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007261NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007262 if (!StdNamespace) {
7263 // The "std" namespace has not yet been defined, so build one implicitly.
7264 StdNamespace = NamespaceDecl::Create(Context,
7265 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007266 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007267 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007268 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007269 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007270 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007271 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007272
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007273 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007274}
7275
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007276bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007277 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007278 "Looking for std::initializer_list outside of C++.");
7279
7280 // We're looking for implicit instantiations of
7281 // template <typename E> class std::initializer_list.
7282
7283 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7284 return false;
7285
Craig Topperc3ec1492014-05-26 06:22:03 +00007286 ClassTemplateDecl *Template = nullptr;
7287 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007288
Sebastian Redl43144e72012-01-17 22:49:58 +00007289 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007290
Sebastian Redl43144e72012-01-17 22:49:58 +00007291 ClassTemplateSpecializationDecl *Specialization =
7292 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7293 if (!Specialization)
7294 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007295
Sebastian Redl43144e72012-01-17 22:49:58 +00007296 Template = Specialization->getSpecializedTemplate();
7297 Arguments = Specialization->getTemplateArgs().data();
7298 } else if (const TemplateSpecializationType *TST =
7299 Ty->getAs<TemplateSpecializationType>()) {
7300 Template = dyn_cast_or_null<ClassTemplateDecl>(
7301 TST->getTemplateName().getAsTemplateDecl());
7302 Arguments = TST->getArgs();
7303 }
7304 if (!Template)
7305 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007306
7307 if (!StdInitializerList) {
7308 // Haven't recognized std::initializer_list yet, maybe this is it.
7309 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7310 if (TemplateClass->getIdentifier() !=
7311 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007312 !getStdNamespace()->InEnclosingNamespaceSetOf(
7313 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007314 return false;
7315 // This is a template called std::initializer_list, but is it the right
7316 // template?
7317 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007318 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007319 return false;
7320 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7321 return false;
7322
7323 // It's the right template.
7324 StdInitializerList = Template;
7325 }
7326
7327 if (Template != StdInitializerList)
7328 return false;
7329
7330 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007331 if (Element)
7332 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007333 return true;
7334}
7335
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007336static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7337 NamespaceDecl *Std = S.getStdNamespace();
7338 if (!Std) {
7339 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007340 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007341 }
7342
7343 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7344 Loc, Sema::LookupOrdinaryName);
7345 if (!S.LookupQualifiedName(Result, Std)) {
7346 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007347 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007348 }
7349 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7350 if (!Template) {
7351 Result.suppressDiagnostics();
7352 // We found something weird. Complain about the first thing we found.
7353 NamedDecl *Found = *Result.begin();
7354 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007355 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007356 }
7357
7358 // We found some template called std::initializer_list. Now verify that it's
7359 // correct.
7360 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007361 if (Params->getMinRequiredArguments() != 1 ||
7362 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007363 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007364 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007365 }
7366
7367 return Template;
7368}
7369
7370QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7371 if (!StdInitializerList) {
7372 StdInitializerList = LookupStdInitializerList(*this, Loc);
7373 if (!StdInitializerList)
7374 return QualType();
7375 }
7376
7377 TemplateArgumentListInfo Args(Loc, Loc);
7378 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7379 Context.getTrivialTypeSourceInfo(Element,
7380 Loc)));
7381 return Context.getCanonicalType(
7382 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7383}
7384
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007385bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7386 // C++ [dcl.init.list]p2:
7387 // A constructor is an initializer-list constructor if its first parameter
7388 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7389 // std::initializer_list<E> for some type E, and either there are no other
7390 // parameters or else all other parameters have default arguments.
7391 if (Ctor->getNumParams() < 1 ||
7392 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7393 return false;
7394
7395 QualType ArgType = Ctor->getParamDecl(0)->getType();
7396 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7397 ArgType = RT->getPointeeType().getUnqualifiedType();
7398
Craig Topperc3ec1492014-05-26 06:22:03 +00007399 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007400}
7401
Douglas Gregora172e082011-03-26 22:25:30 +00007402/// \brief Determine whether a using statement is in a context where it will be
7403/// apply in all contexts.
7404static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7405 switch (CurContext->getDeclKind()) {
7406 case Decl::TranslationUnit:
7407 return true;
7408 case Decl::LinkageSpec:
7409 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7410 default:
7411 return false;
7412 }
7413}
7414
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007415namespace {
7416
7417// Callback to only accept typo corrections that are namespaces.
7418class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007419public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007420 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007421 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007422 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007423 return false;
7424 }
7425};
7426
7427}
7428
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007429static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7430 CXXScopeSpec &SS,
7431 SourceLocation IdentLoc,
7432 IdentifierInfo *Ident) {
7433 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007434 if (TypoCorrection Corrected =
7435 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7436 llvm::make_unique<NamespaceValidatorCCC>(),
7437 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007438 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007439 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7440 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007441 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007442 S.diagnoseTypo(Corrected,
7443 S.PDiag(diag::err_using_directive_member_suggest)
7444 << Ident << DC << DroppedSpecifier << SS.getRange(),
7445 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007446 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007447 S.diagnoseTypo(Corrected,
7448 S.PDiag(diag::err_using_directive_suggest) << Ident,
7449 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007450 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007451 R.addDecl(Corrected.getCorrectionDecl());
7452 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007453 }
7454 return false;
7455}
7456
John McCall48871652010-08-21 09:40:31 +00007457Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007458 SourceLocation UsingLoc,
7459 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007460 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007461 SourceLocation IdentLoc,
7462 IdentifierInfo *NamespcName,
7463 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007464 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7465 assert(NamespcName && "Invalid NamespcName.");
7466 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007467
7468 // This can only happen along a recovery path.
7469 while (S->getFlags() & Scope::TemplateParamScope)
7470 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007471 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007472
Craig Topperc3ec1492014-05-26 06:22:03 +00007473 UsingDirectiveDecl *UDir = nullptr;
7474 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007475 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007476 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007477
Douglas Gregor34074322009-01-14 22:20:51 +00007478 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007479 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7480 LookupParsedName(R, S, &SS);
7481 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007482 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007483
Douglas Gregorcdf87022010-06-29 17:53:46 +00007484 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007485 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007486 // Allow "using namespace std;" or "using namespace ::std;" even if
7487 // "std" hasn't been defined yet, for GCC compatibility.
7488 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7489 NamespcName->isStr("std")) {
7490 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007491 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007492 R.resolveKind();
7493 }
7494 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007495 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007496 }
7497
John McCall9f3059a2009-10-09 21:13:30 +00007498 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007499 NamedDecl *Named = R.getFoundDecl();
7500 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7501 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007502
Nico Riecke50e59a2014-11-24 17:29:52 +00007503 // The use of a nested name specifier may trigger deprecation warnings.
7504 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007505
Douglas Gregor889ceb72009-02-03 19:21:40 +00007506 // C++ [namespace.udir]p1:
7507 // A using-directive specifies that the names in the nominated
7508 // namespace can be used in the scope in which the
7509 // using-directive appears after the using-directive. During
7510 // unqualified name lookup (3.4.1), the names appear as if they
7511 // were declared in the nearest enclosing namespace which
7512 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007513 // namespace. [Note: in this context, "contains" means "contains
7514 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007515
7516 // Find enclosing context containing both using-directive and
7517 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007518 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007519 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7520 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7521 CommonAncestor = CommonAncestor->getParent();
7522
Sebastian Redla6602e92009-11-23 15:34:23 +00007523 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007524 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007525 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007526
Douglas Gregora172e082011-03-26 22:25:30 +00007527 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007528 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007529 Diag(IdentLoc, diag::warn_using_directive_in_header);
7530 }
7531
Douglas Gregor889ceb72009-02-03 19:21:40 +00007532 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007533 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007534 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007535 }
7536
Richard Smith54ecd982013-02-20 19:22:51 +00007537 if (UDir)
7538 ProcessDeclAttributeList(S, UDir, AttrList);
7539
John McCall48871652010-08-21 09:40:31 +00007540 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007541}
7542
7543void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007544 // If the scope has an associated entity and the using directive is at
7545 // namespace or translation unit scope, add the UsingDirectiveDecl into
7546 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007547 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007548 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007549 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007550 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007551 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007552 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007553 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007554}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007555
Douglas Gregorfec52632009-06-20 00:51:54 +00007556
John McCall48871652010-08-21 09:40:31 +00007557Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007558 AccessSpecifier AS,
7559 bool HasUsingKeyword,
7560 SourceLocation UsingLoc,
7561 CXXScopeSpec &SS,
7562 UnqualifiedId &Name,
7563 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007564 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007565 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007566 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007567
Douglas Gregor220f4272009-11-04 16:30:06 +00007568 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007569 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007570 case UnqualifiedId::IK_Identifier:
7571 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007572 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007573 case UnqualifiedId::IK_ConversionFunctionId:
7574 break;
7575
7576 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007577 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007578 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007579 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007580 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007581 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007582 diag::err_using_decl_constructor)
7583 << SS.getRange();
7584
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007585 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007586
Craig Topperc3ec1492014-05-26 06:22:03 +00007587 return nullptr;
7588
Douglas Gregor220f4272009-11-04 16:30:06 +00007589 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007590 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007591 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007592 return nullptr;
7593
Douglas Gregor220f4272009-11-04 16:30:06 +00007594 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007595 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007596 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007597 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007598 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007599
7600 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7601 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007602 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007603 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007604
Richard Smithc2bc61b2013-03-18 21:12:30 +00007605 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007606 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007607 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007608 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7609 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007610 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007611 }
7612
Douglas Gregorc4356532010-12-16 00:46:58 +00007613 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7614 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007615 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007616
John McCall3f746822009-11-17 05:59:44 +00007617 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007618 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007619 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007620 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007621 if (UD)
7622 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007623
John McCall48871652010-08-21 09:40:31 +00007624 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007625}
7626
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007627/// \brief Determine whether a using declaration considers the given
7628/// declarations as "equivalent", e.g., if they are redeclarations of
7629/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007630static bool
7631IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7632 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007633 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007634
Richard Smithdda56e42011-04-15 14:24:37 +00007635 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007636 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007637 return Context.hasSameType(TD1->getUnderlyingType(),
7638 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007639
7640 return false;
7641}
7642
7643
John McCall84d87672009-12-10 09:41:52 +00007644/// Determines whether to create a using shadow decl for a particular
7645/// decl, given the set of decls existing prior to this using lookup.
7646bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007647 const LookupResult &Previous,
7648 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007649 // Diagnose finding a decl which is not from a base class of the
7650 // current class. We do this now because there are cases where this
7651 // function will silently decide not to build a shadow decl, which
7652 // will pre-empt further diagnostics.
7653 //
7654 // We don't need to do this in C++0x because we do the check once on
7655 // the qualifier.
7656 //
7657 // FIXME: diagnose the following if we care enough:
7658 // struct A { int foo; };
7659 // struct B : A { using A::foo; };
7660 // template <class T> struct C : A {};
7661 // template <class T> struct D : C<T> { using B::foo; } // <---
7662 // This is invalid (during instantiation) in C++03 because B::foo
7663 // resolves to the using decl in B, which is not a base class of D<T>.
7664 // We can't diagnose it immediately because C<T> is an unknown
7665 // specialization. The UsingShadowDecl in D<T> then points directly
7666 // to A::foo, which will look well-formed when we instantiate.
7667 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007668 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007669 DeclContext *OrigDC = Orig->getDeclContext();
7670
7671 // Handle enums and anonymous structs.
7672 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7673 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7674 while (OrigRec->isAnonymousStructOrUnion())
7675 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7676
7677 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7678 if (OrigDC == CurContext) {
7679 Diag(Using->getLocation(),
7680 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007681 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007682 Diag(Orig->getLocation(), diag::note_using_decl_target);
7683 return true;
7684 }
7685
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007686 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007687 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007688 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007689 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007690 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007691 Diag(Orig->getLocation(), diag::note_using_decl_target);
7692 return true;
7693 }
7694 }
7695
7696 if (Previous.empty()) return false;
7697
7698 NamedDecl *Target = Orig;
7699 if (isa<UsingShadowDecl>(Target))
7700 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7701
John McCalla17e83e2009-12-11 02:33:26 +00007702 // If the target happens to be one of the previous declarations, we
7703 // don't have a conflict.
7704 //
7705 // FIXME: but we might be increasing its access, in which case we
7706 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007707 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007708 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007709 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7710 I != E; ++I) {
7711 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007712 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7713 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7714 PrevShadow = Shadow;
7715 FoundEquivalentDecl = true;
7716 }
John McCalla17e83e2009-12-11 02:33:26 +00007717
7718 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7719 }
7720
Richard Smithfd8634a2013-10-23 02:17:46 +00007721 if (FoundEquivalentDecl)
7722 return false;
7723
Alp Tokera2794f92014-01-22 07:29:52 +00007724 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007725 NamedDecl *OldDecl = nullptr;
7726 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7727 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007728 case Ovl_Overload:
7729 return false;
7730
7731 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007732 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007733 break;
Richard Smith18819302014-02-06 01:31:33 +00007734
John McCall84d87672009-12-10 09:41:52 +00007735 // We found a decl with the exact signature.
7736 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007737 // If we're in a record, we want to hide the target, so we
7738 // return true (without a diagnostic) to tell the caller not to
7739 // build a shadow decl.
7740 if (CurContext->isRecord())
7741 return true;
7742
7743 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007744 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007745 break;
7746 }
7747
7748 Diag(Target->getLocation(), diag::note_using_decl_target);
7749 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7750 return true;
7751 }
7752
7753 // Target is not a function.
7754
John McCall84d87672009-12-10 09:41:52 +00007755 if (isa<TagDecl>(Target)) {
7756 // No conflict between a tag and a non-tag.
7757 if (!Tag) return false;
7758
John McCalle29c5cd2009-12-10 19:51:03 +00007759 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007760 Diag(Target->getLocation(), diag::note_using_decl_target);
7761 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7762 return true;
7763 }
7764
7765 // No conflict between a tag and a non-tag.
7766 if (!NonTag) return false;
7767
John McCalle29c5cd2009-12-10 19:51:03 +00007768 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007769 Diag(Target->getLocation(), diag::note_using_decl_target);
7770 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7771 return true;
7772}
7773
John McCall3f746822009-11-17 05:59:44 +00007774/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007775UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007776 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007777 NamedDecl *Orig,
7778 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007779
7780 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007781 NamedDecl *Target = Orig;
7782 if (isa<UsingShadowDecl>(Target)) {
7783 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7784 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007785 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007786
John McCall3f746822009-11-17 05:59:44 +00007787 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007788 = UsingShadowDecl::Create(Context, CurContext,
7789 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007790 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007791
Douglas Gregor457104e2010-09-29 04:25:11 +00007792 Shadow->setAccess(UD->getAccess());
7793 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7794 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007795
7796 Shadow->setPreviousDecl(PrevDecl);
7797
John McCall3f746822009-11-17 05:59:44 +00007798 if (S)
John McCall3969e302009-12-08 07:46:18 +00007799 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007800 else
John McCall3969e302009-12-08 07:46:18 +00007801 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007802
John McCall3969e302009-12-08 07:46:18 +00007803
John McCall84d87672009-12-10 09:41:52 +00007804 return Shadow;
7805}
John McCall3969e302009-12-08 07:46:18 +00007806
John McCall84d87672009-12-10 09:41:52 +00007807/// Hides a using shadow declaration. This is required by the current
7808/// using-decl implementation when a resolvable using declaration in a
7809/// class is followed by a declaration which would hide or override
7810/// one or more of the using decl's targets; for example:
7811///
7812/// struct Base { void foo(int); };
7813/// struct Derived : Base {
7814/// using Base::foo;
7815/// void foo(int);
7816/// };
7817///
7818/// The governing language is C++03 [namespace.udecl]p12:
7819///
7820/// When a using-declaration brings names from a base class into a
7821/// derived class scope, member functions in the derived class
7822/// override and/or hide member functions with the same name and
7823/// parameter types in a base class (rather than conflicting).
7824///
7825/// There are two ways to implement this:
7826/// (1) optimistically create shadow decls when they're not hidden
7827/// by existing declarations, or
7828/// (2) don't create any shadow decls (or at least don't make them
7829/// visible) until we've fully parsed/instantiated the class.
7830/// The problem with (1) is that we might have to retroactively remove
7831/// a shadow decl, which requires several O(n) operations because the
7832/// decl structures are (very reasonably) not designed for removal.
7833/// (2) avoids this but is very fiddly and phase-dependent.
7834void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007835 if (Shadow->getDeclName().getNameKind() ==
7836 DeclarationName::CXXConversionFunctionName)
7837 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7838
John McCall84d87672009-12-10 09:41:52 +00007839 // Remove it from the DeclContext...
7840 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007841
John McCall84d87672009-12-10 09:41:52 +00007842 // ...and the scope, if applicable...
7843 if (S) {
John McCall48871652010-08-21 09:40:31 +00007844 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007845 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007846 }
7847
John McCall84d87672009-12-10 09:41:52 +00007848 // ...and the using decl.
7849 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7850
7851 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007852 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007853}
7854
Richard Smith09d5b3a2014-05-01 00:35:04 +00007855/// Find the base specifier for a base class with the given type.
7856static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7857 QualType DesiredBase,
7858 bool &AnyDependentBases) {
7859 // Check whether the named type is a direct base class.
7860 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7861 for (auto &Base : Derived->bases()) {
7862 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7863 if (CanonicalDesiredBase == BaseType)
7864 return &Base;
7865 if (BaseType->isDependentType())
7866 AnyDependentBases = true;
7867 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007868 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007869}
7870
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007871namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007872class UsingValidatorCCC : public CorrectionCandidateCallback {
7873public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007874 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007875 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007876 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007877 IsInstantiation(IsInstantiation), OldNNS(NNS),
7878 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007879
Craig Toppera798a9d2014-03-02 09:32:10 +00007880 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007881 NamedDecl *ND = Candidate.getCorrectionDecl();
7882
7883 // Keywords are not valid here.
7884 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007885 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007886
7887 // Completely unqualified names are invalid for a 'using' declaration.
7888 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7889 return false;
7890
Richard Smith09d5b3a2014-05-01 00:35:04 +00007891 if (RequireMemberOf) {
7892 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7893 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7894 // No-one ever wants a using-declaration to name an injected-class-name
7895 // of a base class, unless they're declaring an inheriting constructor.
7896 ASTContext &Ctx = ND->getASTContext();
7897 if (!Ctx.getLangOpts().CPlusPlus11)
7898 return false;
7899 QualType FoundType = Ctx.getRecordType(FoundRecord);
7900
7901 // Check that the injected-class-name is named as a member of its own
7902 // type; we don't want to suggest 'using Derived::Base;', since that
7903 // means something else.
7904 NestedNameSpecifier *Specifier =
7905 Candidate.WillReplaceSpecifier()
7906 ? Candidate.getCorrectionSpecifier()
7907 : OldNNS;
7908 if (!Specifier->getAsType() ||
7909 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7910 return false;
7911
7912 // Check that this inheriting constructor declaration actually names a
7913 // direct base class of the current class.
7914 bool AnyDependentBases = false;
7915 if (!findDirectBaseWithType(RequireMemberOf,
7916 Ctx.getRecordType(FoundRecord),
7917 AnyDependentBases) &&
7918 !AnyDependentBases)
7919 return false;
7920 } else {
7921 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7922 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7923 return false;
7924
7925 // FIXME: Check that the base class member is accessible?
7926 }
7927 }
7928
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007929 if (isa<TypeDecl>(ND))
7930 return HasTypenameKeyword || !IsInstantiation;
7931
7932 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007933 }
7934
7935private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007936 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007937 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007938 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007939 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007940};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007941} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007942
John McCalle61f2ba2009-11-18 02:36:19 +00007943/// Builds a using declaration.
7944///
7945/// \param IsInstantiation - Whether this call arises from an
7946/// instantiation of an unresolved using declaration. We treat
7947/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007948NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7949 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007950 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007951 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007952 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007953 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007954 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007955 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007956 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007957 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007958 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007959
Anders Carlssonf038fc22009-08-28 05:49:21 +00007960 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007961
Anders Carlsson59140b32009-08-28 03:16:11 +00007962 if (SS.isEmpty()) {
7963 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007964 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007965 }
Mike Stump11289f42009-09-09 15:08:12 +00007966
John McCall84d87672009-12-10 09:41:52 +00007967 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007968 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007969 ForRedeclaration);
7970 Previous.setHideTags(false);
7971 if (S) {
7972 LookupName(Previous, S);
7973
7974 // It is really dumb that we have to do this.
7975 LookupResult::Filter F = Previous.makeFilter();
7976 while (F.hasNext()) {
7977 NamedDecl *D = F.next();
7978 if (!isDeclInScope(D, CurContext, S))
7979 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007980 // If we found a local extern declaration that's not ordinarily visible,
7981 // and this declaration is being added to a non-block scope, ignore it.
7982 // We're only checking for scope conflicts here, not also for violations
7983 // of the linkage rules.
7984 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7985 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7986 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007987 }
7988 F.done();
7989 } else {
7990 assert(IsInstantiation && "no scope in non-instantiation");
7991 assert(CurContext->isRecord() && "scope not record in instantiation");
7992 LookupQualifiedName(Previous, CurContext);
7993 }
7994
John McCall84d87672009-12-10 09:41:52 +00007995 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007996 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7997 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007998 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007999
8000 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008001 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008002 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008003
John McCall84c16cf2009-11-12 03:15:40 +00008004 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008005 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008006 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008007 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008008 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008009 // FIXME: not all declaration name kinds are legal here
8010 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8011 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008012 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008013 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008014 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008015 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8016 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008017 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008018 D->setAccess(AS);
8019 CurContext->addDecl(D);
8020 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008021 }
John McCallb96ec562009-12-04 22:46:56 +00008022
Richard Smith09d5b3a2014-05-01 00:35:04 +00008023 auto Build = [&](bool Invalid) {
8024 UsingDecl *UD =
8025 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8026 HasTypenameKeyword);
8027 UD->setAccess(AS);
8028 CurContext->addDecl(UD);
8029 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008030 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008031 };
8032 auto BuildInvalid = [&]{ return Build(true); };
8033 auto BuildValid = [&]{ return Build(false); };
8034
8035 if (RequireCompleteDeclContext(SS, LookupContext))
8036 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008037
Richard Smith23d55872012-04-02 01:30:27 +00008038 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00008039 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00008040 UsingDecl *UD = BuildValid();
8041 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00008042 return UD;
8043 }
8044
8045 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00008046
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008047 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008048
John McCall3969e302009-12-08 07:46:18 +00008049 // Unlike most lookups, we don't always want to hide tag
8050 // declarations: tag names are visible through the using declaration
8051 // even if hidden by ordinary names, *except* in a dependent context
8052 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008053 if (!IsInstantiation)
8054 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008055
John McCall5dadb652012-04-07 03:04:20 +00008056 // For the purposes of this lookup, we have a base object type
8057 // equal to that of the current context.
8058 if (CurContext->isRecord()) {
8059 R.setBaseObjectType(
8060 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8061 }
8062
John McCall27b18f82009-11-17 02:14:36 +00008063 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008064
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008065 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00008066 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008067 if (TypoCorrection Corrected = CorrectTypo(
8068 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8069 llvm::make_unique<UsingValidatorCCC>(
8070 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8071 dyn_cast<CXXRecordDecl>(CurContext)),
8072 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008073 // We reject any correction for which ND would be NULL.
8074 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008075
Richard Smithf9b15102013-08-17 00:46:16 +00008076 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008077 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008078 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8079 << NameInfo.getName() << LookupContext << 0
8080 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008081
8082 // If we corrected to an inheriting constructor, handle it as one.
8083 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8084 if (RD && RD->isInjectedClassName()) {
8085 // Fix up the information we'll use to build the using declaration.
8086 if (Corrected.WillReplaceSpecifier()) {
8087 NestedNameSpecifierLocBuilder Builder;
8088 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8089 QualifierLoc.getSourceRange());
8090 QualifierLoc = Builder.getWithLocInContext(Context);
8091 }
8092
8093 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8094 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008095 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008096
8097 // Build it and process it as an inheriting constructor.
8098 UsingDecl *UD = BuildValid();
8099 CheckInheritingConstructorUsingDecl(UD);
8100 return UD;
8101 }
8102
8103 // FIXME: Pick up all the declarations if we found an overloaded function.
8104 R.setLookupName(Corrected.getCorrection());
8105 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008106 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008107 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008108 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008109 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008110 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008111 }
8112
Richard Smith09d5b3a2014-05-01 00:35:04 +00008113 if (R.isAmbiguous())
8114 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008115
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008116 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008117 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008118 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008119 Diag(IdentLoc, diag::err_using_typename_non_type);
8120 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8121 Diag((*I)->getUnderlyingDecl()->getLocation(),
8122 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008123 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008124 }
8125 } else {
8126 // If we asked for a non-typename and we got a type, error out,
8127 // but only if this is an instantiation of an unresolved using
8128 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008129 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008130 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8131 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008132 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008133 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008134 }
8135
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008136 // C++0x N2914 [namespace.udecl]p6:
8137 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008138 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008139 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8140 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008141 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008142 }
Mike Stump11289f42009-09-09 15:08:12 +00008143
Richard Smith09d5b3a2014-05-01 00:35:04 +00008144 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008145 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008146 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008147 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8148 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008149 }
John McCall3f746822009-11-17 05:59:44 +00008150
8151 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008152}
8153
Sebastian Redl08905022011-02-05 19:23:19 +00008154/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008155bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008156 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008157
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008158 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008159 assert(SourceType &&
8160 "Using decl naming constructor doesn't have type in scope spec.");
8161 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8162
8163 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008164 bool AnyDependentBases = false;
8165 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8166 AnyDependentBases);
8167 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008168 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008169 diag::err_using_decl_constructor_not_in_direct_base)
8170 << UD->getNameInfo().getSourceRange()
8171 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008172 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008173 return true;
8174 }
8175
Richard Smith09d5b3a2014-05-01 00:35:04 +00008176 if (Base)
8177 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008178
8179 return false;
8180}
8181
John McCall84d87672009-12-10 09:41:52 +00008182/// Checks that the given using declaration is not an invalid
8183/// redeclaration. Note that this is checking only for the using decl
8184/// itself, not for any ill-formedness among the UsingShadowDecls.
8185bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008186 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008187 const CXXScopeSpec &SS,
8188 SourceLocation NameLoc,
8189 const LookupResult &Prev) {
8190 // C++03 [namespace.udecl]p8:
8191 // C++0x [namespace.udecl]p10:
8192 // A using-declaration is a declaration and can therefore be used
8193 // repeatedly where (and only where) multiple declarations are
8194 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008195 //
John McCall032092f2010-11-29 18:01:58 +00008196 // That's in non-member contexts.
8197 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008198 return false;
8199
Aaron Ballman4a979672014-01-03 13:56:08 +00008200 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008201
8202 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8203 NamedDecl *D = *I;
8204
8205 bool DTypename;
8206 NestedNameSpecifier *DQual;
8207 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008208 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008209 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008210 } else if (UnresolvedUsingValueDecl *UD
8211 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8212 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008213 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008214 } else if (UnresolvedUsingTypenameDecl *UD
8215 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8216 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008217 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008218 } else continue;
8219
8220 // using decls differ if one says 'typename' and the other doesn't.
8221 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008222 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008223
8224 // using decls differ if they name different scopes (but note that
8225 // template instantiation can cause this check to trigger when it
8226 // didn't before instantiation).
8227 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8228 Context.getCanonicalNestedNameSpecifier(DQual))
8229 continue;
8230
8231 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008232 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008233 return true;
8234 }
8235
8236 return false;
8237}
8238
John McCall3969e302009-12-08 07:46:18 +00008239
John McCallb96ec562009-12-04 22:46:56 +00008240/// Checks that the given nested-name qualifier used in a using decl
8241/// in the current context is appropriately related to the current
8242/// scope. If an error is found, diagnoses it and returns true.
8243bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8244 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008245 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008246 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008247 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008248
John McCall3969e302009-12-08 07:46:18 +00008249 if (!CurContext->isRecord()) {
8250 // C++03 [namespace.udecl]p3:
8251 // C++0x [namespace.udecl]p8:
8252 // A using-declaration for a class member shall be a member-declaration.
8253
8254 // If we weren't able to compute a valid scope, it must be a
8255 // dependent class scope.
8256 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008257 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008258 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008259 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008260
John McCall3969e302009-12-08 07:46:18 +00008261 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8262 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008263
8264 // If we have a complete, non-dependent source type, try to suggest a
8265 // way to get the same effect.
8266 if (!RD)
8267 return true;
8268
8269 // Find what this using-declaration was referring to.
8270 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8271 R.setHideTags(false);
8272 R.suppressDiagnostics();
8273 LookupQualifiedName(R, RD);
8274
8275 if (R.getAsSingle<TypeDecl>()) {
8276 if (getLangOpts().CPlusPlus11) {
8277 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8278 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8279 << 0 // alias declaration
8280 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8281 NameInfo.getName().getAsString() +
8282 " = ");
8283 } else {
8284 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8285 SourceLocation InsertLoc =
8286 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8287 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8288 << 1 // typedef declaration
8289 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8290 << FixItHint::CreateInsertion(
8291 InsertLoc, " " + NameInfo.getName().getAsString());
8292 }
8293 } else if (R.getAsSingle<VarDecl>()) {
8294 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8295 // repeating the type of the static data member here.
8296 FixItHint FixIt;
8297 if (getLangOpts().CPlusPlus11) {
8298 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8299 FixIt = FixItHint::CreateReplacement(
8300 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8301 }
8302
8303 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8304 << 2 // reference declaration
8305 << FixIt;
8306 }
John McCall3969e302009-12-08 07:46:18 +00008307 return true;
8308 }
8309
8310 // Otherwise, everything is known to be fine.
8311 return false;
8312 }
8313
8314 // The current scope is a record.
8315
8316 // If the named context is dependent, we can't decide much.
8317 if (!NamedContext) {
8318 // FIXME: in C++0x, we can diagnose if we can prove that the
8319 // nested-name-specifier does not refer to a base class, which is
8320 // still possible in some cases.
8321
8322 // Otherwise we have to conservatively report that things might be
8323 // okay.
8324 return false;
8325 }
8326
8327 if (!NamedContext->isRecord()) {
8328 // Ideally this would point at the last name in the specifier,
8329 // but we don't have that level of source info.
8330 Diag(SS.getRange().getBegin(),
8331 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008332 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008333 return true;
8334 }
8335
Douglas Gregor7c842292010-12-21 07:41:49 +00008336 if (!NamedContext->isDependentContext() &&
8337 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8338 return true;
8339
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008340 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008341 // C++0x [namespace.udecl]p3:
8342 // In a using-declaration used as a member-declaration, the
8343 // nested-name-specifier shall name a base class of the class
8344 // being defined.
8345
8346 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8347 cast<CXXRecordDecl>(NamedContext))) {
8348 if (CurContext == NamedContext) {
8349 Diag(NameLoc,
8350 diag::err_using_decl_nested_name_specifier_is_current_class)
8351 << SS.getRange();
8352 return true;
8353 }
8354
8355 Diag(SS.getRange().getBegin(),
8356 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008357 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008358 << cast<CXXRecordDecl>(CurContext)
8359 << SS.getRange();
8360 return true;
8361 }
8362
8363 return false;
8364 }
8365
8366 // C++03 [namespace.udecl]p4:
8367 // A using-declaration used as a member-declaration shall refer
8368 // to a member of a base class of the class being defined [etc.].
8369
8370 // Salient point: SS doesn't have to name a base class as long as
8371 // lookup only finds members from base classes. Therefore we can
8372 // diagnose here only if we can prove that that can't happen,
8373 // i.e. if the class hierarchies provably don't intersect.
8374
8375 // TODO: it would be nice if "definitely valid" results were cached
8376 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8377 // need to be repeated.
8378
8379 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008380 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008381
8382 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8383 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8384 Data->Bases.insert(Base);
8385 return true;
8386 }
8387
8388 bool hasDependentBases(const CXXRecordDecl *Class) {
8389 return !Class->forallBases(collect, this);
8390 }
8391
8392 /// Returns true if the base is dependent or is one of the
8393 /// accumulated base classes.
8394 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8395 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8396 return !Data->Bases.count(Base);
8397 }
8398
8399 bool mightShareBases(const CXXRecordDecl *Class) {
8400 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8401 }
8402 };
8403
8404 UserData Data;
8405
8406 // Returns false if we find a dependent base.
8407 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8408 return false;
8409
8410 // Returns false if the class has a dependent base or if it or one
8411 // of its bases is present in the base set of the current context.
8412 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8413 return false;
8414
8415 Diag(SS.getRange().getBegin(),
8416 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008417 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008418 << cast<CXXRecordDecl>(CurContext)
8419 << SS.getRange();
8420
8421 return true;
John McCallb96ec562009-12-04 22:46:56 +00008422}
8423
Richard Smithdda56e42011-04-15 14:24:37 +00008424Decl *Sema::ActOnAliasDeclaration(Scope *S,
8425 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008426 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008427 SourceLocation UsingLoc,
8428 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008429 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008430 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008431 // Skip up to the relevant declaration scope.
8432 while (S->getFlags() & Scope::TemplateParamScope)
8433 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008434 assert((S->getFlags() & Scope::DeclScope) &&
8435 "got alias-declaration outside of declaration scope");
8436
8437 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008438 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008439
8440 bool Invalid = false;
8441 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008442 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008443 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008444
8445 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008446 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008447
8448 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008449 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008450 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008451 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8452 TInfo->getTypeLoc().getBeginLoc());
8453 }
Richard Smithdda56e42011-04-15 14:24:37 +00008454
8455 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8456 LookupName(Previous, S);
8457
8458 // Warn about shadowing the name of a template parameter.
8459 if (Previous.isSingleResult() &&
8460 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008461 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008462 Previous.clear();
8463 }
8464
8465 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8466 "name in alias declaration must be an identifier");
8467 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8468 Name.StartLocation,
8469 Name.Identifier, TInfo);
8470
8471 NewTD->setAccess(AS);
8472
8473 if (Invalid)
8474 NewTD->setInvalidDecl();
8475
Richard Smith54ecd982013-02-20 19:22:51 +00008476 ProcessDeclAttributeList(S, NewTD, AttrList);
8477
Richard Smith3f1b5d02011-05-05 21:57:07 +00008478 CheckTypedefForVariablyModifiedType(S, NewTD);
8479 Invalid |= NewTD->isInvalidDecl();
8480
Richard Smithdda56e42011-04-15 14:24:37 +00008481 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008482
8483 NamedDecl *NewND;
8484 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008485 TypeAliasTemplateDecl *OldDecl = nullptr;
8486 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008487
8488 if (TemplateParamLists.size() != 1) {
8489 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008490 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8491 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008492 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008493 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008494
8495 // Only consider previous declarations in the same scope.
8496 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8497 /*ExplicitInstantiationOrSpecialization*/false);
8498 if (!Previous.empty()) {
8499 Redeclaration = true;
8500
8501 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8502 if (!OldDecl && !Invalid) {
8503 Diag(UsingLoc, diag::err_redefinition_different_kind)
8504 << Name.Identifier;
8505
8506 NamedDecl *OldD = Previous.getRepresentativeDecl();
8507 if (OldD->getLocation().isValid())
8508 Diag(OldD->getLocation(), diag::note_previous_definition);
8509
8510 Invalid = true;
8511 }
8512
8513 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8514 if (TemplateParameterListsAreEqual(TemplateParams,
8515 OldDecl->getTemplateParameters(),
8516 /*Complain=*/true,
8517 TPL_TemplateMatch))
8518 OldTemplateParams = OldDecl->getTemplateParameters();
8519 else
8520 Invalid = true;
8521
8522 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8523 if (!Invalid &&
8524 !Context.hasSameType(OldTD->getUnderlyingType(),
8525 NewTD->getUnderlyingType())) {
8526 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8527 // but we can't reasonably accept it.
8528 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8529 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8530 if (OldTD->getLocation().isValid())
8531 Diag(OldTD->getLocation(), diag::note_previous_definition);
8532 Invalid = true;
8533 }
8534 }
8535 }
8536
8537 // Merge any previous default template arguments into our parameters,
8538 // and check the parameter list.
8539 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8540 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008541 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008542
8543 TypeAliasTemplateDecl *NewDecl =
8544 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8545 Name.Identifier, TemplateParams,
8546 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008547 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008548
8549 NewDecl->setAccess(AS);
8550
8551 if (Invalid)
8552 NewDecl->setInvalidDecl();
8553 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008554 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008555
8556 NewND = NewDecl;
8557 } else {
8558 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8559 NewND = NewTD;
8560 }
Richard Smithdda56e42011-04-15 14:24:37 +00008561
8562 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008563 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008564
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008565 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008566 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008567}
8568
Richard Smithf4634362014-09-03 23:11:22 +00008569Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8570 SourceLocation AliasLoc,
8571 IdentifierInfo *Alias, CXXScopeSpec &SS,
8572 SourceLocation IdentLoc,
8573 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008574
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008575 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008576 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8577 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008578
John McCall27b18f82009-11-17 02:14:36 +00008579 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008580 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008581
John McCall9f3059a2009-10-09 21:13:30 +00008582 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008583 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008584 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008585 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008586 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008587 }
Richard Smithf4634362014-09-03 23:11:22 +00008588 assert(!R.isAmbiguous() && !R.empty());
8589
8590 // Check if we have a previous declaration with the same name.
8591 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8592 ForRedeclaration);
8593 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8594 PrevDecl = nullptr;
8595
Aaron Ballman43f40102014-11-14 22:34:56 +00008596 NamedDecl *ND = R.getFoundDecl();
8597
Richard Smithf4634362014-09-03 23:11:22 +00008598 if (PrevDecl) {
8599 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8600 // We already have an alias with the same name that points to the same
8601 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008602 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008603 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8604 << Alias;
8605 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8606 << AD->getNamespace();
8607 return nullptr;
8608 }
8609 } else {
8610 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8611 ? diag::err_redefinition
8612 : diag::err_redefinition_different_kind;
8613 Diag(AliasLoc, DiagID) << Alias;
8614 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8615 return nullptr;
8616 }
8617 }
Mike Stump11289f42009-09-09 15:08:12 +00008618
Nico Riecke50e59a2014-11-24 17:29:52 +00008619 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008620 DiagnoseUseOfDecl(ND, IdentLoc);
8621
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008622 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008623 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008624 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008625 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008626 if (PrevDecl)
8627 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008628
John McCalld8d0d432010-02-16 06:53:13 +00008629 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008630 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008631}
8632
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008633Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008634Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8635 CXXMethodDecl *MD) {
8636 CXXRecordDecl *ClassDecl = MD->getParent();
8637
Douglas Gregor6d880b12010-07-01 22:31:05 +00008638 // C++ [except.spec]p14:
8639 // An implicitly declared special member function (Clause 12) shall have an
8640 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008641 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008642 if (ClassDecl->isInvalidDecl())
8643 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008644
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008645 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008646 for (const auto &B : ClassDecl->bases()) {
8647 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008648 continue;
8649
Aaron Ballman574705e2014-03-13 15:41:46 +00008650 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008651 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008652 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8653 // If this is a deleted function, add it anyway. This might be conformant
8654 // with the standard. This might not. I'm not sure. It might not matter.
8655 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008656 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008657 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008658 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008659
8660 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008661 for (const auto &B : ClassDecl->vbases()) {
8662 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008663 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008664 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8665 // If this is a deleted function, add it anyway. This might be conformant
8666 // with the standard. This might not. I'm not sure. It might not matter.
8667 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008668 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008669 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008670 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008671
8672 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008673 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008674 if (F->hasInClassInitializer()) {
8675 if (Expr *E = F->getInClassInitializer())
8676 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008677 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008678 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008679 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8680 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8681 // If this is a deleted function, add it anyway. This might be conformant
8682 // with the standard. This might not. I'm not sure. It might not matter.
8683 // In particular, the problem is that this function never gets called. It
8684 // might just be ill-formed because this function attempts to refer to
8685 // a deleted function here.
8686 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008687 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008688 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008689 }
John McCalldb40c7f2010-12-14 08:05:40 +00008690
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008691 return ExceptSpec;
8692}
8693
Richard Smithc2bc61b2013-03-18 21:12:30 +00008694Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008695Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8696 CXXRecordDecl *ClassDecl = CD->getParent();
8697
8698 // C++ [except.spec]p14:
8699 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008700 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008701 if (ClassDecl->isInvalidDecl())
8702 return ExceptSpec;
8703
8704 // Inherited constructor.
8705 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8706 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8707 // FIXME: Copying or moving the parameters could add extra exceptions to the
8708 // set, as could the default arguments for the inherited constructor. This
8709 // will be addressed when we implement the resolution of core issue 1351.
8710 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8711
8712 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008713 for (const auto &B : ClassDecl->bases()) {
8714 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008715 continue;
8716
Aaron Ballman574705e2014-03-13 15:41:46 +00008717 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008718 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8719 if (BaseClassDecl == InheritedDecl)
8720 continue;
8721 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8722 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008723 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008724 }
8725 }
8726
8727 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008728 for (const auto &B : ClassDecl->vbases()) {
8729 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008730 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8731 if (BaseClassDecl == InheritedDecl)
8732 continue;
8733 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8734 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008735 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008736 }
8737 }
8738
8739 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008740 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008741 if (F->hasInClassInitializer()) {
8742 if (Expr *E = F->getInClassInitializer())
8743 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008744 } else if (const RecordType *RecordTy
8745 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8746 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8747 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8748 if (Constructor)
8749 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8750 }
8751 }
8752
Richard Smithc2bc61b2013-03-18 21:12:30 +00008753 return ExceptSpec;
8754}
8755
Richard Smith8bf22e52012-11-29 01:34:07 +00008756namespace {
8757/// RAII object to register a special member as being currently declared.
8758struct DeclaringSpecialMember {
8759 Sema &S;
8760 Sema::SpecialMemberDecl D;
8761 bool WasAlreadyBeingDeclared;
8762
8763 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8764 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008765 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008766 if (WasAlreadyBeingDeclared)
8767 // This almost never happens, but if it does, ensure that our cache
8768 // doesn't contain a stale result.
8769 S.SpecialMemberCache.clear();
8770
8771 // FIXME: Register a note to be produced if we encounter an error while
8772 // declaring the special member.
8773 }
8774 ~DeclaringSpecialMember() {
8775 if (!WasAlreadyBeingDeclared)
8776 S.SpecialMembersBeingDeclared.erase(D);
8777 }
8778
8779 /// \brief Are we already trying to declare this special member?
8780 bool isAlreadyBeingDeclared() const {
8781 return WasAlreadyBeingDeclared;
8782 }
8783};
8784}
8785
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008786CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8787 CXXRecordDecl *ClassDecl) {
8788 // C++ [class.ctor]p5:
8789 // A default constructor for a class X is a constructor of class X
8790 // that can be called without an argument. If there is no
8791 // user-declared constructor for class X, a default constructor is
8792 // implicitly declared. An implicitly-declared default constructor
8793 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008794 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008795 "Should not build implicit default constructor!");
8796
Richard Smith8bf22e52012-11-29 01:34:07 +00008797 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8798 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008799 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008800
Richard Smithb5800092012-06-10 05:43:50 +00008801 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8802 CXXDefaultConstructor,
8803 false);
8804
Douglas Gregor6d880b12010-07-01 22:31:05 +00008805 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008806 CanQualType ClassType
8807 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008808 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008809 DeclarationName Name
8810 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008811 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008812 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008813 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8814 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8815 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008816 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008817 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008818
8819 if (getLangOpts().CUDA) {
8820 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8821 DefaultCon,
8822 /* ConstRHS */ false,
8823 /* Diagnose */ false);
8824 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008825
8826 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008827 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008828 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008829
Richard Smith6b02d462012-12-08 08:32:28 +00008830 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8831 // constructors is easy to compute.
8832 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8833
8834 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008835 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008836
Douglas Gregor9672f922010-07-03 00:47:00 +00008837 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008838 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008839
Douglas Gregor0be31a22010-07-02 17:43:08 +00008840 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008841 PushOnScopeChains(DefaultCon, S, false);
8842 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008843
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008844 return DefaultCon;
8845}
8846
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008847void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8848 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008849 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008850 !Constructor->doesThisDeclarationHaveABody() &&
8851 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008852 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008853
Anders Carlsson423f5d82010-04-23 16:04:08 +00008854 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008855 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008856
Eli Friedmaneaf34142012-10-18 20:14:08 +00008857 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008858 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008859 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008860 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008861 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008862 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008863 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008864 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008865 }
Douglas Gregor73193272010-09-20 16:48:21 +00008866
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008867 // The exception specification is needed because we are defining the
8868 // function.
8869 ResolveExceptionSpec(CurrentLocation,
8870 Constructor->getType()->castAs<FunctionProtoType>());
8871
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008872 SourceLocation Loc = Constructor->getLocEnd().isValid()
8873 ? Constructor->getLocEnd()
8874 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008875 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008876
Eli Friedman276dd182013-09-05 00:02:25 +00008877 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008878 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008879
8880 if (ASTMutationListener *L = getASTMutationListener()) {
8881 L->CompletedImplicitDefinition(Constructor);
8882 }
Richard Trieuef64e942013-10-25 00:56:00 +00008883
8884 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008885}
8886
Richard Smith938f40b2011-06-11 17:19:42 +00008887void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008888 // Perform any delayed checks on exception specifications.
8889 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008890}
8891
Richard Smith185be182013-04-10 05:48:59 +00008892namespace {
8893/// Information on inheriting constructors to declare.
8894class InheritingConstructorInfo {
8895public:
8896 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8897 : SemaRef(SemaRef), Derived(Derived) {
8898 // Mark the constructors that we already have in the derived class.
8899 //
8900 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8901 // unless there is a user-declared constructor with the same signature in
8902 // the class where the using-declaration appears.
8903 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8904 }
8905
8906 void inheritAll(CXXRecordDecl *RD) {
8907 visitAll(RD, &InheritingConstructorInfo::inherit);
8908 }
8909
8910private:
8911 /// Information about an inheriting constructor.
8912 struct InheritingConstructor {
8913 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008914 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008915
8916 /// If \c true, a constructor with this signature is already declared
8917 /// in the derived class.
8918 bool DeclaredInDerived;
8919
8920 /// The constructor which is inherited.
8921 const CXXConstructorDecl *BaseCtor;
8922
8923 /// The derived constructor we declared.
8924 CXXConstructorDecl *DerivedCtor;
8925 };
8926
8927 /// Inheriting constructors with a given canonical type. There can be at
8928 /// most one such non-template constructor, and any number of templated
8929 /// constructors.
8930 struct InheritingConstructorsForType {
8931 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008932 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8933 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008934
8935 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8936 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8937 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8938 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8939 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8940 false, S.TPL_TemplateMatch))
8941 return Templates[I].second;
8942 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8943 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008944 }
Richard Smith185be182013-04-10 05:48:59 +00008945
8946 return NonTemplate;
8947 }
8948 };
8949
8950 /// Get or create the inheriting constructor record for a constructor.
8951 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8952 QualType CtorType) {
8953 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8954 .getEntry(SemaRef, Ctor);
8955 }
8956
8957 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8958
8959 /// Process all constructors for a class.
8960 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008961 for (const auto *Ctor : RD->ctors())
8962 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008963 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8964 I(RD->decls_begin()), E(RD->decls_end());
8965 I != E; ++I) {
8966 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8967 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8968 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008969 }
8970 }
Richard Smith185be182013-04-10 05:48:59 +00008971
8972 /// Note that a constructor (or constructor template) was declared in Derived.
8973 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8974 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8975 }
8976
8977 /// Inherit a single constructor.
8978 void inherit(const CXXConstructorDecl *Ctor) {
8979 const FunctionProtoType *CtorType =
8980 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00008981 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00008982 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8983
8984 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8985
8986 // Core issue (no number yet): the ellipsis is always discarded.
8987 if (EPI.Variadic) {
8988 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8989 SemaRef.Diag(Ctor->getLocation(),
8990 diag::note_using_decl_constructor_ellipsis);
8991 EPI.Variadic = false;
8992 }
8993
8994 // Declare a constructor for each number of parameters.
8995 //
8996 // C++11 [class.inhctor]p1:
8997 // The candidate set of inherited constructors from the class X named in
8998 // the using-declaration consists of [... modulo defects ...] for each
8999 // constructor or constructor template of X, the set of constructors or
9000 // constructor templates that results from omitting any ellipsis parameter
9001 // specification and successively omitting parameters with a default
9002 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009003 unsigned MinParams = minParamsToInherit(Ctor);
9004 unsigned Params = Ctor->getNumParams();
9005 if (Params >= MinParams) {
9006 do
9007 declareCtor(UsingLoc, Ctor,
9008 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009009 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009010 while (Params > MinParams &&
9011 Ctor->getParamDecl(--Params)->hasDefaultArg());
9012 }
Richard Smith185be182013-04-10 05:48:59 +00009013 }
9014
9015 /// Find the using-declaration which specified that we should inherit the
9016 /// constructors of \p Base.
9017 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9018 // No fancy lookup required; just look for the base constructor name
9019 // directly within the derived class.
9020 ASTContext &Context = SemaRef.Context;
9021 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9022 Context.getCanonicalType(Context.getRecordType(Base)));
9023 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
9024 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9025 }
9026
9027 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9028 // C++11 [class.inhctor]p3:
9029 // [F]or each constructor template in the candidate set of inherited
9030 // constructors, a constructor template is implicitly declared
9031 if (Ctor->getDescribedFunctionTemplate())
9032 return 0;
9033
9034 // For each non-template constructor in the candidate set of inherited
9035 // constructors other than a constructor having no parameters or a
9036 // copy/move constructor having a single parameter, a constructor is
9037 // implicitly declared [...]
9038 if (Ctor->getNumParams() == 0)
9039 return 1;
9040 if (Ctor->isCopyOrMoveConstructor())
9041 return 2;
9042
9043 // Per discussion on core reflector, never inherit a constructor which
9044 // would become a default, copy, or move constructor of Derived either.
9045 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9046 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9047 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9048 }
9049
9050 /// Declare a single inheriting constructor, inheriting the specified
9051 /// constructor, with the given type.
9052 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9053 QualType DerivedType) {
9054 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9055
9056 // C++11 [class.inhctor]p3:
9057 // ... a constructor is implicitly declared with the same constructor
9058 // characteristics unless there is a user-declared constructor with
9059 // the same signature in the class where the using-declaration appears
9060 if (Entry.DeclaredInDerived)
9061 return;
9062
9063 // C++11 [class.inhctor]p7:
9064 // If two using-declarations declare inheriting constructors with the
9065 // same signature, the program is ill-formed
9066 if (Entry.DerivedCtor) {
9067 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9068 // Only diagnose this once per constructor.
9069 if (Entry.DerivedCtor->isInvalidDecl())
9070 return;
9071 Entry.DerivedCtor->setInvalidDecl();
9072
9073 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9074 SemaRef.Diag(BaseCtor->getLocation(),
9075 diag::note_using_decl_constructor_conflict_current_ctor);
9076 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9077 diag::note_using_decl_constructor_conflict_previous_ctor);
9078 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9079 diag::note_using_decl_constructor_conflict_previous_using);
9080 } else {
9081 // Core issue (no number): if the same inheriting constructor is
9082 // produced by multiple base class constructors from the same base
9083 // class, the inheriting constructor is defined as deleted.
9084 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9085 }
9086
9087 return;
9088 }
9089
9090 ASTContext &Context = SemaRef.Context;
9091 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9092 Context.getCanonicalType(Context.getRecordType(Derived)));
9093 DeclarationNameInfo NameInfo(Name, UsingLoc);
9094
Craig Topperc3ec1492014-05-26 06:22:03 +00009095 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009096 if (const FunctionTemplateDecl *FTD =
9097 BaseCtor->getDescribedFunctionTemplate()) {
9098 TemplateParams = FTD->getTemplateParameters();
9099 // We're reusing template parameters from a different DeclContext. This
9100 // is questionable at best, but works out because the template depth in
9101 // both places is guaranteed to be 0.
9102 // FIXME: Rebuild the template parameters in the new context, and
9103 // transform the function type to refer to them.
9104 }
9105
9106 // Build type source info pointing at the using-declaration. This is
9107 // required by template instantiation.
9108 TypeSourceInfo *TInfo =
9109 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9110 FunctionProtoTypeLoc ProtoLoc =
9111 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9112
9113 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9114 Context, Derived, UsingLoc, NameInfo, DerivedType,
9115 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9116 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9117
9118 // Build an unevaluated exception specification for this constructor.
9119 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9120 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009121 EPI.ExceptionSpec.Type = EST_Unevaluated;
9122 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009123 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009124 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009125
9126 // Build the parameter declarations.
9127 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009128 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009129 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009130 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009131 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009132 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9133 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009134 PD->setScopeInfo(0, I);
9135 PD->setImplicit();
9136 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009137 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009138 }
9139
9140 // Set up the new constructor.
9141 DerivedCtor->setAccess(BaseCtor->getAccess());
9142 DerivedCtor->setParams(ParamDecls);
9143 DerivedCtor->setInheritedConstructor(BaseCtor);
9144 if (BaseCtor->isDeleted())
9145 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9146
9147 // If this is a constructor template, build the template declaration.
9148 if (TemplateParams) {
9149 FunctionTemplateDecl *DerivedTemplate =
9150 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9151 TemplateParams, DerivedCtor);
9152 DerivedTemplate->setAccess(BaseCtor->getAccess());
9153 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9154 Derived->addDecl(DerivedTemplate);
9155 } else {
9156 Derived->addDecl(DerivedCtor);
9157 }
9158
9159 Entry.BaseCtor = BaseCtor;
9160 Entry.DerivedCtor = DerivedCtor;
9161 }
9162
9163 Sema &SemaRef;
9164 CXXRecordDecl *Derived;
9165 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9166 MapType Map;
9167};
9168}
9169
9170void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9171 // Defer declaring the inheriting constructors until the class is
9172 // instantiated.
9173 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009174 return;
9175
Richard Smith185be182013-04-10 05:48:59 +00009176 // Find base classes from which we might inherit constructors.
9177 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009178 for (const auto &BaseIt : ClassDecl->bases())
9179 if (BaseIt.getInheritConstructors())
9180 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009181
Richard Smith185be182013-04-10 05:48:59 +00009182 // Go no further if we're not inheriting any constructors.
9183 if (InheritedBases.empty())
9184 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009185
Richard Smith185be182013-04-10 05:48:59 +00009186 // Declare the inherited constructors.
9187 InheritingConstructorInfo ICI(*this, ClassDecl);
9188 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9189 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009190}
9191
Richard Smithc2bc61b2013-03-18 21:12:30 +00009192void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9193 CXXConstructorDecl *Constructor) {
9194 CXXRecordDecl *ClassDecl = Constructor->getParent();
9195 assert(Constructor->getInheritedConstructor() &&
9196 !Constructor->doesThisDeclarationHaveABody() &&
9197 !Constructor->isDeleted());
9198
9199 SynthesizedFunctionScope Scope(*this, Constructor);
9200 DiagnosticErrorTrap Trap(Diags);
9201 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9202 Trap.hasErrorOccurred()) {
9203 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9204 << Context.getTagDeclType(ClassDecl);
9205 Constructor->setInvalidDecl();
9206 return;
9207 }
9208
9209 SourceLocation Loc = Constructor->getLocation();
9210 Constructor->setBody(new (Context) CompoundStmt(Loc));
9211
Eli Friedman276dd182013-09-05 00:02:25 +00009212 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009213 MarkVTableUsed(CurrentLocation, ClassDecl);
9214
9215 if (ASTMutationListener *L = getASTMutationListener()) {
9216 L->CompletedImplicitDefinition(Constructor);
9217 }
9218}
9219
9220
Alexis Huntf91729462011-05-12 22:46:25 +00009221Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009222Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9223 CXXRecordDecl *ClassDecl = MD->getParent();
9224
Douglas Gregorf1203042010-07-01 19:09:28 +00009225 // C++ [except.spec]p14:
9226 // An implicitly declared special member function (Clause 12) shall have
9227 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009228 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009229 if (ClassDecl->isInvalidDecl())
9230 return ExceptSpec;
9231
Douglas Gregorf1203042010-07-01 19:09:28 +00009232 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009233 for (const auto &B : ClassDecl->bases()) {
9234 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009235 continue;
9236
Aaron Ballman574705e2014-03-13 15:41:46 +00009237 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9238 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009239 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009240 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009241
Douglas Gregorf1203042010-07-01 19:09:28 +00009242 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009243 for (const auto &B : ClassDecl->vbases()) {
9244 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9245 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009246 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009247 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009248
Douglas Gregorf1203042010-07-01 19:09:28 +00009249 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009250 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009251 if (const RecordType *RecordTy
9252 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009253 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009254 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009255 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009256
Alexis Huntf91729462011-05-12 22:46:25 +00009257 return ExceptSpec;
9258}
9259
9260CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9261 // C++ [class.dtor]p2:
9262 // If a class has no user-declared destructor, a destructor is
9263 // declared implicitly. An implicitly-declared destructor is an
9264 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009265 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009266
Richard Smith8bf22e52012-11-29 01:34:07 +00009267 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9268 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009269 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009270
Douglas Gregor7454c562010-07-02 20:37:36 +00009271 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009272 CanQualType ClassType
9273 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009274 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009275 DeclarationName Name
9276 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009277 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009278 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009279 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009280 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009281 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009282 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009283 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009284
9285 if (getLangOpts().CUDA) {
9286 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9287 Destructor,
9288 /* ConstRHS */ false,
9289 /* Diagnose */ false);
9290 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009291
9292 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009293 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009294 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009295
Richard Smith6b02d462012-12-08 08:32:28 +00009296 AddOverriddenMethods(ClassDecl, Destructor);
9297
9298 // We don't need to use SpecialMemberIsTrivial here; triviality for
9299 // destructors is easy to compute.
9300 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9301
9302 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009303 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009304
Douglas Gregor7454c562010-07-02 20:37:36 +00009305 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009306 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009307
Douglas Gregor7454c562010-07-02 20:37:36 +00009308 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009309 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009310 PushOnScopeChains(Destructor, S, false);
9311 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009312
Douglas Gregorf1203042010-07-01 19:09:28 +00009313 return Destructor;
9314}
9315
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009316void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009317 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009318 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009319 !Destructor->doesThisDeclarationHaveABody() &&
9320 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009321 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009322 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009323 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009324
Douglas Gregor54818f02010-05-12 16:39:35 +00009325 if (Destructor->isInvalidDecl())
9326 return;
9327
Eli Friedmaneaf34142012-10-18 20:14:08 +00009328 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009329
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009330 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009331 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9332 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009333
Douglas Gregor54818f02010-05-12 16:39:35 +00009334 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009335 Diag(CurrentLocation, diag::note_member_synthesized_at)
9336 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9337
9338 Destructor->setInvalidDecl();
9339 return;
9340 }
9341
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009342 // The exception specification is needed because we are defining the
9343 // function.
9344 ResolveExceptionSpec(CurrentLocation,
9345 Destructor->getType()->castAs<FunctionProtoType>());
9346
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009347 SourceLocation Loc = Destructor->getLocEnd().isValid()
9348 ? Destructor->getLocEnd()
9349 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009350 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009351 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009352 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009353
9354 if (ASTMutationListener *L = getASTMutationListener()) {
9355 L->CompletedImplicitDefinition(Destructor);
9356 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009357}
9358
Richard Smith84973e52012-04-21 18:42:51 +00009359/// \brief Perform any semantic analysis which needs to be delayed until all
9360/// pending class member declarations have been parsed.
9361void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009362 // If the context is an invalid C++ class, just suppress these checks.
9363 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9364 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009365 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009366 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009367 return;
9368 }
9369 }
Richard Smith84973e52012-04-21 18:42:51 +00009370}
9371
Richard Smithd3b5c9082012-07-27 04:22:15 +00009372void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9373 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009374 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009375 "adjusting dtor exception specs was introduced in c++11");
9376
Sebastian Redl623ea822011-05-19 05:13:44 +00009377 // C++11 [class.dtor]p3:
9378 // A declaration of a destructor that does not have an exception-
9379 // specification is implicitly considered to have the same exception-
9380 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009381 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009382 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009383 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009384 return;
9385
Chandler Carruth9a797572011-09-20 04:55:26 +00009386 // Replace the destructor's type, building off the existing one. Fortunately,
9387 // the only thing of interest in the destructor type is its extended info.
9388 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009389 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009390 EPI.ExceptionSpec.Type = EST_Unevaluated;
9391 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009392 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009393
Sebastian Redl623ea822011-05-19 05:13:44 +00009394 // FIXME: If the destructor has a body that could throw, and the newly created
9395 // spec doesn't allow exceptions, we should emit a warning, because this
9396 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009397 // However, we don't have a body or an exception specification yet, so it
9398 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009399}
9400
Pavel Labath58934982013-08-30 08:52:28 +00009401namespace {
9402/// \brief An abstract base class for all helper classes used in building the
9403// copy/move operators. These classes serve as factory functions and help us
9404// avoid using the same Expr* in the AST twice.
9405class ExprBuilder {
9406 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9407 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9408
9409protected:
9410 static Expr *assertNotNull(Expr *E) {
9411 assert(E && "Expression construction must not fail.");
9412 return E;
9413 }
9414
9415public:
9416 ExprBuilder() {}
9417 virtual ~ExprBuilder() {}
9418
9419 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9420};
9421
9422class RefBuilder: public ExprBuilder {
9423 VarDecl *Var;
9424 QualType VarType;
9425
9426public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009427 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009428 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009429 }
9430
9431 RefBuilder(VarDecl *Var, QualType VarType)
9432 : Var(Var), VarType(VarType) {}
9433};
9434
9435class ThisBuilder: public ExprBuilder {
9436public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009437 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009438 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009439 }
9440};
9441
9442class CastBuilder: public ExprBuilder {
9443 const ExprBuilder &Builder;
9444 QualType Type;
9445 ExprValueKind Kind;
9446 const CXXCastPath &Path;
9447
9448public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009449 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009450 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9451 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009452 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009453 }
9454
9455 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9456 const CXXCastPath &Path)
9457 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9458};
9459
9460class DerefBuilder: public ExprBuilder {
9461 const ExprBuilder &Builder;
9462
9463public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009464 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009465 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009466 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009467 }
9468
9469 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9470};
9471
9472class MemberBuilder: public ExprBuilder {
9473 const ExprBuilder &Builder;
9474 QualType Type;
9475 CXXScopeSpec SS;
9476 bool IsArrow;
9477 LookupResult &MemberLookup;
9478
9479public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009480 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009481 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009482 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009483 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009484 }
9485
9486 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9487 LookupResult &MemberLookup)
9488 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9489 MemberLookup(MemberLookup) {}
9490};
9491
9492class MoveCastBuilder: public ExprBuilder {
9493 const ExprBuilder &Builder;
9494
9495public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009496 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009497 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9498 }
9499
9500 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9501};
9502
9503class LvalueConvBuilder: public ExprBuilder {
9504 const ExprBuilder &Builder;
9505
9506public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009507 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009508 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009509 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009510 }
9511
9512 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9513};
9514
9515class SubscriptBuilder: public ExprBuilder {
9516 const ExprBuilder &Base;
9517 const ExprBuilder &Index;
9518
9519public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009520 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009521 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009522 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009523 }
9524
9525 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9526 : Base(Base), Index(Index) {}
9527};
9528
9529} // end anonymous namespace
9530
Richard Smith41ae3282012-11-14 00:50:40 +00009531/// When generating a defaulted copy or move assignment operator, if a field
9532/// should be copied with __builtin_memcpy rather than via explicit assignments,
9533/// do so. This optimization only applies for arrays of scalars, and for arrays
9534/// of class type where the selected copy/move-assignment operator is trivial.
9535static StmtResult
9536buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009537 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009538 // Compute the size of the memory buffer to be copied.
9539 QualType SizeType = S.Context.getSizeType();
9540 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9541 S.Context.getTypeSizeInChars(T).getQuantity());
9542
9543 // Take the address of the field references for "from" and "to". We
9544 // directly construct UnaryOperators here because semantic analysis
9545 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009546 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009547 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9548 S.Context.getPointerType(From->getType()),
9549 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009550 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009551 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9552 S.Context.getPointerType(To->getType()),
9553 VK_RValue, OK_Ordinary, Loc);
9554
9555 const Type *E = T->getBaseElementTypeUnsafe();
9556 bool NeedsCollectableMemCpy =
9557 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9558
9559 // Create a reference to the __builtin_objc_memmove_collectable function
9560 StringRef MemCpyName = NeedsCollectableMemCpy ?
9561 "__builtin_objc_memmove_collectable" :
9562 "__builtin_memcpy";
9563 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9564 Sema::LookupOrdinaryName);
9565 S.LookupName(R, S.TUScope, true);
9566
9567 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9568 if (!MemCpy)
9569 // Something went horribly wrong earlier, and we will have complained
9570 // about it.
9571 return StmtError();
9572
9573 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009574 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009575 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9576
9577 Expr *CallArgs[] = {
9578 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9579 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009580 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009581 Loc, CallArgs, Loc);
9582
9583 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009584 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009585}
9586
Sebastian Redl22653ba2011-08-30 19:58:05 +00009587/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009588/// \c To.
9589///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009590/// This routine is used to copy/move the members of a class with an
9591/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009592/// copied are arrays, this routine builds for loops to copy them.
9593///
9594/// \param S The Sema object used for type-checking.
9595///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009596/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009597///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009598/// \param T The type of the expressions being copied/moved. Both expressions
9599/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009600///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009601/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009602///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009603/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009604///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009605/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009606/// Otherwise, it's a non-static member subobject.
9607///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009608/// \param Copying Whether we're copying or moving.
9609///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009610/// \param Depth Internal parameter recording the depth of the recursion.
9611///
Richard Smith41ae3282012-11-14 00:50:40 +00009612/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9613/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009614static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009615buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009616 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009617 bool CopyingBaseSubobject, bool Copying,
9618 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009619 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009620 // Each subobject is assigned in the manner appropriate to its type:
9621 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009622 // - if the subobject is of class type, as if by a call to operator= with
9623 // the subobject as the object expression and the corresponding
9624 // subobject of x as a single function argument (as if by explicit
9625 // qualification; that is, ignoring any possible virtual overriding
9626 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009627 //
9628 // C++03 [class.copy]p13:
9629 // - if the subobject is of class type, the copy assignment operator for
9630 // the class is used (as if by explicit qualification; that is,
9631 // ignoring any possible virtual overriding functions in more derived
9632 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009633 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9634 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009635
Douglas Gregorb139cd52010-05-01 20:49:11 +00009636 // Look for operator=.
9637 DeclarationName Name
9638 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9639 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9640 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009641
Richard Smith52c0b582012-11-13 00:54:12 +00009642 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9643 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009644 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009645 LookupResult::Filter F = OpLookup.makeFilter();
9646 while (F.hasNext()) {
9647 NamedDecl *D = F.next();
9648 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9649 if (Method->isCopyAssignmentOperator() ||
9650 (!Copying && Method->isMoveAssignmentOperator()))
9651 continue;
9652
9653 F.erase();
9654 }
9655 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009656 }
Richard Smith52c0b582012-11-13 00:54:12 +00009657
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009658 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009659 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009660 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009661 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009662 // ambiguities), we need to cast "this" to that subobject type; to
9663 // ensure that we don't go through the virtual call mechanism, we need
9664 // to qualify the operator= name with the base class (see below). However,
9665 // this means that if the base class has a protected copy assignment
9666 // operator, the protected member access check will fail. So, we
9667 // rewrite "protected" access to "public" access in this case, since we
9668 // know by construction that we're calling from a derived class.
9669 if (CopyingBaseSubobject) {
9670 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9671 L != LEnd; ++L) {
9672 if (L.getAccess() == AS_protected)
9673 L.setAccess(AS_public);
9674 }
9675 }
Richard Smith52c0b582012-11-13 00:54:12 +00009676
Douglas Gregorb139cd52010-05-01 20:49:11 +00009677 // Create the nested-name-specifier that will be used to qualify the
9678 // reference to operator=; this is required to suppress the virtual
9679 // call mechanism.
9680 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009681 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009682 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009683 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009684 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009685 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009686
Douglas Gregorb139cd52010-05-01 20:49:11 +00009687 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009688 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009689 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9690 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009691 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009692 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009693 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009694 /*SuppressQualifierCheck=*/true);
9695 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009696 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009697
Douglas Gregorb139cd52010-05-01 20:49:11 +00009698 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009699
Pavel Labath58934982013-08-30 08:52:28 +00009700 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009701 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009702 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009703 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009704 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009705 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009706
Richard Smith41ae3282012-11-14 00:50:40 +00009707 // If we built a call to a trivial 'operator=' while copying an array,
9708 // bail out. We'll replace the whole shebang with a memcpy.
9709 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9710 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009711 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009712
Richard Smith52c0b582012-11-13 00:54:12 +00009713 // Convert to an expression-statement, and clean up any produced
9714 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009715 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009716 }
John McCallab8c2732010-03-16 06:11:48 +00009717
Richard Smith52c0b582012-11-13 00:54:12 +00009718 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009719 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009720 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009721 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009722 ExprResult Assignment = S.CreateBuiltinBinOp(
9723 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009724 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009725 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009726 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009727 }
Richard Smith52c0b582012-11-13 00:54:12 +00009728
9729 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009730 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009731
Douglas Gregorb139cd52010-05-01 20:49:11 +00009732 // Construct a loop over the array bounds, e.g.,
9733 //
9734 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9735 //
9736 // that will copy each of the array elements.
9737 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009738
Douglas Gregorb139cd52010-05-01 20:49:11 +00009739 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009740 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009741 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009742 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009743 llvm::raw_svector_ostream OS(Str);
9744 OS << "__i" << Depth;
9745 IterationVarName = &S.Context.Idents.get(OS.str());
9746 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009747 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009748 IterationVarName, SizeType,
9749 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009750 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009751
Douglas Gregorb139cd52010-05-01 20:49:11 +00009752 // Initialize the iteration variable to zero.
9753 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009754 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009755
Pavel Labath58934982013-08-30 08:52:28 +00009756 // Creates a reference to the iteration variable.
9757 RefBuilder IterationVarRef(IterationVar, SizeType);
9758 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009759
Douglas Gregorb139cd52010-05-01 20:49:11 +00009760 // Create the DeclStmt that holds the iteration variable.
9761 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009762
Douglas Gregorb139cd52010-05-01 20:49:11 +00009763 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009764 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9765 MoveCastBuilder FromIndexMove(FromIndexCopy);
9766 const ExprBuilder *FromIndex;
9767 if (Copying)
9768 FromIndex = &FromIndexCopy;
9769 else
9770 FromIndex = &FromIndexMove;
9771
9772 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009773
9774 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009775 StmtResult Copy =
9776 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009777 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009778 Copying, Depth + 1);
9779 // Bail out if copying fails or if we determined that we should use memcpy.
9780 if (Copy.isInvalid() || !Copy.get())
9781 return Copy;
9782
9783 // Create the comparison against the array bound.
9784 llvm::APInt Upper
9785 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9786 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009787 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009788 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9789 BO_NE, S.Context.BoolTy,
9790 VK_RValue, OK_Ordinary, Loc, false);
9791
9792 // Create the pre-increment of the iteration variable.
9793 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009794 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9795 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009796
Douglas Gregorb139cd52010-05-01 20:49:11 +00009797 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009798 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009799 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009800 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009801 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009802}
9803
Richard Smith41ae3282012-11-14 00:50:40 +00009804static StmtResult
9805buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009806 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009807 bool CopyingBaseSubobject, bool Copying) {
9808 // Maybe we should use a memcpy?
9809 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9810 T.isTriviallyCopyableType(S.Context))
9811 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9812
9813 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9814 CopyingBaseSubobject,
9815 Copying, 0));
9816
9817 // If we ended up picking a trivial assignment operator for an array of a
9818 // non-trivially-copyable class type, just emit a memcpy.
9819 if (!Result.isInvalid() && !Result.get())
9820 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9821
9822 return Result;
9823}
9824
Richard Smithd3b5c9082012-07-27 04:22:15 +00009825Sema::ImplicitExceptionSpecification
9826Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9827 CXXRecordDecl *ClassDecl = MD->getParent();
9828
9829 ImplicitExceptionSpecification ExceptSpec(*this);
9830 if (ClassDecl->isInvalidDecl())
9831 return ExceptSpec;
9832
9833 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009834 assert(T->getNumParams() == 1 && "not a copy assignment op");
9835 unsigned ArgQuals =
9836 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009837
Douglas Gregor68e11362010-07-01 17:48:08 +00009838 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009839 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009840 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009841
9842 // It is unspecified whether or not an implicit copy assignment operator
9843 // attempts to deduplicate calls to assignment operators of virtual bases are
9844 // made. As such, this exception specification is effectively unspecified.
9845 // Based on a similar decision made for constness in C++0x, we're erring on
9846 // the side of assuming such calls to be made regardless of whether they
9847 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009848 for (const auto &Base : ClassDecl->bases()) {
9849 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009850 continue;
9851
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009852 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009853 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009854 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9855 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009856 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009857 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009858
Aaron Ballman445a9392014-03-13 16:15:17 +00009859 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009860 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009861 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009862 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9863 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009864 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009865 }
9866
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009867 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009868 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009869 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9870 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009871 LookupCopyingAssignment(FieldClassDecl,
9872 ArgQuals | FieldType.getCVRQualifiers(),
9873 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009874 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009875 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009876 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009877
Richard Smithd3b5c9082012-07-27 04:22:15 +00009878 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009879}
9880
9881CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9882 // Note: The following rules are largely analoguous to the copy
9883 // constructor rules. Note that virtual bases are not taken into account
9884 // for determining the argument type of the operator. Note also that
9885 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009886 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009887
Richard Smith8bf22e52012-11-29 01:34:07 +00009888 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9889 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009890 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009891
Alexis Hunt119f3652011-05-14 05:23:20 +00009892 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9893 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009894 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9895 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009896 ArgType = ArgType.withConst();
9897 ArgType = Context.getLValueReferenceType(ArgType);
9898
Richard Smith99005e62013-05-07 03:19:20 +00009899 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9900 CXXCopyAssignment,
9901 Const);
9902
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009903 // An implicitly-declared copy assignment operator is an inline public
9904 // member of its class.
9905 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009906 SourceLocation ClassLoc = ClassDecl->getLocation();
9907 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009908 CXXMethodDecl *CopyAssignment =
9909 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009910 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9911 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009912 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009913 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009914 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009915
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009916 if (getLangOpts().CUDA) {
9917 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9918 CopyAssignment,
9919 /* ConstRHS */ Const,
9920 /* Diagnose */ false);
9921 }
9922
Richard Smithd3b5c9082012-07-27 04:22:15 +00009923 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009924 FunctionProtoType::ExtProtoInfo EPI =
9925 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009926 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009927
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009928 // Add the parameter to the operator.
9929 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009930 ClassLoc, ClassLoc,
9931 /*Id=*/nullptr, ArgType,
9932 /*TInfo=*/nullptr, SC_None,
9933 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009934 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009935
Richard Smith6b02d462012-12-08 08:32:28 +00009936 AddOverriddenMethods(ClassDecl, CopyAssignment);
9937
9938 CopyAssignment->setTrivial(
9939 ClassDecl->needsOverloadResolutionForCopyAssignment()
9940 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9941 : ClassDecl->hasTrivialCopyAssignment());
9942
Richard Smith852265f2012-03-30 20:53:28 +00009943 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009944 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009945
Richard Smith6b02d462012-12-08 08:32:28 +00009946 // Note that we have added this copy-assignment operator.
9947 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9948
9949 if (Scope *S = getScopeForContext(ClassDecl))
9950 PushOnScopeChains(CopyAssignment, S, false);
9951 ClassDecl->addDecl(CopyAssignment);
9952
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009953 return CopyAssignment;
9954}
9955
Richard Smithd577fbb2013-06-13 03:23:42 +00009956/// Diagnose an implicit copy operation for a class which is odr-used, but
9957/// which is deprecated because the class has a user-declared copy constructor,
9958/// copy assignment operator, or destructor.
9959static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9960 SourceLocation UseLoc) {
9961 assert(CopyOp->isImplicit());
9962
9963 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009964 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009965
9966 // In Microsoft mode, assignment operations don't affect constructors and
9967 // vice versa.
9968 if (RD->hasUserDeclaredDestructor()) {
9969 UserDeclaredOperation = RD->getDestructor();
9970 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9971 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009972 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009973 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009974 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009975 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009976 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009977 break;
9978 }
9979 }
9980 assert(UserDeclaredOperation);
9981 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9982 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009983 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009984 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009985 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009986 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009987 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009988 break;
9989 }
9990 }
9991 assert(UserDeclaredOperation);
9992 }
9993
9994 if (UserDeclaredOperation) {
9995 S.Diag(UserDeclaredOperation->getLocation(),
9996 diag::warn_deprecated_copy_operation)
9997 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9998 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9999 S.Diag(UseLoc, diag::note_member_synthesized_at)
10000 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10001 : Sema::CXXCopyAssignment)
10002 << RD;
10003 }
10004}
10005
Douglas Gregorb139cd52010-05-01 20:49:11 +000010006void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10007 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010008 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010009 CopyAssignOperator->isOverloadedOperator() &&
10010 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010011 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10012 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010013 "DefineImplicitCopyAssignment called for wrong function");
10014
10015 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10016
10017 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10018 CopyAssignOperator->setInvalidDecl();
10019 return;
10020 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010021
10022 // C++11 [class.copy]p18:
10023 // The [definition of an implicitly declared copy assignment operator] is
10024 // deprecated if the class has a user-declared copy constructor or a
10025 // user-declared destructor.
10026 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10027 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10028
Eli Friedman276dd182013-09-05 00:02:25 +000010029 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010030
Eli Friedmaneaf34142012-10-18 20:14:08 +000010031 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010032 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010033
10034 // C++0x [class.copy]p30:
10035 // The implicitly-defined or explicitly-defaulted copy assignment operator
10036 // for a non-union class X performs memberwise copy assignment of its
10037 // subobjects. The direct base classes of X are assigned first, in the
10038 // order of their declaration in the base-specifier-list, and then the
10039 // immediate non-static data members of X are assigned, in the order in
10040 // which they were declared in the class definition.
10041
10042 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010043 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010044
10045 // The parameter for the "other" object, which we are copying from.
10046 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10047 Qualifiers OtherQuals = Other->getType().getQualifiers();
10048 QualType OtherRefType = Other->getType();
10049 if (const LValueReferenceType *OtherRef
10050 = OtherRefType->getAs<LValueReferenceType>()) {
10051 OtherRefType = OtherRef->getPointeeType();
10052 OtherQuals = OtherRefType.getQualifiers();
10053 }
10054
10055 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010056 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10057 ? CopyAssignOperator->getLocEnd()
10058 : CopyAssignOperator->getLocation();
10059
Pavel Labath58934982013-08-30 08:52:28 +000010060 // Builds a DeclRefExpr for the "other" object.
10061 RefBuilder OtherRef(Other, OtherRefType);
10062
10063 // Builds the "this" pointer.
10064 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010065
10066 // Assign base classes.
10067 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010068 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010069 // Form the assignment:
10070 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010071 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010072 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010073 Invalid = true;
10074 continue;
10075 }
10076
John McCallcf142162010-08-07 06:22:56 +000010077 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010078 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010079
Douglas Gregorb139cd52010-05-01 20:49:11 +000010080 // Construct the "from" expression, which is an implicit cast to the
10081 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010082 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10083 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010084
10085 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010086 DerefBuilder DerefThis(This);
10087 CastBuilder To(DerefThis,
10088 Context.getCVRQualifiedType(
10089 BaseType, CopyAssignOperator->getTypeQualifiers()),
10090 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010091
10092 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010093 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010094 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010095 /*CopyingBaseSubobject=*/true,
10096 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010097 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010098 Diag(CurrentLocation, diag::note_member_synthesized_at)
10099 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10100 CopyAssignOperator->setInvalidDecl();
10101 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010102 }
10103
10104 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010105 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010106 }
10107
Douglas Gregorb139cd52010-05-01 20:49:11 +000010108 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010109 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010110 if (Field->isUnnamedBitfield())
10111 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010112
10113 if (Field->isInvalidDecl()) {
10114 Invalid = true;
10115 continue;
10116 }
10117
Douglas Gregorb139cd52010-05-01 20:49:11 +000010118 // Check for members of reference type; we can't copy those.
10119 if (Field->getType()->isReferenceType()) {
10120 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10121 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10122 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010123 Diag(CurrentLocation, diag::note_member_synthesized_at)
10124 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010125 Invalid = true;
10126 continue;
10127 }
10128
10129 // Check for members of const-qualified, non-class type.
10130 QualType BaseType = Context.getBaseElementType(Field->getType());
10131 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10132 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10133 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10134 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010135 Diag(CurrentLocation, diag::note_member_synthesized_at)
10136 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010137 Invalid = true;
10138 continue;
10139 }
John McCall1b1a1db2011-06-17 00:18:42 +000010140
10141 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010142 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10143 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010144
10145 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010146 if (FieldType->isIncompleteArrayType()) {
10147 assert(ClassDecl->hasFlexibleArrayMember() &&
10148 "Incomplete array type is not valid");
10149 continue;
10150 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010151
10152 // Build references to the field in the object we're copying from and to.
10153 CXXScopeSpec SS; // Intentionally empty
10154 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10155 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010156 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010157 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010158
10159 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10160
10161 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010162
Douglas Gregorb139cd52010-05-01 20:49:11 +000010163 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010164 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010165 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010166 /*CopyingBaseSubobject=*/false,
10167 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010168 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010169 Diag(CurrentLocation, diag::note_member_synthesized_at)
10170 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10171 CopyAssignOperator->setInvalidDecl();
10172 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010173 }
10174
10175 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010176 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010177 }
10178
10179 if (!Invalid) {
10180 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010181 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010182
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010183 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010184 if (Return.isInvalid())
10185 Invalid = true;
10186 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010187 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010188
10189 if (Trap.hasErrorOccurred()) {
10190 Diag(CurrentLocation, diag::note_member_synthesized_at)
10191 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10192 Invalid = true;
10193 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010194 }
10195 }
10196
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010197 // The exception specification is needed because we are defining the
10198 // function.
10199 ResolveExceptionSpec(CurrentLocation,
10200 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10201
Douglas Gregorb139cd52010-05-01 20:49:11 +000010202 if (Invalid) {
10203 CopyAssignOperator->setInvalidDecl();
10204 return;
10205 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010206
10207 StmtResult Body;
10208 {
10209 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010210 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010211 /*isStmtExpr=*/false);
10212 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10213 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010214 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010215
10216 if (ASTMutationListener *L = getASTMutationListener()) {
10217 L->CompletedImplicitDefinition(CopyAssignOperator);
10218 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010219}
10220
Sebastian Redl22653ba2011-08-30 19:58:05 +000010221Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010222Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10223 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010224
Richard Smithd3b5c9082012-07-27 04:22:15 +000010225 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010226 if (ClassDecl->isInvalidDecl())
10227 return ExceptSpec;
10228
10229 // C++0x [except.spec]p14:
10230 // An implicitly declared special member function (Clause 12) shall have an
10231 // exception-specification. [...]
10232
10233 // It is unspecified whether or not an implicit move assignment operator
10234 // attempts to deduplicate calls to assignment operators of virtual bases are
10235 // made. As such, this exception specification is effectively unspecified.
10236 // Based on a similar decision made for constness in C++0x, we're erring on
10237 // the side of assuming such calls to be made regardless of whether they
10238 // actually happen.
10239 // Note that a move constructor is not implicitly declared when there are
10240 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010241 for (const auto &Base : ClassDecl->bases()) {
10242 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010243 continue;
10244
10245 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010246 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010247 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010248 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010249 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010250 }
10251
Aaron Ballman445a9392014-03-13 16:15:17 +000010252 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010253 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010254 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010255 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010256 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010257 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010258 }
10259
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010260 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010261 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010262 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010263 if (CXXMethodDecl *MoveAssign =
10264 LookupMovingAssignment(FieldClassDecl,
10265 FieldType.getCVRQualifiers(),
10266 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010267 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010268 }
10269 }
10270
10271 return ExceptSpec;
10272}
10273
10274CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010275 assert(ClassDecl->needsImplicitMoveAssignment());
10276
Richard Smith8bf22e52012-11-29 01:34:07 +000010277 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10278 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010279 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010280
Sebastian Redl22653ba2011-08-30 19:58:05 +000010281 // Note: The following rules are largely analoguous to the move
10282 // constructor rules.
10283
Sebastian Redl22653ba2011-08-30 19:58:05 +000010284 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10285 QualType RetType = Context.getLValueReferenceType(ArgType);
10286 ArgType = Context.getRValueReferenceType(ArgType);
10287
Richard Smith99005e62013-05-07 03:19:20 +000010288 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10289 CXXMoveAssignment,
10290 false);
10291
Sebastian Redl22653ba2011-08-30 19:58:05 +000010292 // An implicitly-declared move assignment operator is an inline public
10293 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010294 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10295 SourceLocation ClassLoc = ClassDecl->getLocation();
10296 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010297 CXXMethodDecl *MoveAssignment =
10298 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010299 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010300 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010301 MoveAssignment->setAccess(AS_public);
10302 MoveAssignment->setDefaulted();
10303 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010304
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010305 if (getLangOpts().CUDA) {
10306 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10307 MoveAssignment,
10308 /* ConstRHS */ false,
10309 /* Diagnose */ false);
10310 }
10311
Richard Smithd3b5c9082012-07-27 04:22:15 +000010312 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010313 FunctionProtoType::ExtProtoInfo EPI =
10314 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010315 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010316
Sebastian Redl22653ba2011-08-30 19:58:05 +000010317 // Add the parameter to the operator.
10318 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010319 ClassLoc, ClassLoc,
10320 /*Id=*/nullptr, ArgType,
10321 /*TInfo=*/nullptr, SC_None,
10322 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010323 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010324
Richard Smith6b02d462012-12-08 08:32:28 +000010325 AddOverriddenMethods(ClassDecl, MoveAssignment);
10326
10327 MoveAssignment->setTrivial(
10328 ClassDecl->needsOverloadResolutionForMoveAssignment()
10329 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10330 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010331
Richard Smithd951a1d2012-02-18 02:02:13 +000010332 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010333 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10334 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010335 }
10336
Richard Smith6b02d462012-12-08 08:32:28 +000010337 // Note that we have added this copy-assignment operator.
10338 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10339
Sebastian Redl22653ba2011-08-30 19:58:05 +000010340 if (Scope *S = getScopeForContext(ClassDecl))
10341 PushOnScopeChains(MoveAssignment, S, false);
10342 ClassDecl->addDecl(MoveAssignment);
10343
Sebastian Redl22653ba2011-08-30 19:58:05 +000010344 return MoveAssignment;
10345}
10346
Richard Smithb2504bd2013-11-04 04:26:14 +000010347/// Check if we're implicitly defining a move assignment operator for a class
10348/// with virtual bases. Such a move assignment might move-assign the virtual
10349/// base multiple times.
10350static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10351 SourceLocation CurrentLocation) {
10352 assert(!Class->isDependentContext() && "should not define dependent move");
10353
10354 // Only a virtual base could get implicitly move-assigned multiple times.
10355 // Only a non-trivial move assignment can observe this. We only want to
10356 // diagnose if we implicitly define an assignment operator that assigns
10357 // two base classes, both of which move-assign the same virtual base.
10358 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10359 Class->getNumBases() < 2)
10360 return;
10361
10362 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10363 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10364 VBaseMap VBases;
10365
Aaron Ballman574705e2014-03-13 15:41:46 +000010366 for (auto &BI : Class->bases()) {
10367 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010368 while (!Worklist.empty()) {
10369 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10370 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10371
10372 // If the base has no non-trivial move assignment operators,
10373 // we don't care about moves from it.
10374 if (!Base->hasNonTrivialMoveAssignment())
10375 continue;
10376
10377 // If there's nothing virtual here, skip it.
10378 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10379 continue;
10380
10381 // If we're not actually going to call a move assignment for this base,
10382 // or the selected move assignment is trivial, skip it.
10383 Sema::SpecialMemberOverloadResult *SMOR =
10384 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10385 /*ConstArg*/false, /*VolatileArg*/false,
10386 /*RValueThis*/true, /*ConstThis*/false,
10387 /*VolatileThis*/false);
10388 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10389 !SMOR->getMethod()->isMoveAssignmentOperator())
10390 continue;
10391
10392 if (BaseSpec->isVirtual()) {
10393 // We're going to move-assign this virtual base, and its move
10394 // assignment operator is not trivial. If this can happen for
10395 // multiple distinct direct bases of Class, diagnose it. (If it
10396 // only happens in one base, we'll diagnose it when synthesizing
10397 // that base class's move assignment operator.)
10398 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010399 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010400 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010401 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010402 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10403 << Class << Base;
10404 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10405 << (Base->getCanonicalDecl() ==
10406 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10407 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010408 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010409 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010410 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10411 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010412
10413 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010414 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010415 }
10416 } else {
10417 // Only walk over bases that have defaulted move assignment operators.
10418 // We assume that any user-provided move assignment operator handles
10419 // the multiple-moves-of-vbase case itself somehow.
10420 if (!SMOR->getMethod()->isDefaulted())
10421 continue;
10422
10423 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010424 for (auto &BI : Base->bases())
10425 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010426 }
10427 }
10428 }
10429}
10430
Sebastian Redl22653ba2011-08-30 19:58:05 +000010431void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10432 CXXMethodDecl *MoveAssignOperator) {
10433 assert((MoveAssignOperator->isDefaulted() &&
10434 MoveAssignOperator->isOverloadedOperator() &&
10435 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010436 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10437 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010438 "DefineImplicitMoveAssignment called for wrong function");
10439
10440 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10441
10442 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10443 MoveAssignOperator->setInvalidDecl();
10444 return;
10445 }
10446
Eli Friedman276dd182013-09-05 00:02:25 +000010447 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010448
Eli Friedmaneaf34142012-10-18 20:14:08 +000010449 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010450 DiagnosticErrorTrap Trap(Diags);
10451
10452 // C++0x [class.copy]p28:
10453 // The implicitly-defined or move assignment operator for a non-union class
10454 // X performs memberwise move assignment of its subobjects. The direct base
10455 // classes of X are assigned first, in the order of their declaration in the
10456 // base-specifier-list, and then the immediate non-static data members of X
10457 // are assigned, in the order in which they were declared in the class
10458 // definition.
10459
Richard Smithb2504bd2013-11-04 04:26:14 +000010460 // Issue a warning if our implicit move assignment operator will move
10461 // from a virtual base more than once.
10462 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010463
Sebastian Redl22653ba2011-08-30 19:58:05 +000010464 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010465 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010466
10467 // The parameter for the "other" object, which we are move from.
10468 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10469 QualType OtherRefType = Other->getType()->
10470 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010471 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010472 "Bad argument type of defaulted move assignment");
10473
10474 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010475 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10476 ? MoveAssignOperator->getLocEnd()
10477 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010478
Pavel Labath58934982013-08-30 08:52:28 +000010479 // Builds a reference to the "other" object.
10480 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010481 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010482 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010483
Pavel Labath58934982013-08-30 08:52:28 +000010484 // Builds the "this" pointer.
10485 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010486
Sebastian Redl22653ba2011-08-30 19:58:05 +000010487 // Assign base classes.
10488 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010489 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010490 // C++11 [class.copy]p28:
10491 // It is unspecified whether subobjects representing virtual base classes
10492 // are assigned more than once by the implicitly-defined copy assignment
10493 // operator.
10494 // FIXME: Do not assign to a vbase that will be assigned by some other base
10495 // class. For a move-assignment, this can result in the vbase being moved
10496 // multiple times.
10497
Sebastian Redl22653ba2011-08-30 19:58:05 +000010498 // Form the assignment:
10499 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010500 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010501 if (!BaseType->isRecordType()) {
10502 Invalid = true;
10503 continue;
10504 }
10505
10506 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010507 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010508
10509 // Construct the "from" expression, which is an implicit cast to the
10510 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010511 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010512
10513 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010514 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010515
10516 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010517 CastBuilder To(DerefThis,
10518 Context.getCVRQualifiedType(
10519 BaseType, MoveAssignOperator->getTypeQualifiers()),
10520 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010521
10522 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010523 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010524 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010525 /*CopyingBaseSubobject=*/true,
10526 /*Copying=*/false);
10527 if (Move.isInvalid()) {
10528 Diag(CurrentLocation, diag::note_member_synthesized_at)
10529 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10530 MoveAssignOperator->setInvalidDecl();
10531 return;
10532 }
10533
10534 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010535 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010536 }
10537
Sebastian Redl22653ba2011-08-30 19:58:05 +000010538 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010539 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010540 if (Field->isUnnamedBitfield())
10541 continue;
10542
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010543 if (Field->isInvalidDecl()) {
10544 Invalid = true;
10545 continue;
10546 }
10547
Sebastian Redl22653ba2011-08-30 19:58:05 +000010548 // Check for members of reference type; we can't move those.
10549 if (Field->getType()->isReferenceType()) {
10550 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10551 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10552 Diag(Field->getLocation(), diag::note_declared_at);
10553 Diag(CurrentLocation, diag::note_member_synthesized_at)
10554 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10555 Invalid = true;
10556 continue;
10557 }
10558
10559 // Check for members of const-qualified, non-class type.
10560 QualType BaseType = Context.getBaseElementType(Field->getType());
10561 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10562 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10563 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10564 Diag(Field->getLocation(), diag::note_declared_at);
10565 Diag(CurrentLocation, diag::note_member_synthesized_at)
10566 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10567 Invalid = true;
10568 continue;
10569 }
10570
10571 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010572 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10573 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010574
10575 QualType FieldType = Field->getType().getNonReferenceType();
10576 if (FieldType->isIncompleteArrayType()) {
10577 assert(ClassDecl->hasFlexibleArrayMember() &&
10578 "Incomplete array type is not valid");
10579 continue;
10580 }
10581
10582 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010583 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10584 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010585 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010586 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010587 MemberBuilder From(MoveOther, OtherRefType,
10588 /*IsArrow=*/false, MemberLookup);
10589 MemberBuilder To(This, getCurrentThisType(),
10590 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010591
Pavel Labath58934982013-08-30 08:52:28 +000010592 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010593 "Member reference with rvalue base must be rvalue except for reference "
10594 "members, which aren't allowed for move assignment.");
10595
Sebastian Redl22653ba2011-08-30 19:58:05 +000010596 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010597 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010598 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010599 /*CopyingBaseSubobject=*/false,
10600 /*Copying=*/false);
10601 if (Move.isInvalid()) {
10602 Diag(CurrentLocation, diag::note_member_synthesized_at)
10603 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10604 MoveAssignOperator->setInvalidDecl();
10605 return;
10606 }
Richard Smith11d19592012-11-12 23:33:00 +000010607
Sebastian Redl22653ba2011-08-30 19:58:05 +000010608 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010609 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010610 }
10611
10612 if (!Invalid) {
10613 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010614 ExprResult ThisObj =
10615 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10616
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010617 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010618 if (Return.isInvalid())
10619 Invalid = true;
10620 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010621 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010622
10623 if (Trap.hasErrorOccurred()) {
10624 Diag(CurrentLocation, diag::note_member_synthesized_at)
10625 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10626 Invalid = true;
10627 }
10628 }
10629 }
10630
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010631 // The exception specification is needed because we are defining the
10632 // function.
10633 ResolveExceptionSpec(CurrentLocation,
10634 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10635
Sebastian Redl22653ba2011-08-30 19:58:05 +000010636 if (Invalid) {
10637 MoveAssignOperator->setInvalidDecl();
10638 return;
10639 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010640
10641 StmtResult Body;
10642 {
10643 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010644 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010645 /*isStmtExpr=*/false);
10646 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10647 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010648 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010649
10650 if (ASTMutationListener *L = getASTMutationListener()) {
10651 L->CompletedImplicitDefinition(MoveAssignOperator);
10652 }
10653}
10654
Richard Smithd3b5c9082012-07-27 04:22:15 +000010655Sema::ImplicitExceptionSpecification
10656Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10657 CXXRecordDecl *ClassDecl = MD->getParent();
10658
10659 ImplicitExceptionSpecification ExceptSpec(*this);
10660 if (ClassDecl->isInvalidDecl())
10661 return ExceptSpec;
10662
10663 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010664 assert(T->getNumParams() >= 1 && "not a copy ctor");
10665 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010666
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010667 // C++ [except.spec]p14:
10668 // An implicitly declared special member function (Clause 12) shall have an
10669 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010670 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010671 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010672 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010673 continue;
10674
Douglas Gregora6d69502010-07-02 23:41:54 +000010675 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010676 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010677 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010678 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010679 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010680 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010681 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010682 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010683 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010684 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010685 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010686 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010687 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010688 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010689 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010690 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10691 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010692 LookupCopyingConstructor(FieldClassDecl,
10693 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010694 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010695 }
10696 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010697
Richard Smithd3b5c9082012-07-27 04:22:15 +000010698 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010699}
10700
10701CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10702 CXXRecordDecl *ClassDecl) {
10703 // C++ [class.copy]p4:
10704 // If the class definition does not explicitly declare a copy
10705 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010706 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010707
Richard Smith8bf22e52012-11-29 01:34:07 +000010708 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10709 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010710 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010711
Alexis Hunt913820d2011-05-13 06:10:58 +000010712 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10713 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010714 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010715 if (Const)
10716 ArgType = ArgType.withConst();
10717 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010718
Richard Smithb5800092012-06-10 05:43:50 +000010719 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10720 CXXCopyConstructor,
10721 Const);
10722
Douglas Gregor54be3392010-07-01 17:57:27 +000010723 DeclarationName Name
10724 = Context.DeclarationNames.getCXXConstructorName(
10725 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010726 SourceLocation ClassLoc = ClassDecl->getLocation();
10727 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010728
10729 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010730 // member of its class.
10731 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010732 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010733 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010734 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010735 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010736 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010737
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010738 if (getLangOpts().CUDA) {
10739 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10740 CopyConstructor,
10741 /* ConstRHS */ Const,
10742 /* Diagnose */ false);
10743 }
10744
Richard Smithd3b5c9082012-07-27 04:22:15 +000010745 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010746 FunctionProtoType::ExtProtoInfo EPI =
10747 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010748 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010749 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010750
Douglas Gregor54be3392010-07-01 17:57:27 +000010751 // Add the parameter to the constructor.
10752 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010753 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010754 /*IdentifierInfo=*/nullptr,
10755 ArgType, /*TInfo=*/nullptr,
10756 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010757 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010758
Richard Smith6b02d462012-12-08 08:32:28 +000010759 CopyConstructor->setTrivial(
10760 ClassDecl->needsOverloadResolutionForCopyConstructor()
10761 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10762 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010763
Richard Smith852265f2012-03-30 20:53:28 +000010764 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010765 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010766
Richard Smith6b02d462012-12-08 08:32:28 +000010767 // Note that we have declared this constructor.
10768 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10769
10770 if (Scope *S = getScopeForContext(ClassDecl))
10771 PushOnScopeChains(CopyConstructor, S, false);
10772 ClassDecl->addDecl(CopyConstructor);
10773
Douglas Gregor54be3392010-07-01 17:57:27 +000010774 return CopyConstructor;
10775}
10776
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010777void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010778 CXXConstructorDecl *CopyConstructor) {
10779 assert((CopyConstructor->isDefaulted() &&
10780 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010781 !CopyConstructor->doesThisDeclarationHaveABody() &&
10782 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010783 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010784
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010785 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010786 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010787
Richard Smithd577fbb2013-06-13 03:23:42 +000010788 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010789 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010790 // deprecated if the class has a user-declared copy assignment operator
10791 // or a user-declared destructor.
10792 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10793 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10794
Eli Friedmaneaf34142012-10-18 20:14:08 +000010795 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010796 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010797
David Blaikie3fc2f912013-01-17 05:26:25 +000010798 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010799 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010800 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010801 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010802 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010803 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010804 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10805 ? CopyConstructor->getLocEnd()
10806 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010807 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010808 CopyConstructor->setBody(
10809 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010810 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010811
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010812 // The exception specification is needed because we are defining the
10813 // function.
10814 ResolveExceptionSpec(CurrentLocation,
10815 CopyConstructor->getType()->castAs<FunctionProtoType>());
10816
Eli Friedman276dd182013-09-05 00:02:25 +000010817 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010818 MarkVTableUsed(CurrentLocation, ClassDecl);
10819
Sebastian Redlab238a72011-04-24 16:28:06 +000010820 if (ASTMutationListener *L = getASTMutationListener()) {
10821 L->CompletedImplicitDefinition(CopyConstructor);
10822 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010823}
10824
Sebastian Redl22653ba2011-08-30 19:58:05 +000010825Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010826Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10827 CXXRecordDecl *ClassDecl = MD->getParent();
10828
Sebastian Redl22653ba2011-08-30 19:58:05 +000010829 // C++ [except.spec]p14:
10830 // An implicitly declared special member function (Clause 12) shall have an
10831 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010832 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010833 if (ClassDecl->isInvalidDecl())
10834 return ExceptSpec;
10835
10836 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010837 for (const auto &B : ClassDecl->bases()) {
10838 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010839 continue;
10840
Aaron Ballman574705e2014-03-13 15:41:46 +000010841 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010842 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010843 CXXConstructorDecl *Constructor =
10844 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010845 // If this is a deleted function, add it anyway. This might be conformant
10846 // with the standard. This might not. I'm not sure. It might not matter.
10847 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010848 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010849 }
10850 }
10851
10852 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010853 for (const auto &B : ClassDecl->vbases()) {
10854 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010855 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010856 CXXConstructorDecl *Constructor =
10857 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010858 // If this is a deleted function, add it anyway. This might be conformant
10859 // with the standard. This might not. I'm not sure. It might not matter.
10860 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010861 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010862 }
10863 }
10864
10865 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010866 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010867 QualType FieldType = Context.getBaseElementType(F->getType());
10868 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10869 CXXConstructorDecl *Constructor =
10870 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010871 // If this is a deleted function, add it anyway. This might be conformant
10872 // with the standard. This might not. I'm not sure. It might not matter.
10873 // In particular, the problem is that this function never gets called. It
10874 // might just be ill-formed because this function attempts to refer to
10875 // a deleted function here.
10876 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010877 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010878 }
10879 }
10880
10881 return ExceptSpec;
10882}
10883
10884CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10885 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010886 assert(ClassDecl->needsImplicitMoveConstructor());
10887
Richard Smith8bf22e52012-11-29 01:34:07 +000010888 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10889 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010890 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010891
Sebastian Redl22653ba2011-08-30 19:58:05 +000010892 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10893 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010894
Richard Smithb5800092012-06-10 05:43:50 +000010895 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10896 CXXMoveConstructor,
10897 false);
10898
Sebastian Redl22653ba2011-08-30 19:58:05 +000010899 DeclarationName Name
10900 = Context.DeclarationNames.getCXXConstructorName(
10901 Context.getCanonicalType(ClassType));
10902 SourceLocation ClassLoc = ClassDecl->getLocation();
10903 DeclarationNameInfo NameInfo(Name, ClassLoc);
10904
Richard Smith99005e62013-05-07 03:19:20 +000010905 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010906 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010907 // member of its class.
10908 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010909 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010910 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010911 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010912 MoveConstructor->setAccess(AS_public);
10913 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010914
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010915 if (getLangOpts().CUDA) {
10916 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10917 MoveConstructor,
10918 /* ConstRHS */ false,
10919 /* Diagnose */ false);
10920 }
10921
Richard Smithd3b5c9082012-07-27 04:22:15 +000010922 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010923 FunctionProtoType::ExtProtoInfo EPI =
10924 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010925 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010926 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010927
Sebastian Redl22653ba2011-08-30 19:58:05 +000010928 // Add the parameter to the constructor.
10929 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10930 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010931 /*IdentifierInfo=*/nullptr,
10932 ArgType, /*TInfo=*/nullptr,
10933 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010934 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010935
Richard Smith6b02d462012-12-08 08:32:28 +000010936 MoveConstructor->setTrivial(
10937 ClassDecl->needsOverloadResolutionForMoveConstructor()
10938 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10939 : ClassDecl->hasTrivialMoveConstructor());
10940
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010941 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010942 ClassDecl->setImplicitMoveConstructorIsDeleted();
10943 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010944 }
10945
10946 // Note that we have declared this constructor.
10947 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10948
10949 if (Scope *S = getScopeForContext(ClassDecl))
10950 PushOnScopeChains(MoveConstructor, S, false);
10951 ClassDecl->addDecl(MoveConstructor);
10952
10953 return MoveConstructor;
10954}
10955
10956void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10957 CXXConstructorDecl *MoveConstructor) {
10958 assert((MoveConstructor->isDefaulted() &&
10959 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010960 !MoveConstructor->doesThisDeclarationHaveABody() &&
10961 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010962 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10963
10964 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10965 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10966
Eli Friedmaneaf34142012-10-18 20:14:08 +000010967 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010968 DiagnosticErrorTrap Trap(Diags);
10969
David Blaikie3fc2f912013-01-17 05:26:25 +000010970 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010971 Trap.hasErrorOccurred()) {
10972 Diag(CurrentLocation, diag::note_member_synthesized_at)
10973 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10974 MoveConstructor->setInvalidDecl();
10975 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010976 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10977 ? MoveConstructor->getLocEnd()
10978 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010979 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010980 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010981 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010982 }
10983
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010984 // The exception specification is needed because we are defining the
10985 // function.
10986 ResolveExceptionSpec(CurrentLocation,
10987 MoveConstructor->getType()->castAs<FunctionProtoType>());
10988
Eli Friedman276dd182013-09-05 00:02:25 +000010989 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010990 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010991
10992 if (ASTMutationListener *L = getASTMutationListener()) {
10993 L->CompletedImplicitDefinition(MoveConstructor);
10994 }
10995}
10996
Douglas Gregor74f7d502012-02-15 19:33:52 +000010997bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010998 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010999}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011000
11001void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011002 SourceLocation CurrentLocation,
11003 CXXConversionDecl *Conv) {
11004 CXXRecordDecl *Lambda = Conv->getParent();
11005 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11006 // If we are defining a specialization of a conversion to function-ptr
11007 // cache the deduced template arguments for this specialization
11008 // so that we can use them to retrieve the corresponding call-operator
11009 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011010 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11011
Faisal Vali571df122013-09-29 08:45:24 +000011012 // Retrieve the corresponding call-operator specialization.
11013 if (Lambda->isGenericLambda()) {
11014 assert(Conv->isFunctionTemplateSpecialization());
11015 FunctionTemplateDecl *CallOpTemplate =
11016 CallOp->getDescribedFunctionTemplate();
11017 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011018 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011019 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011020 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011021 InsertPos);
11022 assert(CallOpSpec &&
11023 "Conversion operator must have a corresponding call operator");
11024 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11025 }
11026 // Mark the call operator referenced (and add to pending instantiations
11027 // if necessary).
11028 // For both the conversion and static-invoker template specializations
11029 // we construct their body's in this function, so no need to add them
11030 // to the PendingInstantiations.
11031 MarkFunctionReferenced(CurrentLocation, CallOp);
11032
Eli Friedmaneaf34142012-10-18 20:14:08 +000011033 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011034 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011035
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011036 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011037 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11038 // ... and get the corresponding specialization for a generic lambda.
11039 if (Lambda->isGenericLambda()) {
11040 assert(DeducedTemplateArgs &&
11041 "Must have deduced template arguments from Conversion Operator");
11042 FunctionTemplateDecl *InvokeTemplate =
11043 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011044 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011045 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011046 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011047 InsertPos);
11048 assert(InvokeSpec &&
11049 "Must have a corresponding static invoker specialization");
11050 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11051 }
11052 // Construct the body of the conversion function { return __invoke; }.
11053 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011054 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011055 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011056 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011057 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11058 Conv->getLocation(),
11059 Conv->getLocation()));
11060
11061 Conv->markUsed(Context);
11062 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011063
Faisal Vali571df122013-09-29 08:45:24 +000011064 // Fill in the __invoke function with a dummy implementation. IR generation
11065 // will fill in the actual details.
11066 Invoker->markUsed(Context);
11067 Invoker->setReferenced();
11068 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11069
Douglas Gregord3b672c2012-02-16 01:06:16 +000011070 if (ASTMutationListener *L = getASTMutationListener()) {
11071 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011072 L->CompletedImplicitDefinition(Invoker);
11073 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011074}
11075
Faisal Vali571df122013-09-29 08:45:24 +000011076
11077
Douglas Gregord3b672c2012-02-16 01:06:16 +000011078void Sema::DefineImplicitLambdaToBlockPointerConversion(
11079 SourceLocation CurrentLocation,
11080 CXXConversionDecl *Conv)
11081{
Faisal Vali850da1a2013-09-29 17:08:32 +000011082 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011083
Eli Friedman276dd182013-09-05 00:02:25 +000011084 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011085
Eli Friedmaneaf34142012-10-18 20:14:08 +000011086 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011087 DiagnosticErrorTrap Trap(Diags);
11088
Douglas Gregored90df32012-02-22 05:02:47 +000011089 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011090 Expr *This = ActOnCXXThis(CurrentLocation).get();
11091 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011092
Eli Friedman98b01ed2012-03-01 04:01:32 +000011093 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11094 Conv->getLocation(),
11095 Conv, DerefThis);
11096
11097 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11098 // behavior. Note that only the general conversion function does this
11099 // (since it's unusable otherwise); in the case where we inline the
11100 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011101 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011102 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11103 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011104 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011105
11106 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011107 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011108 Conv->setInvalidDecl();
11109 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011110 }
Douglas Gregored90df32012-02-22 05:02:47 +000011111
Douglas Gregored90df32012-02-22 05:02:47 +000011112 // Create the return statement that returns the block from the conversion
11113 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011114 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011115 if (Return.isInvalid()) {
11116 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11117 Conv->setInvalidDecl();
11118 return;
11119 }
11120
11121 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011122 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011123 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011124 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011125 Conv->getLocation()));
11126
Douglas Gregored90df32012-02-22 05:02:47 +000011127 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011128 if (ASTMutationListener *L = getASTMutationListener()) {
11129 L->CompletedImplicitDefinition(Conv);
11130 }
11131}
11132
Douglas Gregord2f70072012-03-10 06:53:13 +000011133/// \brief Determine whether the given list arguments contains exactly one
11134/// "real" (non-default) argument.
11135static bool hasOneRealArgument(MultiExprArg Args) {
11136 switch (Args.size()) {
11137 case 0:
11138 return false;
11139
11140 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011141 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011142 return false;
11143
11144 // fall through
11145 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011146 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011147 }
11148
11149 return false;
11150}
11151
John McCalldadc5752010-08-24 06:29:42 +000011152ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011153Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011154 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011155 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011156 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011157 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011158 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011159 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011160 unsigned ConstructKind,
11161 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011162 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011163
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011164 // C++0x [class.copy]p34:
11165 // When certain criteria are met, an implementation is allowed to
11166 // omit the copy/move construction of a class object, even if the
11167 // copy/move constructor and/or destructor for the object have
11168 // side effects. [...]
11169 // - when a temporary class object that has not been bound to a
11170 // reference (12.2) would be copied/moved to a class object
11171 // with the same cv-unqualified type, the copy/move operation
11172 // can be omitted by constructing the temporary object
11173 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011174 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011175 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011176 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011177 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011178 }
Mike Stump11289f42009-09-09 15:08:12 +000011179
11180 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011181 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011182 IsListInitialization,
11183 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011184 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011185}
11186
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011187/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11188/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011189ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011190Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11191 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011192 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011193 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011194 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011195 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011196 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011197 unsigned ConstructKind,
11198 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011199 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011200 return CXXConstructExpr::Create(
11201 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011202 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11203 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011204 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11205 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011206}
11207
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011208ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11209 assert(Field->hasInClassInitializer());
11210
11211 // If we already have the in-class initializer nothing needs to be done.
11212 if (Field->getInClassInitializer())
11213 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11214
11215 // Maybe we haven't instantiated the in-class initializer. Go check the
11216 // pattern FieldDecl to see if it has one.
11217 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11218
11219 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11220 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11221 DeclContext::lookup_result Lookup =
11222 ClassPattern->lookup(Field->getDeclName());
11223 assert(Lookup.size() == 1);
11224 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11225 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11226 getTemplateInstantiationArgs(Field)))
11227 return ExprError();
11228 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11229 }
11230
11231 // DR1351:
11232 // If the brace-or-equal-initializer of a non-static data member
11233 // invokes a defaulted default constructor of its class or of an
11234 // enclosing class in a potentially evaluated subexpression, the
11235 // program is ill-formed.
11236 //
11237 // This resolution is unworkable: the exception specification of the
11238 // default constructor can be needed in an unevaluated context, in
11239 // particular, in the operand of a noexcept-expression, and we can be
11240 // unable to compute an exception specification for an enclosed class.
11241 //
11242 // Any attempt to resolve the exception specification of a defaulted default
11243 // constructor before the initializer is lexically complete will ultimately
11244 // come here at which point we can diagnose it.
11245 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11246 if (OutermostClass == ParentRD) {
11247 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11248 << ParentRD << Field;
11249 } else {
11250 Diag(Field->getLocEnd(),
11251 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11252 << ParentRD << OutermostClass << Field;
11253 }
11254
11255 return ExprError();
11256}
11257
John McCall03c48482010-02-02 09:10:11 +000011258void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011259 if (VD->isInvalidDecl()) return;
11260
John McCall03c48482010-02-02 09:10:11 +000011261 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011262 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011263 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011264 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011265
Chandler Carruth86d17d32011-03-27 21:26:48 +000011266 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011267 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011268 CheckDestructorAccess(VD->getLocation(), Destructor,
11269 PDiag(diag::err_access_dtor_var)
11270 << VD->getDeclName()
11271 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011272 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011273
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011274 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011275 if (!VD->hasGlobalStorage()) return;
11276
11277 // Emit warning for non-trivial dtor in global scope (a real global,
11278 // class-static, function-static).
11279 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11280
11281 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011282 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011283 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011284}
11285
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011286/// \brief Given a constructor and the set of arguments provided for the
11287/// constructor, convert the arguments and add any required default arguments
11288/// to form a proper call to this constructor.
11289///
11290/// \returns true if an error occurred, false otherwise.
11291bool
11292Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11293 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011294 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011295 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011296 bool AllowExplicit,
11297 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011298 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11299 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011300 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011301
11302 const FunctionProtoType *Proto
11303 = Constructor->getType()->getAs<FunctionProtoType>();
11304 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011305 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011306
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011307 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011308 if (NumArgs < NumParams)
11309 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011310 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011311 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011312
11313 VariadicCallType CallType =
11314 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011315 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011316 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011317 Proto, 0,
11318 llvm::makeArrayRef(Args, NumArgs),
11319 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011320 CallType, AllowExplicit,
11321 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011322 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011323
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011324 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011325
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011326 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011327 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011328 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011329
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011330 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011331}
11332
Anders Carlssone363c8e2009-12-12 00:32:00 +000011333static inline bool
11334CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11335 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011336 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011337 if (isa<NamespaceDecl>(DC)) {
11338 return SemaRef.Diag(FnDecl->getLocation(),
11339 diag::err_operator_new_delete_declared_in_namespace)
11340 << FnDecl->getDeclName();
11341 }
11342
11343 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011344 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011345 return SemaRef.Diag(FnDecl->getLocation(),
11346 diag::err_operator_new_delete_declared_static)
11347 << FnDecl->getDeclName();
11348 }
11349
Anders Carlsson60659a82009-12-12 02:43:16 +000011350 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011351}
11352
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011353static inline bool
11354CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11355 CanQualType ExpectedResultType,
11356 CanQualType ExpectedFirstParamType,
11357 unsigned DependentParamTypeDiag,
11358 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011359 QualType ResultType =
11360 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011361
11362 // Check that the result type is not dependent.
11363 if (ResultType->isDependentType())
11364 return SemaRef.Diag(FnDecl->getLocation(),
11365 diag::err_operator_new_delete_dependent_result_type)
11366 << FnDecl->getDeclName() << ExpectedResultType;
11367
11368 // Check that the result type is what we expect.
11369 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11370 return SemaRef.Diag(FnDecl->getLocation(),
11371 diag::err_operator_new_delete_invalid_result_type)
11372 << FnDecl->getDeclName() << ExpectedResultType;
11373
11374 // A function template must have at least 2 parameters.
11375 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11376 return SemaRef.Diag(FnDecl->getLocation(),
11377 diag::err_operator_new_delete_template_too_few_parameters)
11378 << FnDecl->getDeclName();
11379
11380 // The function decl must have at least 1 parameter.
11381 if (FnDecl->getNumParams() == 0)
11382 return SemaRef.Diag(FnDecl->getLocation(),
11383 diag::err_operator_new_delete_too_few_parameters)
11384 << FnDecl->getDeclName();
11385
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011386 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011387 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11388 if (FirstParamType->isDependentType())
11389 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11390 << FnDecl->getDeclName() << ExpectedFirstParamType;
11391
11392 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011393 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011394 ExpectedFirstParamType)
11395 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11396 << FnDecl->getDeclName() << ExpectedFirstParamType;
11397
11398 return false;
11399}
11400
Anders Carlsson12308f42009-12-11 23:23:22 +000011401static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011402CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011403 // C++ [basic.stc.dynamic.allocation]p1:
11404 // A program is ill-formed if an allocation function is declared in a
11405 // namespace scope other than global scope or declared static in global
11406 // scope.
11407 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11408 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011409
11410 CanQualType SizeTy =
11411 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11412
11413 // C++ [basic.stc.dynamic.allocation]p1:
11414 // The return type shall be void*. The first parameter shall have type
11415 // std::size_t.
11416 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11417 SizeTy,
11418 diag::err_operator_new_dependent_param_type,
11419 diag::err_operator_new_param_type))
11420 return true;
11421
11422 // C++ [basic.stc.dynamic.allocation]p1:
11423 // The first parameter shall not have an associated default argument.
11424 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011425 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011426 diag::err_operator_new_default_arg)
11427 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11428
11429 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011430}
11431
11432static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011433CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011434 // C++ [basic.stc.dynamic.deallocation]p1:
11435 // A program is ill-formed if deallocation functions are declared in a
11436 // namespace scope other than global scope or declared static in global
11437 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011438 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11439 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011440
11441 // C++ [basic.stc.dynamic.deallocation]p2:
11442 // Each deallocation function shall return void and its first parameter
11443 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011444 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11445 SemaRef.Context.VoidPtrTy,
11446 diag::err_operator_delete_dependent_param_type,
11447 diag::err_operator_delete_param_type))
11448 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011449
Anders Carlsson12308f42009-12-11 23:23:22 +000011450 return false;
11451}
11452
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011453/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11454/// of this overloaded operator is well-formed. If so, returns false;
11455/// otherwise, emits appropriate diagnostics and returns true.
11456bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011457 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011458 "Expected an overloaded operator declaration");
11459
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011460 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11461
Mike Stump11289f42009-09-09 15:08:12 +000011462 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011463 // The allocation and deallocation functions, operator new,
11464 // operator new[], operator delete and operator delete[], are
11465 // described completely in 3.7.3. The attributes and restrictions
11466 // found in the rest of this subclause do not apply to them unless
11467 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011468 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011469 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011470
Anders Carlsson22f443f2009-12-12 00:26:23 +000011471 if (Op == OO_New || Op == OO_Array_New)
11472 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011473
11474 // C++ [over.oper]p6:
11475 // An operator function shall either be a non-static member
11476 // function or be a non-member function and have at least one
11477 // parameter whose type is a class, a reference to a class, an
11478 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011479 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11480 if (MethodDecl->isStatic())
11481 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011482 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011483 } else {
11484 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011485 for (auto Param : FnDecl->params()) {
11486 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011487 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11488 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011489 ClassOrEnumParam = true;
11490 break;
11491 }
11492 }
11493
Douglas Gregord69246b2008-11-17 16:14:12 +000011494 if (!ClassOrEnumParam)
11495 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011496 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011497 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011498 }
11499
11500 // C++ [over.oper]p8:
11501 // An operator function cannot have default arguments (8.3.6),
11502 // except where explicitly stated below.
11503 //
Mike Stump11289f42009-09-09 15:08:12 +000011504 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011505 // (C++ [over.call]p1).
11506 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011507 for (auto Param : FnDecl->params()) {
11508 if (Param->hasDefaultArg())
11509 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011510 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011511 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011512 }
11513 }
11514
Douglas Gregor6cf08062008-11-10 13:38:07 +000011515 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11516 { false, false, false }
11517#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11518 , { Unary, Binary, MemberOnly }
11519#include "clang/Basic/OperatorKinds.def"
11520 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011521
Douglas Gregor6cf08062008-11-10 13:38:07 +000011522 bool CanBeUnaryOperator = OperatorUses[Op][0];
11523 bool CanBeBinaryOperator = OperatorUses[Op][1];
11524 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011525
11526 // C++ [over.oper]p8:
11527 // [...] Operator functions cannot have more or fewer parameters
11528 // than the number required for the corresponding operator, as
11529 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011530 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011531 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011532 if (Op != OO_Call &&
11533 ((NumParams == 1 && !CanBeUnaryOperator) ||
11534 (NumParams == 2 && !CanBeBinaryOperator) ||
11535 (NumParams < 1) || (NumParams > 2))) {
11536 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011537 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011538 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011539 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011540 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011541 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011542 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011543 assert(CanBeBinaryOperator &&
11544 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011545 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011546 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011547
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011548 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011549 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011550 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011551
Douglas Gregord69246b2008-11-17 16:14:12 +000011552 // Overloaded operators other than operator() cannot be variadic.
11553 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011554 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011555 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011556 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011557 }
11558
11559 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011560 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11561 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011562 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011563 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011564 }
11565
11566 // C++ [over.inc]p1:
11567 // The user-defined function called operator++ implements the
11568 // prefix and postfix ++ operator. If this function is a member
11569 // function with no parameters, or a non-member function with one
11570 // parameter of class or enumeration type, it defines the prefix
11571 // increment operator ++ for objects of that type. If the function
11572 // is a member function with one parameter (which shall be of type
11573 // int) or a non-member function with two parameters (the second
11574 // of which shall be of type int), it defines the postfix
11575 // increment operator ++ for objects of that type.
11576 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11577 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011578 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011579
Richard Smith538b52a2014-01-30 22:24:05 +000011580 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11581 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011582 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011583 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011584 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011585 }
11586
Douglas Gregord69246b2008-11-17 16:14:12 +000011587 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011588}
Chris Lattner3b024a32008-12-17 07:09:26 +000011589
Alexis Huntc88db062010-01-13 09:01:02 +000011590/// CheckLiteralOperatorDeclaration - Check whether the declaration
11591/// of this literal operator function is well-formed. If so, returns
11592/// false; otherwise, emits appropriate diagnostics and returns true.
11593bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011594 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011595 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11596 << FnDecl->getDeclName();
11597 return true;
11598 }
11599
Richard Smith72eebee2012-03-04 09:41:16 +000011600 if (FnDecl->isExternC()) {
11601 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11602 return true;
11603 }
11604
Alexis Huntc88db062010-01-13 09:01:02 +000011605 bool Valid = false;
11606
Richard Smithbcc22fc2012-03-09 08:00:36 +000011607 // This might be the definition of a literal operator template.
11608 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11609 // This might be a specialization of a literal operator template.
11610 if (!TpDecl)
11611 TpDecl = FnDecl->getPrimaryTemplate();
11612
Richard Smithb8b41d32013-10-07 19:57:58 +000011613 // template <char...> type operator "" name() and
11614 // template <class T, T...> type operator "" name() are the only valid
11615 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011616 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011617 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011618 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011619 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11620 if (Params->size() == 1) {
11621 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011622 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011623
Alexis Hunt7dd26172010-04-07 23:11:06 +000011624 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011625 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11626 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11627 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011628 } else if (Params->size() == 2) {
11629 TemplateTypeParmDecl *PmType =
11630 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11631 NonTypeTemplateParmDecl *PmArgs =
11632 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11633
11634 // The second template parameter must be a parameter pack with the
11635 // first template parameter as its type.
11636 if (PmType && PmArgs &&
11637 !PmType->isTemplateParameterPack() &&
11638 PmArgs->isTemplateParameterPack()) {
11639 const TemplateTypeParmType *TArgs =
11640 PmArgs->getType()->getAs<TemplateTypeParmType>();
11641 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11642 TArgs->getIndex() == PmType->getIndex()) {
11643 Valid = true;
11644 if (ActiveTemplateInstantiations.empty())
11645 Diag(FnDecl->getLocation(),
11646 diag::ext_string_literal_operator_template);
11647 }
11648 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011649 }
11650 }
Richard Smith72eebee2012-03-04 09:41:16 +000011651 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011652 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011653 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11654
Richard Smith72eebee2012-03-04 09:41:16 +000011655 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011656
Alexis Hunt079a6f72010-04-07 22:57:35 +000011657 // unsigned long long int, long double, and any character type are allowed
11658 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011659 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11660 Context.hasSameType(T, Context.LongDoubleTy) ||
11661 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011662 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011663 Context.hasSameType(T, Context.Char16Ty) ||
11664 Context.hasSameType(T, Context.Char32Ty)) {
11665 if (++Param == FnDecl->param_end())
11666 Valid = true;
11667 goto FinishedParams;
11668 }
11669
Alexis Hunt079a6f72010-04-07 22:57:35 +000011670 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011671 const PointerType *PT = T->getAs<PointerType>();
11672 if (!PT)
11673 goto FinishedParams;
11674 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011675 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011676 goto FinishedParams;
11677 T = T.getUnqualifiedType();
11678
11679 // Move on to the second parameter;
11680 ++Param;
11681
11682 // If there is no second parameter, the first must be a const char *
11683 if (Param == FnDecl->param_end()) {
11684 if (Context.hasSameType(T, Context.CharTy))
11685 Valid = true;
11686 goto FinishedParams;
11687 }
11688
11689 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11690 // are allowed as the first parameter to a two-parameter function
11691 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011692 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011693 Context.hasSameType(T, Context.Char16Ty) ||
11694 Context.hasSameType(T, Context.Char32Ty)))
11695 goto FinishedParams;
11696
11697 // The second and final parameter must be an std::size_t
11698 T = (*Param)->getType().getUnqualifiedType();
11699 if (Context.hasSameType(T, Context.getSizeType()) &&
11700 ++Param == FnDecl->param_end())
11701 Valid = true;
11702 }
11703
11704 // FIXME: This diagnostic is absolutely terrible.
11705FinishedParams:
11706 if (!Valid) {
11707 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11708 << FnDecl->getDeclName();
11709 return true;
11710 }
11711
Richard Smith768cecc2012-03-09 08:16:22 +000011712 // A parameter-declaration-clause containing a default argument is not
11713 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011714 for (auto Param : FnDecl->params()) {
11715 if (Param->hasDefaultArg()) {
11716 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011717 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011718 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011719 break;
11720 }
11721 }
11722
Richard Smith0df56f42012-03-08 02:39:21 +000011723 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011724 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11725 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011726 // C++11 [usrlit.suffix]p1:
11727 // Literal suffix identifiers that do not start with an underscore
11728 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011729 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11730 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011731 }
Richard Smith0df56f42012-03-08 02:39:21 +000011732
Alexis Huntc88db062010-01-13 09:01:02 +000011733 return false;
11734}
11735
Douglas Gregor07665a62009-01-05 19:45:36 +000011736/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11737/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011738/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11739/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011740/// the '{' brace. Otherwise, this linkage specification does not
11741/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011742Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011743 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011744 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011745 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11746 if (!Lit->isAscii()) {
11747 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11748 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011749 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011750 }
11751
11752 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011753 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011754 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011755 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011756 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011757 Language = LinkageSpecDecl::lang_cxx;
11758 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011759 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11760 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011761 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011762 }
Mike Stump11289f42009-09-09 15:08:12 +000011763
Chris Lattner438e5012008-12-17 07:13:27 +000011764 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011765
Richard Smith4ee696d2014-02-17 23:25:27 +000011766 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11767 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011768 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011769 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011770 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011771 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011772}
11773
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011774/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011775/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11776/// valid, it's the position of the closing '}' brace in a linkage
11777/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011778Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011779 Decl *LinkageSpec,
11780 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011781 if (RBraceLoc.isValid()) {
11782 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11783 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011784 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011785 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011786 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011787}
11788
Michael Han84324352013-02-22 17:15:32 +000011789Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11790 AttributeList *AttrList,
11791 SourceLocation SemiLoc) {
11792 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11793 // Attribute declarations appertain to empty declaration so we handle
11794 // them here.
11795 if (AttrList)
11796 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011797
Michael Han84324352013-02-22 17:15:32 +000011798 CurContext->addDecl(ED);
11799 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011800}
11801
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011802/// \brief Perform semantic analysis for the variable declaration that
11803/// occurs within a C++ catch clause, returning the newly-created
11804/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011805VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011806 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011807 SourceLocation StartLoc,
11808 SourceLocation Loc,
11809 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011810 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011811 QualType ExDeclType = TInfo->getType();
11812
Sebastian Redl54c04d42008-12-22 19:15:10 +000011813 // Arrays and functions decay.
11814 if (ExDeclType->isArrayType())
11815 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11816 else if (ExDeclType->isFunctionType())
11817 ExDeclType = Context.getPointerType(ExDeclType);
11818
11819 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11820 // The exception-declaration shall not denote a pointer or reference to an
11821 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011822 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011823 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011824 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011825 Invalid = true;
11826 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011827
Sebastian Redl54c04d42008-12-22 19:15:10 +000011828 QualType BaseType = ExDeclType;
11829 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011830 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011831 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011832 BaseType = Ptr->getPointeeType();
11833 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011834 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011835 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011836 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011837 BaseType = Ref->getPointeeType();
11838 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011839 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011840 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011841 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011842 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011843 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011844
Mike Stump11289f42009-09-09 15:08:12 +000011845 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011846 RequireNonAbstractType(Loc, ExDeclType,
11847 diag::err_abstract_type_in_decl,
11848 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011849 Invalid = true;
11850
John McCall2ca705e2010-07-24 00:37:23 +000011851 // Only the non-fragile NeXT runtime currently supports C++ catches
11852 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011853 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011854 QualType T = ExDeclType;
11855 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11856 T = RT->getPointeeType();
11857
11858 if (T->isObjCObjectType()) {
11859 Diag(Loc, diag::err_objc_object_catch);
11860 Invalid = true;
11861 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011862 // FIXME: should this be a test for macosx-fragile specifically?
11863 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011864 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011865 }
11866 }
11867
Abramo Bagnaradff19302011-03-08 08:55:46 +000011868 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011869 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011870 ExDecl->setExceptionVariable(true);
11871
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011872 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011873 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011874 Invalid = true;
11875
Douglas Gregor750734c2011-07-06 18:14:43 +000011876 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011877 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011878 // Insulate this from anything else we might currently be parsing.
11879 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11880
Douglas Gregor6de584c2010-03-05 23:38:39 +000011881 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011882 // The object declared in an exception-declaration or, if the
11883 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011884 // copy-initialized (8.5) from the exception object. [...]
11885 // The object is destroyed when the handler exits, after the destruction
11886 // of any automatic objects initialized within the handler.
11887 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011888 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011889 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011890 QualType initType = ExDeclType;
11891
11892 InitializedEntity entity =
11893 InitializedEntity::InitializeVariable(ExDecl);
11894 InitializationKind initKind =
11895 InitializationKind::CreateCopy(Loc, SourceLocation());
11896
11897 Expr *opaqueValue =
11898 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011899 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11900 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011901 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011902 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011903 else {
11904 // If the constructor used was non-trivial, set this as the
11905 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011906 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011907 if (!construct->getConstructor()->isTrivial()) {
11908 Expr *init = MaybeCreateExprWithCleanups(construct);
11909 ExDecl->setInit(init);
11910 }
11911
11912 // And make sure it's destructable.
11913 FinalizeVarWithDestructor(ExDecl, recordType);
11914 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011915 }
11916 }
11917
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011918 if (Invalid)
11919 ExDecl->setInvalidDecl();
11920
11921 return ExDecl;
11922}
11923
11924/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11925/// handler.
John McCall48871652010-08-21 09:40:31 +000011926Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011927 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011928 bool Invalid = D.isInvalidType();
11929
11930 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011931 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11932 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011933 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11934 D.getIdentifierLoc());
11935 Invalid = true;
11936 }
11937
Sebastian Redl54c04d42008-12-22 19:15:10 +000011938 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011939 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011940 LookupOrdinaryName,
11941 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011942 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011943 // it contains any previous declaration, except for function parameters in
11944 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011945 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011946 if (isDeclInScope(PrevDecl, CurContext, S)) {
11947 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11948 << D.getIdentifier();
11949 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11950 Invalid = true;
11951 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011952 // Maybe we will complain about the shadowed template parameter.
11953 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011954 }
11955
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011956 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011957 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11958 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011959 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011960 }
11961
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011962 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011963 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011964 D.getIdentifierLoc(),
11965 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011966 if (Invalid)
11967 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011968
Sebastian Redl54c04d42008-12-22 19:15:10 +000011969 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011970 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011971 PushOnScopeChains(ExDecl, S);
11972 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011973 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011974
Douglas Gregor758a8692009-06-17 21:51:59 +000011975 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011976 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011977}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011978
Abramo Bagnaraea947882011-03-08 16:41:52 +000011979Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011980 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011981 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011982 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011983 StringLiteral *AssertMessage =
11984 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011985
Richard Smithded9c2e2012-07-11 22:37:56 +000011986 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011987 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011988
11989 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11990 AssertMessage, RParenLoc, false);
11991}
11992
11993Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11994 Expr *AssertExpr,
11995 StringLiteral *AssertMessage,
11996 SourceLocation RParenLoc,
11997 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011998 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011999 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12000 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012001 // In a static_assert-declaration, the constant-expression shall be a
12002 // constant expression that can be contextually converted to bool.
12003 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12004 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012005 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012006
Richard Smith902ca212011-12-14 23:32:26 +000012007 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012008 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012009 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012010 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012011 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012012
Richard Smithded9c2e2012-07-11 22:37:56 +000012013 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012014 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012015 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012016 if (AssertMessage)
12017 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012018 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012019 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012020 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012021 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012022 }
Mike Stump11289f42009-09-09 15:08:12 +000012023
Abramo Bagnaraea947882011-03-08 16:41:52 +000012024 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012025 AssertExpr, AssertMessage, RParenLoc,
12026 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012027
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012028 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012029 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012030}
Sebastian Redlf769df52009-03-24 22:27:57 +000012031
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012032/// \brief Perform semantic analysis of the given friend type declaration.
12033///
12034/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012035FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012036 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012037 TypeSourceInfo *TSInfo) {
12038 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12039
12040 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012041 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012042
Richard Smithc8239732011-10-18 21:39:00 +000012043 // C++03 [class.friend]p2:
12044 // An elaborated-type-specifier shall be used in a friend declaration
12045 // for a class.*
12046 //
12047 // * The class-key of the elaborated-type-specifier is required.
12048 if (!ActiveTemplateInstantiations.empty()) {
12049 // Do not complain about the form of friend template types during
12050 // template instantiation; we will already have complained when the
12051 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012052 } else {
12053 if (!T->isElaboratedTypeSpecifier()) {
12054 // If we evaluated the type to a record type, suggest putting
12055 // a tag in front.
12056 if (const RecordType *RT = T->getAs<RecordType>()) {
12057 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012058
12059 SmallString<16> InsertionText(" ");
12060 InsertionText += RD->getKindName();
12061
Nick Lewycky36722d22013-02-06 05:59:33 +000012062 Diag(TypeRange.getBegin(),
12063 getLangOpts().CPlusPlus11 ?
12064 diag::warn_cxx98_compat_unelaborated_friend_type :
12065 diag::ext_unelaborated_friend_type)
12066 << (unsigned) RD->getTagKind()
12067 << T
12068 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12069 InsertionText);
12070 } else {
12071 Diag(FriendLoc,
12072 getLangOpts().CPlusPlus11 ?
12073 diag::warn_cxx98_compat_nonclass_type_friend :
12074 diag::ext_nonclass_type_friend)
12075 << T
12076 << TypeRange;
12077 }
12078 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012079 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012080 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012081 diag::warn_cxx98_compat_enum_friend :
12082 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012083 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012084 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012085 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012086
Nick Lewycky36722d22013-02-06 05:59:33 +000012087 // C++11 [class.friend]p3:
12088 // A friend declaration that does not declare a function shall have one
12089 // of the following forms:
12090 // friend elaborated-type-specifier ;
12091 // friend simple-type-specifier ;
12092 // friend typename-specifier ;
12093 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12094 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12095 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012096
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012097 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012098 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012099 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012100 return FriendDecl::Create(Context, CurContext,
12101 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12102 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012103}
12104
John McCallace48cd2010-10-19 01:40:49 +000012105/// Handle a friend tag declaration where the scope specifier was
12106/// templated.
12107Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12108 unsigned TagSpec, SourceLocation TagLoc,
12109 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012110 IdentifierInfo *Name,
12111 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012112 AttributeList *Attr,
12113 MultiTemplateParamsArg TempParamLists) {
12114 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12115
12116 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012117 bool Invalid = false;
12118
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012119 if (TemplateParameterList *TemplateParams =
12120 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012121 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012122 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012123 if (TemplateParams->size() > 0) {
12124 // This is a declaration of a class template.
12125 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012126 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012127
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012128 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12129 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012130 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012131 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012132 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012133 } else {
12134 // The "template<>" header is extraneous.
12135 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12136 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12137 isExplicitSpecialization = true;
12138 }
12139 }
12140
Craig Topperc3ec1492014-05-26 06:22:03 +000012141 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012142
John McCallace48cd2010-10-19 01:40:49 +000012143 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012144 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012145 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012146 isAllExplicitSpecializations = false;
12147 break;
12148 }
12149 }
12150
12151 // FIXME: don't ignore attributes.
12152
12153 // If it's explicit specializations all the way down, just forget
12154 // about the template header and build an appropriate non-templated
12155 // friend. TODO: for source fidelity, remember the headers.
12156 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012157 if (SS.isEmpty()) {
12158 bool Owned = false;
12159 bool IsDependent = false;
12160 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012161 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012162 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012163 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012164 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012165 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012166 /*UnderlyingType=*/TypeResult(),
12167 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012168 }
Richard Smith649c7b062014-01-08 00:56:48 +000012169
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012170 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012171 ElaboratedTypeKeyword Keyword
12172 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012173 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012174 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012175 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012176 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012177
12178 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12179 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012180 DependentNameTypeLoc TL =
12181 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012182 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012183 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012184 TL.setNameLoc(NameLoc);
12185 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012186 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012187 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012188 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012189 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012190 }
12191
12192 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012193 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012194 Friend->setAccess(AS_public);
12195 CurContext->addDecl(Friend);
12196 return Friend;
12197 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012198
12199 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12200
12201
John McCallace48cd2010-10-19 01:40:49 +000012202
12203 // Handle the case of a templated-scope friend class. e.g.
12204 // template <class T> class A<T>::B;
12205 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012206 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12207 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012208 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12209 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12210 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012211 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012212 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012213 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012214 TL.setNameLoc(NameLoc);
12215
12216 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012217 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012218 Friend->setAccess(AS_public);
12219 Friend->setUnsupportedFriend(true);
12220 CurContext->addDecl(Friend);
12221 return Friend;
12222}
12223
12224
John McCall11083da2009-09-16 22:47:08 +000012225/// Handle a friend type declaration. This works in tandem with
12226/// ActOnTag.
12227///
12228/// Notes on friend class templates:
12229///
12230/// We generally treat friend class declarations as if they were
12231/// declaring a class. So, for example, the elaborated type specifier
12232/// in a friend declaration is required to obey the restrictions of a
12233/// class-head (i.e. no typedefs in the scope chain), template
12234/// parameters are required to match up with simple template-ids, &c.
12235/// However, unlike when declaring a template specialization, it's
12236/// okay to refer to a template specialization without an empty
12237/// template parameter declaration, e.g.
12238/// friend class A<T>::B<unsigned>;
12239/// We permit this as a special case; if there are any template
12240/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012241/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012242Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012243 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012244 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012245
12246 assert(DS.isFriendSpecified());
12247 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12248
John McCall11083da2009-09-16 22:47:08 +000012249 // Try to convert the decl specifier to a type. This works for
12250 // friend templates because ActOnTag never produces a ClassTemplateDecl
12251 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012252 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012253 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12254 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012255 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012256 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012257
Douglas Gregor6c110f32010-12-16 01:14:37 +000012258 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012259 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012260
John McCall11083da2009-09-16 22:47:08 +000012261 // This is definitely an error in C++98. It's probably meant to
12262 // be forbidden in C++0x, too, but the specification is just
12263 // poorly written.
12264 //
12265 // The problem is with declarations like the following:
12266 // template <T> friend A<T>::foo;
12267 // where deciding whether a class C is a friend or not now hinges
12268 // on whether there exists an instantiation of A that causes
12269 // 'foo' to equal C. There are restrictions on class-heads
12270 // (which we declare (by fiat) elaborated friend declarations to
12271 // be) that makes this tractable.
12272 //
12273 // FIXME: handle "template <> friend class A<T>;", which
12274 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012275 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012276 Diag(Loc, diag::err_tagless_friend_type_template)
12277 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012278 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012279 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012280
John McCallaa74a0c2009-08-28 07:59:38 +000012281 // C++98 [class.friend]p1: A friend of a class is a function
12282 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012283 // This is fixed in DR77, which just barely didn't make the C++03
12284 // deadline. It's also a very silly restriction that seriously
12285 // affects inner classes and which nobody else seems to implement;
12286 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012287 //
12288 // But note that we could warn about it: it's always useless to
12289 // friend one of your own members (it's not, however, worthless to
12290 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012291
John McCall11083da2009-09-16 22:47:08 +000012292 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012293 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012294 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012295 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012296 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012297 TSI,
John McCall11083da2009-09-16 22:47:08 +000012298 DS.getFriendSpecLoc());
12299 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012300 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012301
12302 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012303 return nullptr;
12304
John McCall11083da2009-09-16 22:47:08 +000012305 D->setAccess(AS_public);
12306 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012307
John McCall48871652010-08-21 09:40:31 +000012308 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012309}
12310
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012311NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12312 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012313 const DeclSpec &DS = D.getDeclSpec();
12314
12315 assert(DS.isFriendSpecified());
12316 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12317
12318 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012319 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012320
12321 // C++ [class.friend]p1
12322 // A friend of a class is a function or class....
12323 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012324 // It *doesn't* see through dependent types, which is correct
12325 // according to [temp.arg.type]p3:
12326 // If a declaration acquires a function type through a
12327 // type dependent on a template-parameter and this causes
12328 // a declaration that does not use the syntactic form of a
12329 // function declarator to have a function type, the program
12330 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012331 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012332 Diag(Loc, diag::err_unexpected_friend);
12333
12334 // It might be worthwhile to try to recover by creating an
12335 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012336 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012337 }
12338
12339 // C++ [namespace.memdef]p3
12340 // - If a friend declaration in a non-local class first declares a
12341 // class or function, the friend class or function is a member
12342 // of the innermost enclosing namespace.
12343 // - The name of the friend is not found by simple name lookup
12344 // until a matching declaration is provided in that namespace
12345 // scope (either before or after the class declaration granting
12346 // friendship).
12347 // - If a friend function is called, its name may be found by the
12348 // name lookup that considers functions from namespaces and
12349 // classes associated with the types of the function arguments.
12350 // - When looking for a prior declaration of a class or a function
12351 // declared as a friend, scopes outside the innermost enclosing
12352 // namespace scope are not considered.
12353
John McCallde3fd222010-10-12 23:13:28 +000012354 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012355 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12356 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012357 assert(Name);
12358
Douglas Gregor6c110f32010-12-16 01:14:37 +000012359 // Check for unexpanded parameter packs.
12360 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12361 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12362 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012363 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012364
John McCall07e91c02009-08-06 02:15:43 +000012365 // The context we found the declaration in, or in which we should
12366 // create the declaration.
12367 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012368 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012369 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012370 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012371
Richard Smith114394f2013-08-09 04:35:01 +000012372 // There are five cases here.
12373 // - There's no scope specifier and we're in a local class. Only look
12374 // for functions declared in the immediately-enclosing block scope.
12375 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012376 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012377 if ((SS.isInvalid() || !SS.isSet()) &&
12378 (FunctionContainingLocalClass =
12379 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12380 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012381 // If a friend declaration appears in a local class and the name
12382 // specified is an unqualified name, a prior declaration is
12383 // looked up without considering scopes that are outside the
12384 // innermost enclosing non-class scope. For a friend function
12385 // declaration, if there is no prior declaration, the program is
12386 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012387
12388 // Find the innermost enclosing non-class scope. This is the block
12389 // scope containing the local class definition (or for a nested class,
12390 // the outer local class).
12391 DCScope = S->getFnParent();
12392
12393 // Look up the function name in the scope.
12394 Previous.clear(LookupLocalFriendName);
12395 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12396
12397 if (!Previous.empty()) {
12398 // All possible previous declarations must have the same context:
12399 // either they were declared at block scope or they are members of
12400 // one of the enclosing local classes.
12401 DC = Previous.getRepresentativeDecl()->getDeclContext();
12402 } else {
12403 // This is ill-formed, but provide the context that we would have
12404 // declared the function in, if we were permitted to, for error recovery.
12405 DC = FunctionContainingLocalClass;
12406 }
Richard Smith541b38b2013-09-20 01:15:31 +000012407 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012408
12409 // C++ [class.friend]p6:
12410 // A function can be defined in a friend declaration of a class if and
12411 // only if the class is a non-local class (9.8), the function name is
12412 // unqualified, and the function has namespace scope.
12413 if (D.isFunctionDefinition()) {
12414 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12415 }
12416
12417 // - There's no scope specifier, in which case we just go to the
12418 // appropriate scope and look for a function or function template
12419 // there as appropriate.
12420 } else if (SS.isInvalid() || !SS.isSet()) {
12421 // C++11 [namespace.memdef]p3:
12422 // If the name in a friend declaration is neither qualified nor
12423 // a template-id and the declaration is a function or an
12424 // elaborated-type-specifier, the lookup to determine whether
12425 // the entity has been previously declared shall not consider
12426 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012427 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012428
John McCallf7cfb222010-10-13 05:45:15 +000012429 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012430 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012431
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012432 // Skip class contexts. If someone can cite chapter and verse
12433 // for this behavior, that would be nice --- it's what GCC and
12434 // EDG do, and it seems like a reasonable intent, but the spec
12435 // really only says that checks for unqualified existing
12436 // declarations should stop at the nearest enclosing namespace,
12437 // not that they should only consider the nearest enclosing
12438 // namespace.
12439 while (DC->isRecord())
12440 DC = DC->getParent();
12441
12442 DeclContext *LookupDC = DC;
12443 while (LookupDC->isTransparentContext())
12444 LookupDC = LookupDC->getParent();
12445
12446 while (true) {
12447 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012448
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012449 if (!Previous.empty()) {
12450 DC = LookupDC;
12451 break;
John McCallf4776592010-10-14 22:22:28 +000012452 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012453
12454 if (isTemplateId) {
12455 if (isa<TranslationUnitDecl>(LookupDC)) break;
12456 } else {
12457 if (LookupDC->isFileContext()) break;
12458 }
12459 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012460 }
12461
John McCallccbc0322010-10-13 06:22:15 +000012462 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012463
John McCallde3fd222010-10-12 23:13:28 +000012464 // - There's a non-dependent scope specifier, in which case we
12465 // compute it and do a previous lookup there for a function
12466 // or function template.
12467 } else if (!SS.getScopeRep()->isDependent()) {
12468 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012469 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012470
Craig Topperc3ec1492014-05-26 06:22:03 +000012471 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012472
12473 LookupQualifiedName(Previous, DC);
12474
12475 // Ignore things found implicitly in the wrong scope.
12476 // TODO: better diagnostics for this case. Suggesting the right
12477 // qualified scope would be nice...
12478 LookupResult::Filter F = Previous.makeFilter();
12479 while (F.hasNext()) {
12480 NamedDecl *D = F.next();
12481 if (!DC->InEnclosingNamespaceSetOf(
12482 D->getDeclContext()->getRedeclContext()))
12483 F.erase();
12484 }
12485 F.done();
12486
12487 if (Previous.empty()) {
12488 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012489 Diag(Loc, diag::err_qualified_friend_not_found)
12490 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012491 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012492 }
12493
12494 // C++ [class.friend]p1: A friend of a class is a function or
12495 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012496 if (DC->Equals(CurContext))
12497 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012498 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012499 diag::warn_cxx98_compat_friend_is_member :
12500 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012501
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012502 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012503 // C++ [class.friend]p6:
12504 // A function can be defined in a friend declaration of a class if and
12505 // only if the class is a non-local class (9.8), the function name is
12506 // unqualified, and the function has namespace scope.
12507 SemaDiagnosticBuilder DB
12508 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12509
12510 DB << SS.getScopeRep();
12511 if (DC->isFileContext())
12512 DB << FixItHint::CreateRemoval(SS.getRange());
12513 SS.clear();
12514 }
John McCallde3fd222010-10-12 23:13:28 +000012515
12516 // - There's a scope specifier that does not match any template
12517 // parameter lists, in which case we use some arbitrary context,
12518 // create a method or method template, and wait for instantiation.
12519 // - There's a scope specifier that does match some template
12520 // parameter lists, which we don't handle right now.
12521 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012522 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012523 // C++ [class.friend]p6:
12524 // A function can be defined in a friend declaration of a class if and
12525 // only if the class is a non-local class (9.8), the function name is
12526 // unqualified, and the function has namespace scope.
12527 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12528 << SS.getScopeRep();
12529 }
12530
John McCallde3fd222010-10-12 23:13:28 +000012531 DC = CurContext;
12532 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012533 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012534
John McCallf7cfb222010-10-13 05:45:15 +000012535 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012536 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012537 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12538 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12539 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012540 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012541 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12542 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012543 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012544 }
John McCall07e91c02009-08-06 02:15:43 +000012545 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012546
Douglas Gregordd847ba2011-11-03 16:37:14 +000012547 // FIXME: This is an egregious hack to cope with cases where the scope stack
12548 // does not contain the declaration context, i.e., in an out-of-line
12549 // definition of a class.
12550 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12551 if (!DCScope) {
12552 FakeDCScope.setEntity(DC);
12553 DCScope = &FakeDCScope;
12554 }
Richard Smith114394f2013-08-09 04:35:01 +000012555
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012556 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012557 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012558 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012559 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012560
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012561 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012562
Richard Smith114394f2013-08-09 04:35:01 +000012563 // If we performed typo correction, we might have added a scope specifier
12564 // and changed the decl context.
12565 DC = ND->getDeclContext();
12566
John McCall759e32b2009-08-31 22:39:49 +000012567 // Add the function declaration to the appropriate lookup tables,
12568 // adjusting the redeclarations list as necessary. We don't
12569 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012570 //
John McCall759e32b2009-08-31 22:39:49 +000012571 // Also update the scope-based lookup if the target context's
12572 // lookup context is in lexical scope.
12573 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012574 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012575 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012576 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012577 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012578 }
John McCallaa74a0c2009-08-28 07:59:38 +000012579
12580 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012581 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012582 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012583 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012584 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012585
John McCalla0a96892012-08-10 03:15:35 +000012586 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012587 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012588 } else {
12589 if (DC->isRecord()) CheckFriendAccess(ND);
12590
John McCall2c2eb122010-10-16 06:59:13 +000012591 FunctionDecl *FD;
12592 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12593 FD = FTD->getTemplatedDecl();
12594 else
12595 FD = cast<FunctionDecl>(ND);
12596
David Majnemer502b0ed2013-06-25 23:09:30 +000012597 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12598 // default argument expression, that declaration shall be a definition
12599 // and shall be the only declaration of the function or function
12600 // template in the translation unit.
12601 if (functionDeclHasDefaultArgument(FD)) {
12602 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12603 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12604 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12605 } else if (!D.isFunctionDefinition())
12606 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12607 }
12608
John McCall2c2eb122010-10-16 06:59:13 +000012609 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012610 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12611 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12612 << SS.getScopeRep() << SS.getRange()
12613 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012614 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012615 }
John McCall2c2eb122010-10-16 06:59:13 +000012616 }
John McCallde3fd222010-10-12 23:13:28 +000012617
John McCall48871652010-08-21 09:40:31 +000012618 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012619}
12620
John McCall48871652010-08-21 09:40:31 +000012621void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12622 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012623
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012624 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012625 if (!Fn) {
12626 Diag(DelLoc, diag::err_deleted_non_function);
12627 return;
12628 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012629
Douglas Gregorec9fd132012-01-14 16:38:05 +000012630 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012631 // Don't consider the implicit declaration we generate for explicit
12632 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012633 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12634 Prev->getPreviousDecl()) &&
12635 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012636 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012637 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12638 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12639 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012640 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012641 // If the declaration wasn't the first, we delete the function anyway for
12642 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012643 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012644 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012645
Nico Rieck9de0a572014-05-29 16:51:19 +000012646 // dllimport/dllexport cannot be deleted.
12647 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12648 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12649 Fn->setInvalidDecl();
12650 }
12651
Richard Smithb4d2a152013-04-02 19:38:47 +000012652 if (Fn->isDeleted())
12653 return;
12654
12655 // See if we're deleting a function which is already known to override a
12656 // non-deleted virtual function.
12657 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12658 bool IssuedDiagnostic = false;
12659 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12660 E = MD->end_overridden_methods();
12661 I != E; ++I) {
12662 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12663 if (!IssuedDiagnostic) {
12664 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12665 IssuedDiagnostic = true;
12666 }
12667 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12668 }
12669 }
12670 }
12671
Richard Smithb63b6ee2014-01-22 01:43:19 +000012672 // C++11 [basic.start.main]p3:
12673 // A program that defines main as deleted [...] is ill-formed.
12674 if (Fn->isMain())
12675 Diag(DelLoc, diag::err_deleted_main);
12676
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012677 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012678}
Sebastian Redl4c018662009-04-27 21:33:24 +000012679
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012680void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012681 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012682
12683 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012684 if (MD->getParent()->isDependentType()) {
12685 MD->setDefaulted();
12686 MD->setExplicitlyDefaulted();
12687 return;
12688 }
12689
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012690 CXXSpecialMember Member = getSpecialMember(MD);
12691 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012692 if (!MD->isInvalidDecl())
12693 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012694 return;
12695 }
12696
12697 MD->setDefaulted();
12698 MD->setExplicitlyDefaulted();
12699
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012700 // If this definition appears within the record, do the checking when
12701 // the record is complete.
12702 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012703 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012704 // Find the uninstantiated declaration that actually had the '= default'
12705 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012706 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012707
Richard Smith3901dfe2013-03-27 00:22:47 +000012708 // If the method was defaulted on its first declaration, we will have
12709 // already performed the checking in CheckCompletedCXXClass. Such a
12710 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012711 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012712 return;
12713
Richard Smithd3b5c9082012-07-27 04:22:15 +000012714 CheckExplicitlyDefaultedSpecialMember(MD);
12715
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012716 if (MD->isInvalidDecl())
12717 return;
12718
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012719 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012720 case CXXDefaultConstructor:
12721 DefineImplicitDefaultConstructor(DefaultLoc,
12722 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012723 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012724 case CXXCopyConstructor:
12725 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012726 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012727 case CXXCopyAssignment:
12728 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012729 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012730 case CXXDestructor:
12731 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012732 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012733 case CXXMoveConstructor:
12734 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012735 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012736 case CXXMoveAssignment:
12737 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012738 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012739 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012740 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012741 }
12742 } else {
12743 Diag(DefaultLoc, diag::err_default_special_members);
12744 }
12745}
12746
Sebastian Redl4c018662009-04-27 21:33:24 +000012747static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012748 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012749 Stmt *SubStmt = *CI;
12750 if (!SubStmt)
12751 continue;
12752 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012753 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012754 diag::err_return_in_constructor_handler);
12755 if (!isa<Expr>(SubStmt))
12756 SearchForReturnInStmt(Self, SubStmt);
12757 }
12758}
12759
12760void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12761 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12762 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12763 SearchForReturnInStmt(*this, Handler);
12764 }
12765}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012766
David Blaikie68f71a32013-01-18 23:03:15 +000012767bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012768 const CXXMethodDecl *Old) {
12769 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12770 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12771
12772 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12773
12774 // If the calling conventions match, everything is fine
12775 if (NewCC == OldCC)
12776 return false;
12777
Hans Wennborg2545efe2013-12-11 17:42:11 +000012778 // If the calling conventions mismatch because the new function is static,
12779 // suppress the calling convention mismatch error; the error about static
12780 // function override (err_static_overrides_virtual from
12781 // Sema::CheckFunctionDeclaration) is more clear.
12782 if (New->getStorageClass() == SC_Static)
12783 return false;
12784
Reid Kleckner78af0702013-08-27 23:08:25 +000012785 Diag(New->getLocation(),
12786 diag::err_conflicting_overriding_cc_attributes)
12787 << New->getDeclName() << New->getType() << Old->getType();
12788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12789 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012790}
12791
Mike Stump11289f42009-09-09 15:08:12 +000012792bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012793 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012794 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12795 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012796
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012797 if (Context.hasSameType(NewTy, OldTy) ||
12798 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012799 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012800
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012801 // Check if the return types are covariant
12802 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012803
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012804 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012805 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12806 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012807 NewClassTy = NewPT->getPointeeType();
12808 OldClassTy = OldPT->getPointeeType();
12809 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012810 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12811 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12812 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12813 NewClassTy = NewRT->getPointeeType();
12814 OldClassTy = OldRT->getPointeeType();
12815 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012816 }
12817 }
Mike Stump11289f42009-09-09 15:08:12 +000012818
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012819 // The return types aren't either both pointers or references to a class type.
12820 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012821 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012822 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012823 << New->getDeclName() << NewTy << OldTy
12824 << New->getReturnTypeSourceRange();
12825 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12826 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012827
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012828 return true;
12829 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012830
Anders Carlssone60365b2009-12-31 18:34:24 +000012831 // C++ [class.virtual]p6:
12832 // If the return type of D::f differs from the return type of B::f, the
12833 // class type in the return type of D::f shall be complete at the point of
12834 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012835 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12836 if (!RT->isBeingDefined() &&
12837 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012838 diag::err_covariant_return_incomplete,
12839 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012840 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012841 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012842
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012843 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012844 // Check if the new class derives from the old class.
12845 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012846 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12847 << New->getDeclName() << NewTy << OldTy
12848 << New->getReturnTypeSourceRange();
12849 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12850 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012851 return true;
12852 }
Mike Stump11289f42009-09-09 15:08:12 +000012853
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012854 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012855 if (CheckDerivedToBaseConversion(
12856 NewClassTy, OldClassTy,
12857 diag::err_covariant_return_inaccessible_base,
12858 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12859 New->getLocation(), New->getReturnTypeSourceRange(),
12860 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012861 // FIXME: this note won't trigger for delayed access control
12862 // diagnostics, and it's impossible to get an undelayed error
12863 // here from access control during the original parse because
12864 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012865 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12866 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012867 return true;
12868 }
12869 }
Mike Stump11289f42009-09-09 15:08:12 +000012870
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012871 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012872 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012873 Diag(New->getLocation(),
12874 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012875 << New->getDeclName() << NewTy << OldTy
12876 << New->getReturnTypeSourceRange();
12877 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12878 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012879 return true;
12880 };
Mike Stump11289f42009-09-09 15:08:12 +000012881
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012882
12883 // The new class type must have the same or less qualifiers as the old type.
12884 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12885 Diag(New->getLocation(),
12886 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012887 << New->getDeclName() << NewTy << OldTy
12888 << New->getReturnTypeSourceRange();
12889 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12890 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012891 return true;
12892 };
Mike Stump11289f42009-09-09 15:08:12 +000012893
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012894 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012895}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012896
Douglas Gregor21920e372009-12-01 17:24:26 +000012897/// \brief Mark the given method pure.
12898///
12899/// \param Method the method to be marked pure.
12900///
12901/// \param InitRange the source range that covers the "0" initializer.
12902bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012903 SourceLocation EndLoc = InitRange.getEnd();
12904 if (EndLoc.isValid())
12905 Method->setRangeEnd(EndLoc);
12906
Douglas Gregor21920e372009-12-01 17:24:26 +000012907 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12908 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012909 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012910 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012911
12912 if (!Method->isInvalidDecl())
12913 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12914 << Method->getDeclName() << InitRange;
12915 return true;
12916}
12917
Douglas Gregor926410d2012-02-21 02:22:07 +000012918/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012919static bool isStaticDataMember(const Decl *D) {
12920 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12921 return Var->isStaticDataMember();
12922
12923 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012924}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012925
John McCall1f4ee7b2009-12-19 09:28:58 +000012926/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12927/// an initializer for the out-of-line declaration 'Dcl'. The scope
12928/// is a fresh scope pushed for just this purpose.
12929///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012930/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12931/// static data member of class X, names should be looked up in the scope of
12932/// class X.
John McCall48871652010-08-21 09:40:31 +000012933void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012934 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012935 if (!D || D->isInvalidDecl())
12936 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012937
Richard Smitha2302242013-12-05 07:51:02 +000012938 // We will always have a nested name specifier here, but this declaration
12939 // might not be out of line if the specifier names the current namespace:
12940 // extern int n;
12941 // int ::n = 0;
12942 if (D->isOutOfLine())
12943 EnterDeclaratorContext(S, D->getDeclContext());
12944
Douglas Gregor926410d2012-02-21 02:22:07 +000012945 // If we are parsing the initializer for a static data member, push a
12946 // new expression evaluation context that is associated with this static
12947 // data member.
12948 if (isStaticDataMember(D))
12949 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012950}
12951
12952/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012953/// initializer for the out-of-line declaration 'D'.
12954void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012955 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012956 if (!D || D->isInvalidDecl())
12957 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012958
Douglas Gregor926410d2012-02-21 02:22:07 +000012959 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012960 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012961
Richard Smitha2302242013-12-05 07:51:02 +000012962 if (D->isOutOfLine())
12963 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012964}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012965
12966/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12967/// C++ if/switch/while/for statement.
12968/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012969DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012970 // C++ 6.4p2:
12971 // The declarator shall not specify a function or an array.
12972 // The type-specifier-seq shall not contain typedef and shall not declare a
12973 // new class or enumeration.
12974 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12975 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012976
12977 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012978 if (!Dcl)
12979 return true;
12980
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012981 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12982 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012983 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012984 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012985 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012986
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012987 return Dcl;
12988}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012989
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012990void Sema::LoadExternalVTableUses() {
12991 if (!ExternalSource)
12992 return;
12993
12994 SmallVector<ExternalVTableUse, 4> VTables;
12995 ExternalSource->ReadUsedVTables(VTables);
12996 SmallVector<VTableUse, 4> NewUses;
12997 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12998 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12999 = VTablesUsed.find(VTables[I].Record);
13000 // Even if a definition wasn't required before, it may be required now.
13001 if (Pos != VTablesUsed.end()) {
13002 if (!Pos->second && VTables[I].DefinitionRequired)
13003 Pos->second = true;
13004 continue;
13005 }
13006
13007 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13008 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13009 }
13010
13011 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13012}
13013
Douglas Gregor88d292c2010-05-13 16:44:06 +000013014void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13015 bool DefinitionRequired) {
13016 // Ignore any vtable uses in unevaluated operands or for classes that do
13017 // not have a vtable.
13018 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013019 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013020 return;
13021
Douglas Gregor88d292c2010-05-13 16:44:06 +000013022 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013023 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013024 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13025 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13026 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13027 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013028 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013029 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013030 // list, since we may have already processed the first entry.
13031 if (DefinitionRequired && !Pos.first->second) {
13032 Pos.first->second = true;
13033 } else {
13034 // Otherwise, we can early exit.
13035 return;
13036 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013037 } else {
13038 // The Microsoft ABI requires that we perform the destructor body
13039 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13040 // the deleting destructor is emitted with the vtable, not with the
13041 // destructor definition as in the Itanium ABI.
13042 // If it has a definition, we do the check at that point instead.
13043 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13044 Class->hasUserDeclaredDestructor() &&
13045 !Class->getDestructor()->isDefined() &&
13046 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013047 CXXDestructorDecl *DD = Class->getDestructor();
13048 ContextRAII SavedContext(*this, DD);
13049 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013050 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013051 }
13052
13053 // Local classes need to have their virtual members marked
13054 // immediately. For all other classes, we mark their virtual members
13055 // at the end of the translation unit.
13056 if (Class->isLocalClass())
13057 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013058 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013059 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013060}
13061
Douglas Gregor88d292c2010-05-13 16:44:06 +000013062bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013063 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013064 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013065 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013066
Douglas Gregor88d292c2010-05-13 16:44:06 +000013067 // Note: The VTableUses vector could grow as a result of marking
13068 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013069 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013070 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013071 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013072 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013073 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013074 if (!Class)
13075 continue;
13076
13077 SourceLocation Loc = VTableUses[I].second;
13078
Richard Smithd3b5c9082012-07-27 04:22:15 +000013079 bool DefineVTable = true;
13080
Douglas Gregor88d292c2010-05-13 16:44:06 +000013081 // If this class has a key function, but that key function is
13082 // defined in another translation unit, we don't need to emit the
13083 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013084 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013085 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013086 // The key function is in another translation unit.
13087 DefineVTable = false;
13088 TemplateSpecializationKind TSK =
13089 KeyFunction->getTemplateSpecializationKind();
13090 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13091 TSK != TSK_ImplicitInstantiation &&
13092 "Instantiations don't have key functions");
13093 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013094 } else if (!KeyFunction) {
13095 // If we have a class with no key function that is the subject
13096 // of an explicit instantiation declaration, suppress the
13097 // vtable; it will live with the explicit instantiation
13098 // definition.
13099 bool IsExplicitInstantiationDeclaration
13100 = Class->getTemplateSpecializationKind()
13101 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013102 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013103 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013104 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013105 if (TSK == TSK_ExplicitInstantiationDeclaration)
13106 IsExplicitInstantiationDeclaration = true;
13107 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13108 IsExplicitInstantiationDeclaration = false;
13109 break;
13110 }
13111 }
13112
13113 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013114 DefineVTable = false;
13115 }
13116
13117 // The exception specifications for all virtual members may be needed even
13118 // if we are not providing an authoritative form of the vtable in this TU.
13119 // We may choose to emit it available_externally anyway.
13120 if (!DefineVTable) {
13121 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13122 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013123 }
13124
13125 // Mark all of the virtual members of this class as referenced, so
13126 // that we can build a vtable. Then, tell the AST consumer that a
13127 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013128 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013129 MarkVirtualMembersReferenced(Loc, Class);
13130 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013131 if (VTablesUsed[Canonical])
13132 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013133
13134 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013135 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013136 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013137 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013138 if (!KeyFunction ||
13139 (KeyFunction->hasBody(KeyFunctionDef) &&
13140 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013141 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13142 TSK_ExplicitInstantiationDefinition
13143 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13144 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013145 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013146 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013147 VTableUses.clear();
13148
Douglas Gregor97509692011-04-22 22:25:37 +000013149 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013150}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013151
Richard Smithd3b5c9082012-07-27 04:22:15 +000013152void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13153 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013154 for (const auto *I : RD->methods())
13155 if (I->isVirtual() && !I->isPure())
13156 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013157}
13158
Rafael Espindola5b334082010-03-26 00:36:59 +000013159void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13160 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013161 // Mark all functions which will appear in RD's vtable as used.
13162 CXXFinalOverriderMap FinalOverriders;
13163 RD->getFinalOverriders(FinalOverriders);
13164 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13165 E = FinalOverriders.end();
13166 I != E; ++I) {
13167 for (OverridingMethods::const_iterator OI = I->second.begin(),
13168 OE = I->second.end();
13169 OI != OE; ++OI) {
13170 assert(OI->second.size() > 0 && "no final overrider");
13171 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013172
Richard Smith4ff9ff92012-07-07 06:59:51 +000013173 // C++ [basic.def.odr]p2:
13174 // [...] A virtual member function is used if it is not pure. [...]
13175 if (!Overrider->isPure())
13176 MarkFunctionReferenced(Loc, Overrider);
13177 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013178 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013179
13180 // Only classes that have virtual bases need a VTT.
13181 if (RD->getNumVBases() == 0)
13182 return;
13183
Aaron Ballman574705e2014-03-13 15:41:46 +000013184 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013185 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013186 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013187 if (Base->getNumVBases() == 0)
13188 continue;
13189 MarkVirtualMembersReferenced(Loc, Base);
13190 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013191}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013192
13193/// SetIvarInitializers - This routine builds initialization ASTs for the
13194/// Objective-C implementation whose ivars need be initialized.
13195void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013196 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013197 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013198 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013199 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013200 CollectIvarsToConstructOrDestruct(OID, ivars);
13201 if (ivars.empty())
13202 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013203 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013204 for (unsigned i = 0; i < ivars.size(); i++) {
13205 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013206 if (Field->isInvalidDecl())
13207 continue;
13208
Alexis Hunt1d792652011-01-08 20:30:50 +000013209 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013210 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13211 InitializationKind InitKind =
13212 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013213
13214 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13215 ExprResult MemberInit =
13216 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013217 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013218 // Note, MemberInit could actually come back empty if no initialization
13219 // is required (e.g., because it would call a trivial default constructor)
13220 if (!MemberInit.get() || MemberInit.isInvalid())
13221 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013222
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013223 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013224 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13225 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013226 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013227 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013228 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013229
13230 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013231 if (const RecordType *RecordTy =
13232 Context.getBaseElementType(Field->getType())
13233 ->getAs<RecordType>()) {
13234 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013235 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013236 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013237 CheckDestructorAccess(Field->getLocation(), Destructor,
13238 PDiag(diag::err_access_dtor_ivar)
13239 << Context.getBaseElementType(Field->getType()));
13240 }
13241 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013242 }
13243 ObjCImplementation->setIvarInitializers(Context,
13244 AllToInit.data(), AllToInit.size());
13245 }
13246}
Alexis Hunt6118d662011-05-04 05:57:24 +000013247
Alexis Hunt27a761d2011-05-04 23:29:54 +000013248static
13249void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13250 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13251 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13252 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13253 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013254 if (Ctor->isInvalidDecl())
13255 return;
13256
Richard Smith802c4b72012-08-23 06:16:52 +000013257 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13258
13259 // Target may not be determinable yet, for instance if this is a dependent
13260 // call in an uninstantiated template.
13261 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013262 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013263 (void)Target->hasBody(FNTarget);
13264 Target = const_cast<CXXConstructorDecl*>(
13265 cast_or_null<CXXConstructorDecl>(FNTarget));
13266 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013267
13268 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13269 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013270 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013271
David Blaikie82e95a32014-11-19 07:49:47 +000013272 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013273 return;
13274
13275 // We know that beyond here, we aren't chaining into a cycle.
13276 if (!Target || !Target->isDelegatingConstructor() ||
13277 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013278 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013279 Current.clear();
13280 // We've hit a cycle.
13281 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13282 Current.count(TCanonical)) {
13283 // If we haven't diagnosed this cycle yet, do so now.
13284 if (!Invalid.count(TCanonical)) {
13285 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013286 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013287 << Ctor;
13288
Richard Smith802c4b72012-08-23 06:16:52 +000013289 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013290 if (TCanonical != Canonical)
13291 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13292
13293 CXXConstructorDecl *C = Target;
13294 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013295 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013296 (void)C->getTargetConstructor()->hasBody(FNTarget);
13297 assert(FNTarget && "Ctor cycle through bodiless function");
13298
Richard Smith802c4b72012-08-23 06:16:52 +000013299 C = const_cast<CXXConstructorDecl*>(
13300 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013301 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13302 }
13303 }
13304
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013305 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013306 Current.clear();
13307 } else {
13308 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13309 }
13310}
13311
13312
Alexis Hunt6118d662011-05-04 05:57:24 +000013313void Sema::CheckDelegatingCtorCycles() {
13314 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13315
Douglas Gregorbae31202011-07-27 21:57:17 +000013316 for (DelegatingCtorDeclsType::iterator
13317 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013318 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013319 I != E; ++I)
13320 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013321
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013322 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13323 CE = Invalid.end();
13324 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013325 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013326}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013327
Douglas Gregor3024f072012-04-16 07:05:22 +000013328namespace {
13329 /// \brief AST visitor that finds references to the 'this' expression.
13330 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13331 Sema &S;
13332
13333 public:
13334 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13335
13336 bool VisitCXXThisExpr(CXXThisExpr *E) {
13337 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13338 << E->isImplicit();
13339 return false;
13340 }
13341 };
13342}
13343
13344bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13345 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13346 if (!TSInfo)
13347 return false;
13348
13349 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013350 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013351 if (!ProtoTL)
13352 return false;
13353
13354 // C++11 [expr.prim.general]p3:
13355 // [The expression this] shall not appear before the optional
13356 // cv-qualifier-seq and it shall not appear within the declaration of a
13357 // static member function (although its type and value category are defined
13358 // within a static member function as they are within a non-static member
13359 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013360 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013361 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013362 FindCXXThisExpr Finder(*this);
13363
13364 // If the return type came after the cv-qualifier-seq, check it now.
13365 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013366 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013367 return true;
13368
13369 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013370 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13371 return true;
13372
13373 return checkThisInStaticMemberFunctionAttributes(Method);
13374}
13375
13376bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13377 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13378 if (!TSInfo)
13379 return false;
13380
13381 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013382 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013383 if (!ProtoTL)
13384 return false;
13385
David Blaikie6adc78e2013-02-18 22:06:02 +000013386 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013387 FindCXXThisExpr Finder(*this);
13388
Douglas Gregor3024f072012-04-16 07:05:22 +000013389 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013390 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013391 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013392 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013393 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013394 case EST_DynamicNone:
13395 case EST_MSAny:
13396 case EST_None:
13397 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013398
Douglas Gregor3024f072012-04-16 07:05:22 +000013399 case EST_ComputedNoexcept:
13400 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13401 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013402
Douglas Gregor3024f072012-04-16 07:05:22 +000013403 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013404 for (const auto &E : Proto->exceptions()) {
13405 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013406 return true;
13407 }
13408 break;
13409 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013410
13411 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013412}
13413
13414bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13415 FindCXXThisExpr Finder(*this);
13416
13417 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013418 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013419 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013420 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013421 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013422 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013423 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013424 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013425 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013426 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013427 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013428 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013429 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013430 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013431 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013432 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013433 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013434 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013435 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013436 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013437 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013438 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013439 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013440 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013441 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013442 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013443 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013444 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013445 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013446 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013447 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013448
13449 if (Arg && !Finder.TraverseStmt(Arg))
13450 return true;
13451
13452 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13453 if (!Finder.TraverseStmt(Args[I]))
13454 return true;
13455 }
13456 }
13457
13458 return false;
13459}
13460
Richard Smith2e321552014-11-12 02:00:47 +000013461void Sema::checkExceptionSpecification(
13462 bool IsTopLevel, ExceptionSpecificationType EST,
13463 ArrayRef<ParsedType> DynamicExceptions,
13464 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13465 SmallVectorImpl<QualType> &Exceptions,
13466 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013467 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013468 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013469 if (EST == EST_Dynamic) {
13470 Exceptions.reserve(DynamicExceptions.size());
13471 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13472 // FIXME: Preserve type source info.
13473 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13474
Richard Smith2e321552014-11-12 02:00:47 +000013475 if (IsTopLevel) {
13476 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13477 collectUnexpandedParameterPacks(ET, Unexpanded);
13478 if (!Unexpanded.empty()) {
13479 DiagnoseUnexpandedParameterPacks(
13480 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13481 Unexpanded);
13482 continue;
13483 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013484 }
13485
13486 // Check that the type is valid for an exception spec, and
13487 // drop it if not.
13488 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13489 Exceptions.push_back(ET);
13490 }
Richard Smith8acb4282014-07-31 21:57:55 +000013491 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013492 return;
13493 }
Richard Smith8acb4282014-07-31 21:57:55 +000013494
Douglas Gregor433e0532012-04-16 18:27:27 +000013495 if (EST == EST_ComputedNoexcept) {
13496 // If an error occurred, there's no expression here.
13497 if (NoexceptExpr) {
13498 assert((NoexceptExpr->isTypeDependent() ||
13499 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13500 Context.BoolTy) &&
13501 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013502 if (IsTopLevel && NoexceptExpr &&
13503 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013504 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013505 return;
13506 }
Richard Smith8acb4282014-07-31 21:57:55 +000013507
Douglas Gregor433e0532012-04-16 18:27:27 +000013508 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013509 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013510 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013511 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013512 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013513 }
13514 return;
13515 }
13516}
13517
Richard Smith0b3a4622014-11-13 20:01:57 +000013518void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13519 ExceptionSpecificationType EST,
13520 SourceRange SpecificationRange,
13521 ArrayRef<ParsedType> DynamicExceptions,
13522 ArrayRef<SourceRange> DynamicExceptionRanges,
13523 Expr *NoexceptExpr) {
13524 if (!MethodD)
13525 return;
13526
13527 // Dig out the method we're referring to.
13528 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13529 MethodD = FunTmpl->getTemplatedDecl();
13530
13531 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13532 if (!Method)
13533 return;
13534
13535 // Check the exception specification.
13536 llvm::SmallVector<QualType, 4> Exceptions;
13537 FunctionProtoType::ExceptionSpecInfo ESI;
13538 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13539 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13540 ESI);
13541
13542 // Update the exception specification on the function type.
13543 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13544
13545 if (Method->isStatic())
13546 checkThisInStaticMemberFunctionExceptionSpec(Method);
13547
13548 if (Method->isVirtual()) {
13549 // Check overrides, which we previously had to delay.
13550 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13551 OEnd = Method->end_overridden_methods();
13552 O != OEnd; ++O)
13553 CheckOverridingFunctionExceptionSpec(Method, *O);
13554 }
13555}
13556
John McCall5e77d762013-04-16 07:28:30 +000013557/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13558///
13559MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13560 SourceLocation DeclStart,
13561 Declarator &D, Expr *BitWidth,
13562 InClassInitStyle InitStyle,
13563 AccessSpecifier AS,
13564 AttributeList *MSPropertyAttr) {
13565 IdentifierInfo *II = D.getIdentifier();
13566 if (!II) {
13567 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013568 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013569 }
13570 SourceLocation Loc = D.getIdentifierLoc();
13571
13572 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13573 QualType T = TInfo->getType();
13574 if (getLangOpts().CPlusPlus) {
13575 CheckExtraCXXDefaultArguments(D);
13576
13577 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13578 UPPC_DataMemberType)) {
13579 D.setInvalidType();
13580 T = Context.IntTy;
13581 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13582 }
13583 }
13584
13585 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13586
13587 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13588 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13589 diag::err_invalid_thread)
13590 << DeclSpec::getSpecifierName(TSCS);
13591
13592 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013593 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013594 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13595 LookupName(Previous, S);
13596 switch (Previous.getResultKind()) {
13597 case LookupResult::Found:
13598 case LookupResult::FoundUnresolvedValue:
13599 PrevDecl = Previous.getAsSingle<NamedDecl>();
13600 break;
13601
13602 case LookupResult::FoundOverloaded:
13603 PrevDecl = Previous.getRepresentativeDecl();
13604 break;
13605
13606 case LookupResult::NotFound:
13607 case LookupResult::NotFoundInCurrentInstantiation:
13608 case LookupResult::Ambiguous:
13609 break;
13610 }
13611
13612 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13613 // Maybe we will complain about the shadowed template parameter.
13614 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13615 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013616 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013617 }
13618
13619 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013620 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013621
13622 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013623 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013624 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13625 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013626 ProcessDeclAttributes(TUScope, NewPD, D);
13627 NewPD->setAccess(AS);
13628
13629 if (NewPD->isInvalidDecl())
13630 Record->setInvalidDecl();
13631
13632 if (D.getDeclSpec().isModulePrivateSpecified())
13633 NewPD->setModulePrivate();
13634
13635 if (NewPD->isInvalidDecl() && PrevDecl) {
13636 // Don't introduce NewFD into scope; there's already something
13637 // with the same name in the same scope.
13638 } else if (II) {
13639 PushOnScopeChains(NewPD, S);
13640 } else
13641 Record->addDecl(NewPD);
13642
13643 return NewPD;
13644}