blob: 844011880e4f5e916b6be8ee8163fe8056ef4b59 [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"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000041#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000042#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner58258242008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattnerb0d38442008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 public:
Mike Stump11289f42009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 };
Chris Lattner58258242008-04-10 02:22:51 +000071
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000078 }
79
Chris Lattnerb0d38442008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106
Douglas Gregor8e12c382008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109
Douglas Gregor97a9c812008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000118 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000119
John McCall7353c862013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0d49512012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner58258242008-04-10 02:22:51 +0000147}
148
Richard Smithb7151b92013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith938f40b2011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
Anders Carlssonf1c26952009-08-25 01:02:06 +0000320 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 Param->setInvalidDecl();
324 return;
325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
John McCallb268a282010-08-23 23:25:46 +0000327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000328}
329
Douglas Gregor58354032008-12-24 00:01:03 +0000330/// ActOnParamUnparsedDefaultArgument - We've seen a default
331/// argument for a function parameter, but we can't parse it yet
332/// because we're inside a class definition. Note that this default
333/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000335 SourceLocation EqualLoc,
336 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000337 if (!param)
338 return;
Mike Stump11289f42009-09-09 15:08:12 +0000339
John McCall48871652010-08-21 09:40:31 +0000340 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000341 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000342 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000343}
344
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param,
348 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000355 Param->setDefaultArg(new(Context)
356 OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Alp Tokerc5350722014-02-26 22:27:52 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384 ++argIdx) {
385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Toppere4794282012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000465
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000482 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000486
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCalle61b02b2010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smith58c3cc12012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
David Majnemeree4f4022014-03-30 06:44:54 +0000589 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000592 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000593 if (New->isConstexpr() != Old->isConstexpr()) {
594 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
595 << New << New->isConstexpr();
596 Diag(Old->getLocation(), diag::note_previous_declaration);
597 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000598 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
599 // C++11 [dcl.fcn.spec]p4:
600 // If the definition of a function appears in a translation unit before its
601 // first declaration as inline, the program is ill-formed.
602 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
603 Diag(Def->getLocation(), diag::note_previous_definition);
604 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000605 }
606
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000608 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000609 // the only declaration of the function or function template in the
610 // translation unit.
611 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
612 functionDeclHasDefaultArgument(Old)) {
613 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
614 Diag(Old->getLocation(), diag::note_previous_declaration);
615 Invalid = true;
616 }
617
Douglas Gregorf40863c2010-02-12 07:32:17 +0000618 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000619 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000620
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000621 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000622}
623
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000624/// \brief Merge the exception specifications of two variable declarations.
625///
626/// This is called when there's a redeclaration of a VarDecl. The function
627/// checks if the redeclaration might have an exception specification and
628/// validates compatibility and merges the specs if necessary.
629void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
630 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000631 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000632 return;
633
634 assert(Context.hasSameType(New->getType(), Old->getType()) &&
635 "Should only be called if types are otherwise the same.");
636
637 QualType NewType = New->getType();
638 QualType OldType = Old->getType();
639
640 // We're only interested in pointers and references to functions, as well
641 // as pointers to member functions.
642 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
643 NewType = R->getPointeeType();
644 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
645 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
646 NewType = P->getPointeeType();
647 OldType = OldType->getAs<PointerType>()->getPointeeType();
648 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
649 NewType = M->getPointeeType();
650 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
651 }
652
653 if (!NewType->isFunctionProtoType())
654 return;
655
656 // There's lots of special cases for functions. For function pointers, system
657 // libraries are hopefully not as broken so that we don't need these
658 // workarounds.
659 if (CheckEquivalentExceptionSpec(
660 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
661 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
662 New->setInvalidDecl();
663 }
664}
665
Chris Lattner199abbc2008-04-08 05:04:30 +0000666/// CheckCXXDefaultArguments - Verify that the default arguments for a
667/// function declaration are well-formed according to C++
668/// [dcl.fct.default].
669void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
670 unsigned NumParams = FD->getNumParams();
671 unsigned p;
672
673 // Find first parameter with a default argument
674 for (p = 0; p < NumParams; ++p) {
675 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000676 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000677 break;
678 }
679
680 // C++ [dcl.fct.default]p4:
681 // In a given function declaration, all parameters
682 // subsequent to a parameter with a default argument shall
683 // have default arguments supplied in this or previous
684 // declarations. A default argument shall not be redefined
685 // by a later declaration (not even to the same value).
686 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000687 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000689 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000690 if (Param->isInvalidDecl())
691 /* We already complained about this parameter. */;
692 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000693 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000694 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000695 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 else
Mike Stump11289f42009-09-09 15:08:12 +0000697 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner199abbc2008-04-08 05:04:30 +0000700 LastMissingDefaultArg = p;
701 }
702 }
703
704 if (LastMissingDefaultArg > 0) {
705 // Some default arguments were missing. Clear out all of the
706 // default arguments up to (and including) the last missing
707 // default argument, so that we leave the function parameters
708 // in a semantically valid state.
709 for (p = 0; p <= LastMissingDefaultArg; ++p) {
710 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000711 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000712 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000713 }
714 }
715 }
716}
Douglas Gregor556877c2008-04-13 21:30:24 +0000717
Richard Smitheb3c10c2011-10-01 02:31:28 +0000718// CheckConstexprParameterTypes - Check whether a function's parameter types
719// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000720// diagnostic and return false.
721static bool CheckConstexprParameterTypes(Sema &SemaRef,
722 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000723 unsigned ArgIndex = 0;
724 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000725 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
726 e = FT->param_type_end();
727 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000728 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
729 SourceLocation ParamLoc = PD->getLocation();
730 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000731 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000732 diag::err_constexpr_non_literal_param,
733 ArgIndex+1, PD->getSourceRange(),
734 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000736 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000737 return true;
738}
739
740/// \brief Get diagnostic %select index for tag kind for
741/// record diagnostic message.
742/// WARNING: Indexes apply to particular diagnostics only!
743///
744/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000745static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000746 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000747 case TTK_Struct: return 0;
748 case TTK_Interface: return 1;
749 case TTK_Class: return 2;
750 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000751 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000752}
753
754// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
755// the requirements of a constexpr function definition or a constexpr
756// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000758//
Richard Smith3607ffe2012-02-13 03:54:03 +0000759// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
760bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
762 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000763 // C++11 [dcl.constexpr]p4:
764 // The definition of a constexpr constructor shall satisfy the following
765 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000766 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000767 const CXXRecordDecl *RD = MD->getParent();
768 if (RD->getNumVBases()) {
769 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
770 << isa<CXXConstructorDecl>(NewFD)
771 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000772 for (const auto &I : RD->vbases())
773 Diag(I.getLocStart(),
774 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000775 return false;
776 }
Richard Smith7971b692012-01-13 04:54:00 +0000777 }
778
779 if (!isa<CXXConstructorDecl>(NewFD)) {
780 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 // The definition of a constexpr function shall satisfy the following
782 // constraints:
783 // - it shall not be virtual;
784 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
785 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787
Richard Smith3607ffe2012-02-13 03:54:03 +0000788 // If it's not obvious why this function is virtual, find an overridden
789 // function which uses the 'virtual' keyword.
790 const CXXMethodDecl *WrittenVirtual = Method;
791 while (!WrittenVirtual->isVirtualAsWritten())
792 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
793 if (WrittenVirtual != Method)
794 Diag(WrittenVirtual->getLocation(),
795 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796 return false;
797 }
798
799 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000800 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000802 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000803 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000804 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000805 }
806
Richard Smith7971b692012-01-13 04:54:00 +0000807 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000809 return false;
810
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 return true;
812}
813
814/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816///
Richard Smithd9f663b2013-04-22 15:31:51 +0000817/// \return true if the body is OK (maybe only as an extension), false if we
818/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000820 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
821 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
823 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000824 for (const auto *DclIt : DS->decls()) {
825 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 case Decl::StaticAssert:
827 case Decl::Using:
828 case Decl::UsingShadow:
829 case Decl::UsingDirective:
830 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000831 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 // - static_assert-declarations
833 // - using-declarations,
834 // - using-directives,
835 continue;
836
837 case Decl::Typedef:
838 case Decl::TypeAlias: {
839 // - typedef declarations and alias-declarations that do not define
840 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000841 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000842 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
843 // Don't allow variably-modified types in constexpr functions.
844 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
845 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
846 << TL.getSourceRange() << TL.getType()
847 << isa<CXXConstructorDecl>(Dcl);
848 return false;
849 }
850 continue;
851 }
852
853 case Decl::Enum:
854 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000857 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000858 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000859 ? diag::warn_cxx11_compat_constexpr_type_definition
860 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000861 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000862 continue;
863
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 case Decl::EnumConstant:
865 case Decl::IndirectField:
866 case Decl::ParmVar:
867 // These can only appear with other declarations which are banned in
868 // C++11 and permitted in C++1y, so ignore them.
869 continue;
870
871 case Decl::Var: {
872 // C++1y [dcl.constexpr]p3 allows anything except:
873 // a definition of a variable of non-literal type or of static or
874 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000875 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 if (VD->isThisDeclarationADefinition()) {
877 if (VD->isStaticLocal()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_static)
880 << isa<CXXConstructorDecl>(Dcl)
881 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
882 return false;
883 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000884 if (!VD->getType()->isDependentType() &&
885 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000886 VD->getLocation(), VD->getType(),
887 diag::err_constexpr_local_var_non_literal_type,
888 isa<CXXConstructorDecl>(Dcl)))
889 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000890 if (!VD->getType()->isDependentType() &&
891 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000892 SemaRef.Diag(VD->getLocation(),
893 diag::err_constexpr_local_var_no_init)
894 << isa<CXXConstructorDecl>(Dcl);
895 return false;
896 }
897 }
898 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000899 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000900 ? diag::warn_cxx11_compat_constexpr_local_var
901 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000902 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000903 continue;
904 }
905
906 case Decl::NamespaceAlias:
907 case Decl::Function:
908 // These are disallowed in C++11 and permitted in C++1y. Allow them
909 // everywhere as an extension.
910 if (!Cxx1yLoc.isValid())
911 Cxx1yLoc = DS->getLocStart();
912 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000913
914 default:
915 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916 << isa<CXXConstructorDecl>(Dcl);
917 return false;
918 }
919 }
920
921 return true;
922}
923
924/// Check that the given field is initialized within a constexpr constructor.
925///
926/// \param Dcl The constexpr constructor being checked.
927/// \param Field The field being checked. This may be a member of an anonymous
928/// struct or union nested within the class being checked.
929/// \param Inits All declarations, including anonymous struct/union members and
930/// indirect members, for which any initialization was provided.
931/// \param Diagnosed Set to true if an error is produced.
932static void CheckConstexprCtorInitializer(Sema &SemaRef,
933 const FunctionDecl *Dcl,
934 FieldDecl *Field,
935 llvm::SmallSet<Decl*, 16> &Inits,
936 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000937 if (Field->isInvalidDecl())
938 return;
939
Douglas Gregor556e5862011-10-10 17:22:13 +0000940 if (Field->isUnnamedBitfield())
941 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000942
Richard Smithab44d5b2013-12-10 08:25:00 +0000943 // Anonymous unions with no variant members and empty anonymous structs do not
944 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
945 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000946 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000947 (Field->getType()->isUnionType()
948 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
949 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000950 return;
951
Richard Smitheb3c10c2011-10-01 02:31:28 +0000952 if (!Inits.count(Field)) {
953 if (!Diagnosed) {
954 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
955 Diagnosed = true;
956 }
957 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
958 } else if (Field->isAnonymousStructOrUnion()) {
959 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000960 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000961 // If an anonymous union contains an anonymous struct of which any member
962 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000963 if (!RD->isUnion() || Inits.count(I))
964 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000965 }
966}
967
Richard Smithd9f663b2013-04-22 15:31:51 +0000968/// Check the provided statement is allowed in a constexpr function
969/// definition.
970static bool
971CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000972 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000973 SourceLocation &Cxx1yLoc) {
974 // - its function-body shall be [...] a compound-statement that contains only
975 switch (S->getStmtClass()) {
976 case Stmt::NullStmtClass:
977 // - null statements,
978 return true;
979
980 case Stmt::DeclStmtClass:
981 // - static_assert-declarations
982 // - using-declarations,
983 // - using-directives,
984 // - typedef declarations and alias-declarations that do not define
985 // classes or enumerations,
986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
987 return false;
988 return true;
989
990 case Stmt::ReturnStmtClass:
991 // - and exactly one return statement;
992 if (isa<CXXConstructorDecl>(Dcl)) {
993 // C++1y allows return statements in constexpr constructors.
994 if (!Cxx1yLoc.isValid())
995 Cxx1yLoc = S->getLocStart();
996 return true;
997 }
998
999 ReturnStmts.push_back(S->getLocStart());
1000 return true;
1001
1002 case Stmt::CompoundStmtClass: {
1003 // C++1y allows compound-statements.
1004 if (!Cxx1yLoc.isValid())
1005 Cxx1yLoc = S->getLocStart();
1006
1007 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001008 for (auto *BodyIt : CompStmt->body()) {
1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001010 Cxx1yLoc))
1011 return false;
1012 }
1013 return true;
1014 }
1015
1016 case Stmt::AttributedStmtClass:
1017 if (!Cxx1yLoc.isValid())
1018 Cxx1yLoc = S->getLocStart();
1019 return true;
1020
1021 case Stmt::IfStmtClass: {
1022 // C++1y allows if-statements.
1023 if (!Cxx1yLoc.isValid())
1024 Cxx1yLoc = S->getLocStart();
1025
1026 IfStmt *If = cast<IfStmt>(S);
1027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1028 Cxx1yLoc))
1029 return false;
1030 if (If->getElse() &&
1031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1032 Cxx1yLoc))
1033 return false;
1034 return true;
1035 }
1036
1037 case Stmt::WhileStmtClass:
1038 case Stmt::DoStmtClass:
1039 case Stmt::ForStmtClass:
1040 case Stmt::CXXForRangeStmtClass:
1041 case Stmt::ContinueStmtClass:
1042 // C++1y allows all of these. We don't allow them as extensions in C++11,
1043 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001044 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001045 break;
1046 if (!Cxx1yLoc.isValid())
1047 Cxx1yLoc = S->getLocStart();
1048 for (Stmt::child_range Children = S->children(); Children; ++Children)
1049 if (*Children &&
1050 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1051 Cxx1yLoc))
1052 return false;
1053 return true;
1054
1055 case Stmt::SwitchStmtClass:
1056 case Stmt::CaseStmtClass:
1057 case Stmt::DefaultStmtClass:
1058 case Stmt::BreakStmtClass:
1059 // C++1y allows switch-statements, and since they don't need variable
1060 // mutation, we can reasonably allow them in C++11 as an extension.
1061 if (!Cxx1yLoc.isValid())
1062 Cxx1yLoc = S->getLocStart();
1063 for (Stmt::child_range Children = S->children(); Children; ++Children)
1064 if (*Children &&
1065 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1066 Cxx1yLoc))
1067 return false;
1068 return true;
1069
1070 default:
1071 if (!isa<Expr>(S))
1072 break;
1073
1074 // C++1y allows expression-statements.
1075 if (!Cxx1yLoc.isValid())
1076 Cxx1yLoc = S->getLocStart();
1077 return true;
1078 }
1079
1080 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1081 << isa<CXXConstructorDecl>(Dcl);
1082 return false;
1083}
1084
Richard Smitheb3c10c2011-10-01 02:31:28 +00001085/// Check the body for the given constexpr function declaration only contains
1086/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1087///
1088/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001089bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001091 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001092 // The definition of a constexpr function shall satisfy the following
1093 // constraints: [...]
1094 // - its function-body shall be = delete, = default, or a
1095 // compound-statement
1096 //
Richard Smith74388b42012-02-04 00:33:54 +00001097 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001098 // In the definition of a constexpr constructor, [...]
1099 // - its function-body shall not be a function-try-block;
1100 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1101 << isa<CXXConstructorDecl>(Dcl);
1102 return false;
1103 }
1104
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001105 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001106
1107 // - its function-body shall be [...] a compound-statement that contains only
1108 // [... list of cases ...]
1109 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1110 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001111 for (auto *BodyIt : CompBody->body()) {
1112 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001113 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001114 }
1115
Richard Smithd9f663b2013-04-22 15:31:51 +00001116 if (Cxx1yLoc.isValid())
1117 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001118 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001119 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1120 : diag::ext_constexpr_body_invalid_stmt)
1121 << isa<CXXConstructorDecl>(Dcl);
1122
Richard Smitheb3c10c2011-10-01 02:31:28 +00001123 if (const CXXConstructorDecl *Constructor
1124 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1125 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001126 // DR1359:
1127 // - every non-variant non-static data member and base class sub-object
1128 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001129 // DR1460:
1130 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001131 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001133 if (Constructor->getNumCtorInitializers() == 0 &&
1134 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1136 return false;
1137 }
Richard Smithf368fb42011-10-10 16:38:04 +00001138 } else if (!Constructor->isDependentContext() &&
1139 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001140 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1141
1142 // Skip detailed checking if we have enough initializers, and we would
1143 // allow at most one initializer per member.
1144 bool AnyAnonStructUnionMembers = false;
1145 unsigned Fields = 0;
1146 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1147 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001148 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001149 AnyAnonStructUnionMembers = true;
1150 break;
1151 }
1152 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001153 // DR1460:
1154 // - if the class is a union-like class, but is not a union, for each of
1155 // its anonymous union members having variant members, exactly one of
1156 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001157 if (AnyAnonStructUnionMembers ||
1158 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1159 // Check initialization of non-static data members. Base classes are
1160 // always initialized so do not need to be checked. Dependent bases
1161 // might not have initializers in the member initializer list.
1162 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001163 for (const auto *I: Constructor->inits()) {
1164 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001166 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 Inits.insert(ID->chain_begin(), ID->chain_end());
1168 }
1169
1170 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001171 for (auto *I : RD->fields())
1172 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001173 if (Diagnosed)
1174 return false;
1175 }
1176 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 } else {
1178 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001180 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001181 // otherwise if there's no return statement, the function cannot
1182 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001183 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001184 (Dcl->getReturnType()->isVoidType() ||
1185 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001186 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001187 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1188 : diag::err_constexpr_body_no_return);
1189 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001190 }
1191 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001192 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001193 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001194 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1195 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1197 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001198 }
1199 }
1200
Richard Smith74388b42012-02-04 00:33:54 +00001201 // C++11 [dcl.constexpr]p5:
1202 // if no function argument values exist such that the function invocation
1203 // substitution would produce a constant expression, the program is
1204 // ill-formed; no diagnostic required.
1205 // C++11 [dcl.constexpr]p3:
1206 // - every constructor call and implicit conversion used in initializing the
1207 // return value shall be one of those allowed in a constant expression.
1208 // C++11 [dcl.constexpr]p4:
1209 // - every constructor involved in initializing non-static data members and
1210 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001211 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001212 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001213 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001214 << isa<CXXConstructorDecl>(Dcl);
1215 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1216 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001217 // Don't return false here: we allow this for compatibility in
1218 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001219 }
1220
Richard Smitheb3c10c2011-10-01 02:31:28 +00001221 return true;
1222}
1223
Douglas Gregor61956c42008-10-31 09:07:45 +00001224/// isCurrentClassName - Determine whether the identifier II is the
1225/// name of the class type currently being defined. In the case of
1226/// nested classes, this will only return true if II is the name of
1227/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001228bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1229 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001231
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001232 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001233 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001234 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1236 } else
1237 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1238
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001239 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001240 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001241 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001242}
1243
Richard Smithfb8b7b92013-10-15 00:00:26 +00001244/// \brief Determine whether the identifier II is a typo for the name of
1245/// the class type currently being defined. If so, update it to the identifier
1246/// that should have been used.
1247bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1248 assert(getLangOpts().CPlusPlus && "No class names in C!");
1249
1250 if (!getLangOpts().SpellChecking)
1251 return false;
1252
1253 CXXRecordDecl *CurDecl;
1254 if (SS && SS->isSet() && !SS->isInvalid()) {
1255 DeclContext *DC = computeDeclContext(*SS, true);
1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1257 } else
1258 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1259
1260 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1261 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1262 < II->getLength()) {
1263 II = CurDecl->getIdentifier();
1264 return true;
1265 }
1266
1267 return false;
1268}
1269
Douglas Gregordc974572012-11-10 07:24:09 +00001270/// \brief Determine whether the given class is a base class of the given
1271/// class, including looking at dependent bases.
1272static bool findCircularInheritance(const CXXRecordDecl *Class,
1273 const CXXRecordDecl *Current) {
1274 SmallVector<const CXXRecordDecl*, 8> Queue;
1275
1276 Class = Class->getCanonicalDecl();
1277 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001278 for (const auto &I : Current->bases()) {
1279 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001280 if (!Base)
1281 continue;
1282
1283 Base = Base->getDefinition();
1284 if (!Base)
1285 continue;
1286
1287 if (Base->getCanonicalDecl() == Class)
1288 return true;
1289
1290 Queue.push_back(Base);
1291 }
1292
1293 if (Queue.empty())
1294 return false;
1295
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001296 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001297 }
1298
1299 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001300}
1301
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001302/// \brief Perform propagation of DLL attributes from a derived class to a
1303/// templated base class for MS compatibility.
1304static void propagateDLLAttrToBaseClassTemplate(
1305 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1306 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1307 if (getDLLAttr(
1308 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1309 // If the base class template has a DLL attribute, don't try to change it.
1310 return;
1311 }
1312
1313 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1314 // If the base class is not already specialized, we can do the propagation.
1315 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1316 NewAttr->setInherited(true);
1317 BaseTemplateSpec->addAttr(NewAttr);
1318 return;
1319 }
1320
1321 bool DifferentAttribute = false;
1322 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1323 if (!SpecializationAttr->isInherited()) {
1324 // The template has previously been specialized or instantiated with an
1325 // explicit attribute. We should not try to change it.
1326 return;
1327 }
1328 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1329 // The specialization already has the right attribute.
1330 return;
1331 }
1332 DifferentAttribute = true;
1333 }
1334
1335 // The template was previously instantiated or explicitly specialized without
1336 // a dll attribute, or the template was previously instantiated with a
1337 // different inherited attribute. It's too late for us to change the
1338 // attribute, so warn that this is unsupported.
1339 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1340 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1341 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1342 if (BaseTemplateSpec->isExplicitSpecialization()) {
1343 S.Diag(BaseTemplateSpec->getLocation(),
1344 diag::note_template_class_explicit_specialization_was_here)
1345 << BaseTemplateSpec;
1346 } else {
1347 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1348 diag::note_template_class_instantiation_was_here)
1349 << BaseTemplateSpec;
1350 }
1351}
1352
Mike Stump11289f42009-09-09 15:08:12 +00001353/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001354///
1355/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1356/// and returns NULL otherwise.
1357CXXBaseSpecifier *
1358Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1359 SourceRange SpecifierRange,
1360 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001361 TypeSourceInfo *TInfo,
1362 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001363 QualType BaseType = TInfo->getType();
1364
Douglas Gregor463421d2009-03-03 04:44:36 +00001365 // C++ [class.union]p1:
1366 // A union shall not have base classes.
1367 if (Class->isUnion()) {
1368 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1369 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001370 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001371 }
1372
Douglas Gregor752a5952011-01-03 22:36:02 +00001373 if (EllipsisLoc.isValid() &&
1374 !TInfo->getType()->containsUnexpandedParameterPack()) {
1375 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1376 << TInfo->getTypeLoc().getSourceRange();
1377 EllipsisLoc = SourceLocation();
1378 }
Douglas Gregor62004702012-11-10 01:18:17 +00001379
1380 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1381
1382 if (BaseType->isDependentType()) {
1383 // Make sure that we don't have circular inheritance among our dependent
1384 // bases. For non-dependent bases, the check for completeness below handles
1385 // this.
1386 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1387 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1388 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001389 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001390 Diag(BaseLoc, diag::err_circular_inheritance)
1391 << BaseType << Context.getTypeDeclType(Class);
1392
1393 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1394 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1395 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001396
1397 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001398 }
1399 }
1400
Mike Stump11289f42009-09-09 15:08:12 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001404 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001405
1406 // Base specifiers must be record types.
1407 if (!BaseType->isRecordType()) {
1408 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 }
1411
1412 // C++ [class.union]p1:
1413 // A union shall not be used as a base class.
1414 if (BaseType->isUnionType()) {
1415 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001416 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001417 }
1418
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001419 // For the MS ABI, propagate DLL attributes to base class templates.
1420 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1421 if (Attr *ClassAttr = getDLLAttr(Class)) {
1422 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1423 BaseType->getAsCXXRecordDecl())) {
1424 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1425 BaseTemplate, BaseLoc);
1426 }
1427 }
1428 }
1429
Douglas Gregor463421d2009-03-03 04:44:36 +00001430 // C++ [class.derived]p2:
1431 // The class-name in a base-specifier shall not be an incompletely
1432 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001433 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001434 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001435 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001436 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001437 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001438
Eli Friedmanc96d4962009-08-15 21:55:26 +00001439 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001440 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001441 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001442 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001443 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001444 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001445 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001446
David Majnemer9b1754d2013-11-02 12:00:36 +00001447 // A class which contains a flexible array member is not suitable for use as a
1448 // base class:
1449 // - If the layout determines that a base comes before another base,
1450 // the flexible array member would index into the subsequent base.
1451 // - If the layout determines that base comes before the derived class,
1452 // the flexible array member would index into the derived class.
1453 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1454 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1455 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001456 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001457 }
1458
Anders Carlsson65c76d32011-03-25 14:55:14 +00001459 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001460 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001461 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001462 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001463 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001464 << CXXBaseDecl->getDeclName()
1465 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001466 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1467 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001468 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001469 }
1470
John McCall3696dcb2010-08-17 07:23:57 +00001471 if (BaseDecl->isInvalidDecl())
1472 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001473
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001474 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001475 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001476 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001477 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001478}
1479
Douglas Gregor556877c2008-04-13 21:30:24 +00001480/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1481/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001482/// example:
1483/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001484/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001485BaseResult
John McCall48871652010-08-21 09:40:31 +00001486Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001487 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001488 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001489 ParsedType basetype, SourceLocation BaseLoc,
1490 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001491 if (!classdecl)
1492 return true;
1493
Douglas Gregorc40290e2009-03-09 23:48:35 +00001494 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001495 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001496 if (!Class)
1497 return true;
1498
David Majnemer5ef4fe72014-06-13 06:43:46 +00001499 // We haven't yet attached the base specifiers.
1500 Class->setIsParsingBaseSpecifiers();
1501
Richard Smith4c96e992013-02-19 23:47:15 +00001502 // We do not support any C++11 attributes on base-specifiers yet.
1503 // Diagnose any attributes we see.
1504 if (!Attributes.empty()) {
1505 for (AttributeList *Attr = Attributes.getList(); Attr;
1506 Attr = Attr->getNext()) {
1507 if (Attr->isInvalid() ||
1508 Attr->getKind() == AttributeList::IgnoredAttribute)
1509 continue;
1510 Diag(Attr->getLoc(),
1511 Attr->getKind() == AttributeList::UnknownAttribute
1512 ? diag::warn_unknown_attribute_ignored
1513 : diag::err_base_specifier_attribute)
1514 << Attr->getName();
1515 }
1516 }
1517
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001519 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001520
Douglas Gregor752a5952011-01-03 22:36:02 +00001521 if (EllipsisLoc.isInvalid() &&
1522 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001523 UPPC_BaseType))
1524 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001525
Douglas Gregor463421d2009-03-03 04:44:36 +00001526 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001527 Virtual, Access, TInfo,
1528 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001529 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001530 else
1531 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregor463421d2009-03-03 04:44:36 +00001533 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001534}
Douglas Gregor556877c2008-04-13 21:30:24 +00001535
Douglas Gregor463421d2009-03-03 04:44:36 +00001536/// \brief Performs the actual work of attaching the given base class
1537/// specifiers to a C++ class.
1538bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1539 unsigned NumBases) {
1540 if (NumBases == 0)
1541 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001542
1543 // Used to keep track of which base types we have already seen, so
1544 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001545 // that the key is always the unqualified canonical type of the base
1546 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001547 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1548
1549 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001550 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001551 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001552 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001553 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001554 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001555 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001556
1557 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1558 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001559 // C++ [class.mi]p3:
1560 // A class shall not be specified as a direct base class of a
1561 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001562 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001563 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001564 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001565 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001566
1567 // Delete the duplicate base class specifier; we're going to
1568 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001569 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001570
1571 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001572 } else {
1573 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001574 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001575 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001576 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1577 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1578 if (Class->isInterface() &&
1579 (!RD->isInterface() ||
1580 KnownBase->getAccessSpecifier() != AS_public)) {
1581 // The Microsoft extension __interface does not permit bases that
1582 // are not themselves public interfaces.
1583 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1584 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1585 << RD->getSourceRange();
1586 Invalid = true;
1587 }
1588 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001589 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001590 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001591 }
1592 }
1593
1594 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001595 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001596
1597 // Delete the remaining (good) base class specifiers, since their
1598 // data has been copied into the CXXRecordDecl.
1599 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001600 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001601
1602 return Invalid;
1603}
1604
1605/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1606/// class, after checking whether there are any duplicate base
1607/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001608void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001609 unsigned NumBases) {
1610 if (!ClassDecl || !Bases || !NumBases)
1611 return;
1612
1613 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001614 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001615}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001616
Douglas Gregor36d1b142009-10-06 17:59:45 +00001617/// \brief Determine whether the type \p Derived is a C++ class that is
1618/// derived from the type \p Base.
1619bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001620 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001621 return false;
John McCalle78aac42010-03-10 03:28:59 +00001622
Douglas Gregor45bb4832013-03-26 23:36:30 +00001623 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001624 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001625 return false;
1626
Douglas Gregor45bb4832013-03-26 23:36:30 +00001627 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001628 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001629 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001630
1631 // If either the base or the derived type is invalid, don't try to
1632 // check whether one is derived from the other.
1633 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1634 return false;
1635
John McCall67da35c2010-02-04 22:26:26 +00001636 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1637 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638}
1639
1640/// \brief Determine whether the type \p Derived is a C++ class that is
1641/// derived from the type \p Base.
1642bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001643 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644 return false;
1645
Douglas Gregor45bb4832013-03-26 23:36:30 +00001646 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001647 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001648 return false;
1649
Douglas Gregor45bb4832013-03-26 23:36:30 +00001650 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001651 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001652 return false;
1653
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1655}
1656
Anders Carlssona70cff62010-04-24 19:06:50 +00001657void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001658 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001659 assert(BasePathArray.empty() && "Base path array must be empty!");
1660 assert(Paths.isRecordingPaths() && "Must record paths!");
1661
1662 const CXXBasePath &Path = Paths.front();
1663
1664 // We first go backward and check if we have a virtual base.
1665 // FIXME: It would be better if CXXBasePath had the base specifier for
1666 // the nearest virtual base.
1667 unsigned Start = 0;
1668 for (unsigned I = Path.size(); I != 0; --I) {
1669 if (Path[I - 1].Base->isVirtual()) {
1670 Start = I - 1;
1671 break;
1672 }
1673 }
1674
1675 // Now add all bases.
1676 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001677 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001678}
1679
Douglas Gregor88d292c2010-05-13 16:44:06 +00001680/// \brief Determine whether the given base path includes a virtual
1681/// base class.
John McCallcf142162010-08-07 06:22:56 +00001682bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1683 for (CXXCastPath::const_iterator B = BasePath.begin(),
1684 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001685 B != BEnd; ++B)
1686 if ((*B)->isVirtual())
1687 return true;
1688
1689 return false;
1690}
1691
Douglas Gregor36d1b142009-10-06 17:59:45 +00001692/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1693/// conversion (where Derived and Base are class types) is
1694/// well-formed, meaning that the conversion is unambiguous (and
1695/// that all of the base classes are accessible). Returns true
1696/// and emits a diagnostic if the code is ill-formed, returns false
1697/// otherwise. Loc is the location where this routine should point to
1698/// if there is an error, and Range is the source range to highlight
1699/// if there is an error.
1700bool
1701Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001702 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 unsigned AmbigiousBaseConvID,
1704 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001705 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001706 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707 // First, determine whether the path from Derived to Base is
1708 // ambiguous. This is slightly more expensive than checking whether
1709 // the Derived to Base conversion exists, because here we need to
1710 // explore multiple paths to determine if there is an ambiguity.
1711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1712 /*DetectVirtual=*/false);
1713 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1714 assert(DerivationOkay &&
1715 "Can only be used with a derived-to-base conversion");
1716 (void)DerivationOkay;
1717
1718 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001719 if (InaccessibleBaseID) {
1720 // Check that the base class can be accessed.
1721 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1722 InaccessibleBaseID)) {
1723 case AR_inaccessible:
1724 return true;
1725 case AR_accessible:
1726 case AR_dependent:
1727 case AR_delayed:
1728 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001729 }
John McCall5b0829a2010-02-10 09:31:12 +00001730 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001731
1732 // Build a base path if necessary.
1733 if (BasePath)
1734 BuildBasePathArray(Paths, *BasePath);
1735 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001736 }
1737
David Majnemer626032f2013-06-22 06:43:58 +00001738 if (AmbigiousBaseConvID) {
1739 // We know that the derived-to-base conversion is ambiguous, and
1740 // we're going to produce a diagnostic. Perform the derived-to-base
1741 // search just one more time to compute all of the possible paths so
1742 // that we can print them out. This is more expensive than any of
1743 // the previous derived-to-base checks we've done, but at this point
1744 // performance isn't as much of an issue.
1745 Paths.clear();
1746 Paths.setRecordingPaths(true);
1747 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1748 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1749 (void)StillOkay;
1750
1751 // Build up a textual representation of the ambiguous paths, e.g.,
1752 // D -> B -> A, that will be used to illustrate the ambiguous
1753 // conversions in the diagnostic. We only print one of the paths
1754 // to each base class subobject.
1755 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1756
1757 Diag(Loc, AmbigiousBaseConvID)
1758 << Derived << Base << PathDisplayStr << Range << Name;
1759 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001760 return true;
1761}
1762
1763bool
1764Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001765 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001766 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001767 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001768 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001769 IgnoreAccess ? 0
1770 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001771 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001772 Loc, Range, DeclarationName(),
1773 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001774}
1775
1776
1777/// @brief Builds a string representing ambiguous paths from a
1778/// specific derived class to different subobjects of the same base
1779/// class.
1780///
1781/// This function builds a string that can be used in error messages
1782/// to show the different paths that one can take through the
1783/// inheritance hierarchy to go from the derived class to different
1784/// subobjects of a base class. The result looks something like this:
1785/// @code
1786/// struct D -> struct B -> struct A
1787/// struct D -> struct C -> struct A
1788/// @endcode
1789std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1790 std::string PathDisplayStr;
1791 std::set<unsigned> DisplayedPaths;
1792 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1793 Path != Paths.end(); ++Path) {
1794 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1795 // We haven't displayed a path to this particular base
1796 // class subobject yet.
1797 PathDisplayStr += "\n ";
1798 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1799 for (CXXBasePath::const_iterator Element = Path->begin();
1800 Element != Path->end(); ++Element)
1801 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1802 }
1803 }
1804
1805 return PathDisplayStr;
1806}
1807
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001808//===----------------------------------------------------------------------===//
1809// C++ class member Handling
1810//===----------------------------------------------------------------------===//
1811
Abramo Bagnarad7340582010-06-05 05:09:32 +00001812/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001813bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1814 SourceLocation ASLoc,
1815 SourceLocation ColonLoc,
1816 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001817 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001818 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001819 ASLoc, ColonLoc);
1820 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001821 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001822}
1823
Richard Smith18f07db2012-08-06 03:25:17 +00001824/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001825void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001826 if (D->isInvalidDecl())
1827 return;
1828
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001829 // We only care about "override" and "final" declarations.
1830 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1831 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001832
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001835 // We can't check dependent instance methods.
1836 if (MD && MD->isInstance() &&
1837 (MD->getParent()->hasAnyDependentBases() ||
1838 MD->getType()->isDependentType()))
1839 return;
1840
1841 if (MD && !MD->isVirtual()) {
1842 // If we have a non-virtual method, check if if hides a virtual method.
1843 // (In that case, it's most likely the method has the wrong type.)
1844 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1845 FindHiddenVirtualMethods(MD, OverloadedMethods);
1846
1847 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001848 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1849 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001850 diag::override_keyword_hides_virtual_member_function)
1851 << "override" << (OverloadedMethods.size() > 1);
1852 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001853 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001854 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001855 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1856 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001857 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001858 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1859 MD->setInvalidDecl();
1860 return;
1861 }
1862 // Fall through into the general case diagnostic.
1863 // FIXME: We might want to attempt typo correction here.
1864 }
1865
1866 if (!MD || !MD->isVirtual()) {
1867 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1868 Diag(OA->getLocation(),
1869 diag::override_keyword_only_allowed_on_virtual_member_functions)
1870 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1871 D->dropAttr<OverrideAttr>();
1872 }
1873 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1874 Diag(FA->getLocation(),
1875 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001876 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1877 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001878 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001879 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001880 return;
1881 }
Richard Smith18f07db2012-08-06 03:25:17 +00001882
Richard Smith18f07db2012-08-06 03:25:17 +00001883 // C++11 [class.virtual]p5:
1884 // If a virtual function is marked with the virt-specifier override and
1885 // does not override a member function of a base class, the program is
1886 // ill-formed.
1887 bool HasOverriddenMethods =
1888 MD->begin_overridden_methods() != MD->end_overridden_methods();
1889 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1890 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1891 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001892}
1893
Richard Smith18f07db2012-08-06 03:25:17 +00001894/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001895/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001896/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001897bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1898 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001899 FinalAttr *FA = Old->getAttr<FinalAttr>();
1900 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001901 return false;
1902
1903 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001904 << New->getDeclName()
1905 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001906 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1907 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001908}
1909
Daniel Jasper0baec5492012-06-06 08:32:04 +00001910static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001911 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1912 // FIXME: Destruction of ObjC lifetime types has side-effects.
1913 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1914 return !RD->isCompleteDefinition() ||
1915 !RD->hasTrivialDefaultConstructor() ||
1916 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001917 return false;
1918}
1919
John McCall5e77d762013-04-16 07:28:30 +00001920static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001922 if (it->isDeclspecPropertyAttribute())
1923 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001925}
1926
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001927/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1928/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001929/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001930/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1931/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001932NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001933Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001934 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001935 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001936 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1939 DeclarationName Name = NameInfo.getName();
1940 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001941
1942 // For anonymous bitfields, the location should point to the type.
1943 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001944 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001945
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001946 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001947
John McCallb1cd7da2010-06-04 08:34:12 +00001948 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001949 assert(!DS.isFriendSpecified());
1950
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001951 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001952
John McCalldb632ac2012-09-25 07:32:39 +00001953 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1954 // The Microsoft extension __interface only permits public member functions
1955 // and prohibits constructors, destructors, operators, non-public member
1956 // functions, static methods and data members.
1957 unsigned InvalidDecl;
1958 bool ShowDeclName = true;
1959 if (!isFunc)
1960 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1961 else if (AS != AS_public)
1962 InvalidDecl = 2;
1963 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1964 InvalidDecl = 3;
1965 else switch (Name.getNameKind()) {
1966 case DeclarationName::CXXConstructorName:
1967 InvalidDecl = 4;
1968 ShowDeclName = false;
1969 break;
1970
1971 case DeclarationName::CXXDestructorName:
1972 InvalidDecl = 5;
1973 ShowDeclName = false;
1974 break;
1975
1976 case DeclarationName::CXXOperatorName:
1977 case DeclarationName::CXXConversionFunctionName:
1978 InvalidDecl = 6;
1979 break;
1980
1981 default:
1982 InvalidDecl = 0;
1983 break;
1984 }
1985
1986 if (InvalidDecl) {
1987 if (ShowDeclName)
1988 Diag(Loc, diag::err_invalid_member_in_interface)
1989 << (InvalidDecl-1) << Name;
1990 else
1991 Diag(Loc, diag::err_invalid_member_in_interface)
1992 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001994 }
1995 }
1996
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001997 // C++ 9.2p6: A member shall not be declared to have automatic storage
1998 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001999 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2000 // data members and cannot be applied to names declared const or static,
2001 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002002 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002003 case DeclSpec::SCS_unspecified:
2004 case DeclSpec::SCS_typedef:
2005 case DeclSpec::SCS_static:
2006 break;
2007 case DeclSpec::SCS_mutable:
2008 if (isFunc) {
2009 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Richard Smithb4a9e862013-04-12 22:46:28 +00002011 // FIXME: It would be nicer if the keyword was ignored only for this
2012 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002013 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002014 }
2015 break;
2016 default:
2017 Diag(DS.getStorageClassSpecLoc(),
2018 diag::err_storageclass_invalid_for_member);
2019 D.getMutableDeclSpec().ClearStorageClassSpecs();
2020 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002021 }
2022
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002025 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002026
David Blaikie35506f82013-01-30 01:22:18 +00002027 if (DS.isConstexprSpecified() && isInstField) {
2028 SemaDiagnosticBuilder B =
2029 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2030 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2031 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002032 B << 0 << 0;
2033 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2034 B << FixItHint::CreateRemoval(ConstexprLoc);
2035 else {
2036 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2037 D.getMutableDeclSpec().ClearConstexprSpec();
2038 const char *PrevSpec;
2039 unsigned DiagID;
2040 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2041 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2042 (void)Failed;
2043 assert(!Failed && "Making a constexpr member const shouldn't fail");
2044 }
David Blaikie35506f82013-01-30 01:22:18 +00002045 } else {
2046 B << 1;
2047 const char *PrevSpec;
2048 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002049 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002050 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2051 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002053 "This is the only DeclSpec that should fail to be applied");
2054 B << 1;
2055 } else {
2056 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2057 isInstField = false;
2058 }
2059 }
2060 }
2061
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002062 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002063 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002064 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002065
2066 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002067 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002068 Diag(Loc, diag::err_bad_variable_name)
2069 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002071 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002072
Benjamin Kramer365082d2012-05-19 16:34:46 +00002073 IdentifierInfo *II = Name.getAsIdentifierInfo();
2074
Douglas Gregor7c26c042011-09-21 14:40:46 +00002075 // Member field could not be with "template" keyword.
2076 // So TemplateParameterLists should be empty in this case.
2077 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002078 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002079 if (TemplateParams->size()) {
2080 // There is no such thing as a member field template.
2081 Diag(D.getIdentifierLoc(), diag::err_template_member)
2082 << II
2083 << SourceRange(TemplateParams->getTemplateLoc(),
2084 TemplateParams->getRAngleLoc());
2085 } else {
2086 // There is an extraneous 'template<>' for this member.
2087 Diag(TemplateParams->getTemplateLoc(),
2088 diag::err_template_member_noparams)
2089 << II
2090 << SourceRange(TemplateParams->getTemplateLoc(),
2091 TemplateParams->getRAngleLoc());
2092 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002093 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002094 }
2095
Douglas Gregora007d362010-10-13 22:19:53 +00002096 if (SS.isSet() && !SS.isInvalid()) {
2097 // The user provided a superfluous scope specifier inside a class
2098 // definition:
2099 //
2100 // class X {
2101 // int X::member;
2102 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002103 if (DeclContext *DC = computeDeclContext(SS, false))
2104 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002105 else
2106 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2107 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002108
Douglas Gregora007d362010-10-13 22:19:53 +00002109 SS.clear();
2110 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002111
John McCall5e77d762013-04-16 07:28:30 +00002112 AttributeList *MSPropertyAttr =
2113 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002114 if (MSPropertyAttr) {
2115 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2116 BitWidth, InitStyle, AS, MSPropertyAttr);
2117 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002118 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002119 isInstField = false;
2120 } else {
2121 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2122 BitWidth, InitStyle, AS);
2123 assert(Member && "HandleField never returns null");
2124 }
2125 } else {
2126 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2127
2128 Member = HandleDeclarator(S, D, TemplateParameterLists);
2129 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002131
2132 // Non-instance-fields can't have a bitfield.
2133 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002134 if (Member->isInvalidDecl()) {
2135 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002136 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002137 // C++ 9.6p3: A bit-field shall not be a static member.
2138 // "static member 'A' cannot be a bit-field"
2139 Diag(Loc, diag::err_static_not_bitfield)
2140 << Name << BitWidth->getSourceRange();
2141 } else if (isa<TypedefDecl>(Member)) {
2142 // "typedef member 'x' cannot be a bit-field"
2143 Diag(Loc, diag::err_typedef_not_bitfield)
2144 << Name << BitWidth->getSourceRange();
2145 } else {
2146 // A function typedef ("typedef int f(); f a;").
2147 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2148 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002149 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002150 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Craig Topperc3ec1492014-05-26 06:22:03 +00002153 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002154 Member->setInvalidDecl();
2155 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002156
2157 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002158
Larisse Voufo39a1e502013-08-06 01:03:05 +00002159 // If we have declared a member function template or static data member
2160 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2162 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002163 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2164 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002165 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002166
Richard Smith18f07db2012-08-06 03:25:17 +00002167 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002168 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002169 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002170 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2171 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002172
Douglas Gregorf2f08062011-03-08 17:10:18 +00002173 if (VS.getLastLocation().isValid()) {
2174 // Update the end location of a method that has a virt-specifiers.
2175 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2176 MD->setRangeEnd(VS.getLastLocation());
2177 }
Richard Smith18f07db2012-08-06 03:25:17 +00002178
Anders Carlssonc87f8612011-01-20 06:29:02 +00002179 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002180
Douglas Gregor92751d42008-11-17 22:58:34 +00002181 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002182
Daniel Jasper0baec5492012-06-06 08:32:04 +00002183 if (isInstField) {
2184 FieldDecl *FD = cast<FieldDecl>(Member);
2185 FieldCollector->Add(FD);
2186
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002187 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002188 // Remember all explicit private FieldDecls that have a name, no side
2189 // effects and are not part of a dependent type declaration.
2190 if (!FD->isImplicit() && FD->getDeclName() &&
2191 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002192 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002193 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002194 !InitializationHasSideEffects(*FD))
2195 UnusedPrivateFields.insert(FD);
2196 }
2197 }
2198
John McCall48871652010-08-21 09:40:31 +00002199 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002200}
2201
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002202namespace {
2203 class UninitializedFieldVisitor
2204 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2205 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002206 // List of Decls to generate a warning on. Also remove Decls that become
2207 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002208 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002209 // If non-null, add a note to the warning pointing back to the constructor.
2210 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002211 public:
2212 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002213 UninitializedFieldVisitor(Sema &S,
Craig Topper4dd9b432014-08-17 23:49:53 +00002214 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002215 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002216 : Inherited(S.Context), S(S), Decls(Decls),
2217 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002218
Richard Trieufd687772013-09-16 20:46:50 +00002219 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002220 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2221 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002222
Richard Trieu1bc22c12013-09-13 03:20:53 +00002223 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2224 // or union.
2225 MemberExpr *FieldME = ME;
2226
2227 Expr *Base = ME;
2228 while (isa<MemberExpr>(Base)) {
2229 ME = cast<MemberExpr>(Base);
2230
2231 if (isa<VarDecl>(ME->getMemberDecl()))
2232 return;
2233
2234 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2235 if (!FD->isAnonymousStructOrUnion())
2236 FieldME = ME;
2237
2238 Base = ME->getBase();
2239 }
2240
Richard Trieufd687772013-09-16 20:46:50 +00002241 if (!isa<CXXThisExpr>(Base))
2242 return;
2243
Richard Trieu406e65c2013-09-20 03:03:06 +00002244 ValueDecl* FoundVD = FieldME->getMemberDecl();
2245
Richard Trieuef64e942013-10-25 00:56:00 +00002246 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002247 return;
2248
Richard Trieuef64e942013-10-25 00:56:00 +00002249 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002250
Richard Trieuef64e942013-10-25 00:56:00 +00002251 // Prevent double warnings on use of unbounded references.
2252 if (IsReference != CheckReferenceOnly)
2253 return;
2254
2255 unsigned diag = IsReference
2256 ? diag::warn_reference_field_is_uninit
2257 : diag::warn_field_is_uninit;
2258 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2259 if (Constructor)
2260 S.Diag(Constructor->getLocation(),
2261 diag::note_uninit_in_this_constructor)
2262 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2263
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002264 }
2265
2266 void HandleValue(Expr *E) {
2267 E = E->IgnoreParens();
2268
2269 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002270 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002271 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002272 }
2273
2274 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2275 HandleValue(CO->getTrueExpr());
2276 HandleValue(CO->getFalseExpr());
2277 return;
2278 }
2279
2280 if (BinaryConditionalOperator *BCO =
2281 dyn_cast<BinaryConditionalOperator>(E)) {
2282 HandleValue(BCO->getCommon());
2283 HandleValue(BCO->getFalseExpr());
2284 return;
2285 }
2286
2287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2288 switch (BO->getOpcode()) {
2289 default:
2290 return;
2291 case(BO_PtrMemD):
2292 case(BO_PtrMemI):
2293 HandleValue(BO->getLHS());
2294 return;
2295 case(BO_Comma):
2296 HandleValue(BO->getRHS());
2297 return;
2298 }
2299 }
2300 }
2301
Richard Trieu1bc22c12013-09-13 03:20:53 +00002302 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002303 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002304 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002305
2306 Inherited::VisitMemberExpr(ME);
2307 }
2308
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002309 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2310 if (E->getCastKind() == CK_LValueToRValue)
2311 HandleValue(E->getSubExpr());
2312
2313 Inherited::VisitImplicitCastExpr(E);
2314 }
2315
Richard Trieu1bc22c12013-09-13 03:20:53 +00002316 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002317 if (E->getConstructor()->isCopyConstructor()) {
2318 Expr *ArgExpr = E->getArg(0);
2319 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2320 if (ICE->getCastKind() == CK_NoOp) {
2321 ArgExpr = ICE->getSubExpr();
2322 }
2323 }
2324
2325 if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2326 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2327 }
2328 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002329 Inherited::VisitCXXConstructExpr(E);
2330 }
2331
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002332 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2333 Expr *Callee = E->getCallee();
2334 if (isa<MemberExpr>(Callee))
2335 HandleValue(Callee);
2336
2337 Inherited::VisitCXXMemberCallExpr(E);
2338 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002339
2340 void VisitBinaryOperator(BinaryOperator *E) {
2341 // If a field assignment is detected, remove the field from the
2342 // uninitiailized field set.
2343 if (E->getOpcode() == BO_Assign)
2344 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002346 if (!FD->getType()->isReferenceType())
2347 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002348
2349 Inherited::VisitBinaryOperator(E);
2350 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002351 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002352 static void CheckInitExprContainsUninitializedFields(
Craig Topper4dd9b432014-08-17 23:49:53 +00002353 Sema &S, Expr *E, llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
Richard Trieuef64e942013-10-25 00:56:00 +00002354 const CXXConstructorDecl *Constructor) {
2355 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002356 return;
2357
Richard Trieuef64e942013-10-25 00:56:00 +00002358 if (!E)
2359 return;
2360
2361 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2362 E = Default->getExpr();
2363 if (!E)
2364 return;
2365 // In class initializers will point to the constructor.
2366 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2367 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002368 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieuef64e942013-10-25 00:56:00 +00002369 }
2370 }
2371
2372 // Diagnose value-uses of fields to initialize themselves, e.g.
2373 // foo(foo)
2374 // where foo is not also a parameter to the constructor.
2375 // Also diagnose across field uninitialized use such as
2376 // x(y), y(x)
2377 // TODO: implement -Wuninitialized and fold this into that framework.
2378 static void DiagnoseUninitializedFields(
2379 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2380
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002381 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2382 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002383 return;
2384 }
2385
2386 if (Constructor->isInvalidDecl())
2387 return;
2388
2389 const CXXRecordDecl *RD = Constructor->getParent();
2390
2391 // Holds fields that are uninitialized.
2392 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2393
2394 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002395 for (auto *I : RD->decls()) {
2396 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002397 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002398 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002399 UninitializedFields.insert(IFD->getAnonField());
2400 }
2401 }
2402
Aaron Ballman0ad78302014-03-13 17:34:31 +00002403 for (const auto *FieldInit : Constructor->inits()) {
2404 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002405
2406 CheckInitExprContainsUninitializedFields(
2407 SemaRef, InitExpr, UninitializedFields, Constructor);
2408
Aaron Ballman0ad78302014-03-13 17:34:31 +00002409 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002410 UninitializedFields.erase(Field);
2411 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002412 }
2413} // namespace
2414
Richard Smith74108172014-01-17 03:11:34 +00002415/// \brief Enter a new C++ default initializer scope. After calling this, the
2416/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2417/// parsing or instantiating the initializer failed.
2418void Sema::ActOnStartCXXInClassMemberInitializer() {
2419 // Create a synthetic function scope to represent the call to the constructor
2420 // that notionally surrounds a use of this initializer.
2421 PushFunctionScope();
2422}
2423
2424/// \brief This is invoked after parsing an in-class initializer for a
2425/// non-static C++ class member, and after instantiating an in-class initializer
2426/// in a class template. Such actions are deferred until the class is complete.
2427void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2428 SourceLocation InitLoc,
2429 Expr *InitExpr) {
2430 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002431 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002432
Richard Smith938f40b2011-06-11 17:19:42 +00002433 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002434 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2435 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002436
2437 if (!InitExpr) {
2438 FD->setInvalidDecl();
2439 FD->removeInClassInitializer();
2440 return;
2441 }
2442
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002443 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2444 FD->setInvalidDecl();
2445 FD->removeInClassInitializer();
2446 return;
2447 }
2448
Richard Smith938f40b2011-06-11 17:19:42 +00002449 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002450 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002451 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002452 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002453 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002454 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002455 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2456 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002457 if (Init.isInvalid()) {
2458 FD->setInvalidDecl();
2459 return;
2460 }
Richard Smith938f40b2011-06-11 17:19:42 +00002461 }
2462
Richard Smith945f8d32013-01-14 22:39:08 +00002463 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002464 // The initialization of each base and member constitutes a
2465 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002466 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002467 if (Init.isInvalid()) {
2468 FD->setInvalidDecl();
2469 return;
2470 }
2471
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002472 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002473
2474 FD->setInClassInitializer(InitExpr);
2475}
2476
Douglas Gregor15e77a22009-12-31 09:10:24 +00002477/// \brief Find the direct and/or virtual base specifiers that
2478/// correspond to the given base type, for use in base initialization
2479/// within a constructor.
2480static bool FindBaseInitializer(Sema &SemaRef,
2481 CXXRecordDecl *ClassDecl,
2482 QualType BaseType,
2483 const CXXBaseSpecifier *&DirectBaseSpec,
2484 const CXXBaseSpecifier *&VirtualBaseSpec) {
2485 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002486 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002487 for (const auto &Base : ClassDecl->bases()) {
2488 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002489 // We found a direct base of this type. That's what we're
2490 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002491 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002492 break;
2493 }
2494 }
2495
2496 // Check for a virtual base class.
2497 // FIXME: We might be able to short-circuit this if we know in advance that
2498 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002499 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002500 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2501 // We haven't found a base yet; search the class hierarchy for a
2502 // virtual base class.
2503 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2504 /*DetectVirtual=*/false);
2505 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2506 BaseType, Paths)) {
2507 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2508 Path != Paths.end(); ++Path) {
2509 if (Path->back().Base->isVirtual()) {
2510 VirtualBaseSpec = Path->back().Base;
2511 break;
2512 }
2513 }
2514 }
2515 }
2516
2517 return DirectBaseSpec || VirtualBaseSpec;
2518}
2519
Sebastian Redla74948d2011-09-24 17:48:25 +00002520/// \brief Handle a C++ member initializer using braced-init-list syntax.
2521MemInitResult
2522Sema::ActOnMemInitializer(Decl *ConstructorD,
2523 Scope *S,
2524 CXXScopeSpec &SS,
2525 IdentifierInfo *MemberOrBase,
2526 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002527 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002528 SourceLocation IdLoc,
2529 Expr *InitList,
2530 SourceLocation EllipsisLoc) {
2531 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002532 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002533 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002534}
2535
2536/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002537MemInitResult
John McCall48871652010-08-21 09:40:31 +00002538Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002539 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002540 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002541 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002542 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002543 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002544 SourceLocation IdLoc,
2545 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002546 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002547 SourceLocation RParenLoc,
2548 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002549 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002550 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002551 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002552 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002553}
2554
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002555namespace {
2556
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002557// Callback to only accept typo corrections that can be a valid C++ member
2558// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002559class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002560public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002561 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2562 : ClassDecl(ClassDecl) {}
2563
Craig Toppera798a9d2014-03-02 09:32:10 +00002564 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002565 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2566 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2567 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002568 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002569 }
2570 return false;
2571 }
2572
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002573private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002574 CXXRecordDecl *ClassDecl;
2575};
2576
2577}
2578
Sebastian Redla74948d2011-09-24 17:48:25 +00002579/// \brief Handle a C++ member initializer.
2580MemInitResult
2581Sema::BuildMemInitializer(Decl *ConstructorD,
2582 Scope *S,
2583 CXXScopeSpec &SS,
2584 IdentifierInfo *MemberOrBase,
2585 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002586 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002587 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002588 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002589 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002590 if (!ConstructorD)
2591 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002592
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002593 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002594
2595 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002596 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002597 if (!Constructor) {
2598 // The user wrote a constructor initializer on a function that is
2599 // not a C++ constructor. Ignore the error for now, because we may
2600 // have more member initializers coming; we'll diagnose it just
2601 // once in ActOnMemInitializers.
2602 return true;
2603 }
2604
2605 CXXRecordDecl *ClassDecl = Constructor->getParent();
2606
2607 // C++ [class.base.init]p2:
2608 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002609 // constructor's class and, if not found in that scope, are looked
2610 // up in the scope containing the constructor's definition.
2611 // [Note: if the constructor's class contains a member with the
2612 // same name as a direct or virtual base class of the class, a
2613 // mem-initializer-id naming the member or base class and composed
2614 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002615 // mem-initializer-id for the hidden base class may be specified
2616 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002617 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002618 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002619 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002620 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002621 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002622 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002623 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2624 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002625 if (EllipsisLoc.isValid())
2626 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002627 << MemberOrBase
2628 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002629
Sebastian Redla9351792012-02-11 23:51:47 +00002630 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002631 }
Francois Pichetd583da02010-12-04 09:14:42 +00002632 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002633 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002634 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002635 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002636 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002637
2638 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002639 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002640 } else if (DS.getTypeSpecType() == TST_decltype) {
2641 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002642 } else {
2643 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2644 LookupParsedName(R, S, &SS);
2645
2646 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2647 if (!TyD) {
2648 if (R.isAmbiguous()) return true;
2649
John McCallda6841b2010-04-09 19:01:14 +00002650 // We don't want access-control diagnostics here.
2651 R.suppressDiagnostics();
2652
Douglas Gregora3b624a2010-01-19 06:46:48 +00002653 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2654 bool NotUnknownSpecialization = false;
2655 DeclContext *DC = computeDeclContext(SS, false);
2656 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2657 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2658
2659 if (!NotUnknownSpecialization) {
2660 // When the scope specifier can refer to a member of an unknown
2661 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002662 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2663 SS.getWithLocInContext(Context),
2664 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002665 if (BaseType.isNull())
2666 return true;
2667
Douglas Gregora3b624a2010-01-19 06:46:48 +00002668 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002669 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002670 }
2671 }
2672
Douglas Gregor15e77a22009-12-31 09:10:24 +00002673 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002674 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002675 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002676 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002677 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002678 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002679 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002680 // We have found a non-static data member with a similar
2681 // name to what was typed; complain and initialize that
2682 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002683 diagnoseTypo(Corr,
2684 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2685 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002686 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002687 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002688 const CXXBaseSpecifier *DirectBaseSpec;
2689 const CXXBaseSpecifier *VirtualBaseSpec;
2690 if (FindBaseInitializer(*this, ClassDecl,
2691 Context.getTypeDeclType(Type),
2692 DirectBaseSpec, VirtualBaseSpec)) {
2693 // We have found a direct or virtual base class with a
2694 // similar name to what was typed; complain and initialize
2695 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002696 diagnoseTypo(Corr,
2697 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2698 << MemberOrBase << false,
2699 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002700
Richard Smithf9b15102013-08-17 00:46:16 +00002701 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2702 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002703 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002704 diag::note_base_class_specified_here)
2705 << BaseSpec->getType()
2706 << BaseSpec->getSourceRange();
2707
Douglas Gregor15e77a22009-12-31 09:10:24 +00002708 TyD = Type;
2709 }
2710 }
2711 }
2712
Douglas Gregora3b624a2010-01-19 06:46:48 +00002713 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002714 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002715 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002716 return true;
2717 }
John McCallb5a0d312009-12-21 10:41:20 +00002718 }
2719
Douglas Gregora3b624a2010-01-19 06:46:48 +00002720 if (BaseType.isNull()) {
2721 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002722 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002723 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002724 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2725 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002726 }
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
John McCallbcd03502009-12-07 02:54:59 +00002729 if (!TInfo)
2730 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002731
Sebastian Redla9351792012-02-11 23:51:47 +00002732 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002733}
2734
Chandler Carruth599deef2011-09-03 01:14:15 +00002735/// Checks a member initializer expression for cases where reference (or
2736/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002737static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2738 Expr *Init,
2739 SourceLocation IdLoc) {
2740 QualType MemberTy = Member->getType();
2741
2742 // We only handle pointers and references currently.
2743 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2744 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2745 return;
2746
2747 const bool IsPointer = MemberTy->isPointerType();
2748 if (IsPointer) {
2749 if (const UnaryOperator *Op
2750 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2751 // The only case we're worried about with pointers requires taking the
2752 // address.
2753 if (Op->getOpcode() != UO_AddrOf)
2754 return;
2755
2756 Init = Op->getSubExpr();
2757 } else {
2758 // We only handle address-of expression initializers for pointers.
2759 return;
2760 }
2761 }
2762
Richard Smithe3b28bc2013-06-12 21:51:50 +00002763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002764 // We only warn when referring to a non-reference parameter declaration.
2765 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2766 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002767 return;
2768
2769 S.Diag(Init->getExprLoc(),
2770 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2771 : diag::warn_bind_ref_member_to_parameter)
2772 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002773 } else {
2774 // Other initializers are fine.
2775 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002776 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002777
2778 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2779 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002780}
2781
John McCallfaf5fb42010-08-26 23:41:50 +00002782MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002783Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002784 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002785 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2786 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2787 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002788 "Member must be a FieldDecl or IndirectFieldDecl");
2789
Sebastian Redla9351792012-02-11 23:51:47 +00002790 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002791 return true;
2792
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002793 if (Member->isInvalidDecl())
2794 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002795
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002796 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002798 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002799 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002801 } else {
2802 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002804 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002805
Sebastian Redla9351792012-02-11 23:51:47 +00002806 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002807
Sebastian Redla9351792012-02-11 23:51:47 +00002808 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002809 // Can't check initialization for a member of dependent type or when
2810 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002811 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002812 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002813 bool InitList = false;
2814 if (isa<InitListExpr>(Init)) {
2815 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002816 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002817 }
2818
Chandler Carruthd44c3102010-12-06 09:23:57 +00002819 // Initialize the member.
2820 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002821 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2822 : InitializedEntity::InitializeMember(IndirectMember,
2823 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002824 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002825 InitList ? InitializationKind::CreateDirectList(IdLoc)
2826 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2827 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002828
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002829 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2831 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002832 if (MemberInit.isInvalid())
2833 return true;
2834
Richard Smith736a9472013-06-12 20:42:33 +00002835 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2836
Richard Smith945f8d32013-01-14 22:39:08 +00002837 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002838 // The initialization of each base and member constitutes a
2839 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002840 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002841 if (MemberInit.isInvalid())
2842 return true;
2843
Richard Smithd59b8322012-12-19 01:39:02 +00002844 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002845 }
2846
Chandler Carruthd44c3102010-12-06 09:23:57 +00002847 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002848 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2849 InitRange.getBegin(), Init,
2850 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002851 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002852 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2853 InitRange.getBegin(), Init,
2854 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002855 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002856}
2857
John McCallfaf5fb42010-08-26 23:41:50 +00002858MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002859Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002860 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002861 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002862 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002863 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002864 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002865 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002866
Sebastian Redl0501c632012-02-12 16:37:36 +00002867 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002868 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002869 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2870 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002871 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002872 }
2873
Sebastian Redla9351792012-02-11 23:51:47 +00002874 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002875 // Initialize the object.
2876 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2877 QualType(ClassDecl->getTypeForDecl(), 0));
2878 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002879 InitList ? InitializationKind::CreateDirectList(NameLoc)
2880 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2881 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002882 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002883 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002885 if (DelegationInit.isInvalid())
2886 return true;
2887
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002888 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2889 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002890
Richard Smith945f8d32013-01-14 22:39:08 +00002891 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002892 // The initialization of each base and member constitutes a
2893 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002894 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2895 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002896 if (DelegationInit.isInvalid())
2897 return true;
2898
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002899 // If we are in a dependent context, template instantiation will
2900 // perform this type-checking again. Just save the arguments that we
2901 // received in a ParenListExpr.
2902 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2903 // of the information that we have about the base
2904 // initializer. However, deconstructing the ASTs is a dicey process,
2905 // and this approach is far more likely to get the corner cases right.
2906 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002907 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002908
Sebastian Redla9351792012-02-11 23:51:47 +00002909 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002910 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002911 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002912}
2913
2914MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002915Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002916 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002917 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002918 SourceLocation BaseLoc
2919 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002920
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002921 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2922 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2923 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2924
2925 // C++ [class.base.init]p2:
2926 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002927 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002928 // of that class, the mem-initializer is ill-formed. A
2929 // mem-initializer-list can initialize a base class using any
2930 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002931 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002932
Sebastian Redla9351792012-02-11 23:51:47 +00002933 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002934 if (EllipsisLoc.isValid()) {
2935 // This is a pack expansion.
2936 if (!BaseType->containsUnexpandedParameterPack()) {
2937 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002938 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002939
Douglas Gregor44e7df62011-01-04 00:32:56 +00002940 EllipsisLoc = SourceLocation();
2941 }
2942 } else {
2943 // Check for any unexpanded parameter packs.
2944 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2945 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002946
Sebastian Redla9351792012-02-11 23:51:47 +00002947 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002948 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002949 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002950
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002951 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002952 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2953 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002954 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002955 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2956 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002957 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002958
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002959 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2960 VirtualBaseSpec);
2961
2962 // C++ [base.class.init]p2:
2963 // Unless the mem-initializer-id names a nonstatic data member of the
2964 // constructor's class or a direct or virtual base of that class, the
2965 // mem-initializer is ill-formed.
2966 if (!DirectBaseSpec && !VirtualBaseSpec) {
2967 // If the class has any dependent bases, then it's possible that
2968 // one of those types will resolve to the same type as
2969 // BaseType. Therefore, just treat this as a dependent base
2970 // class initialization. FIXME: Should we try to check the
2971 // initialization anyway? It seems odd.
2972 if (ClassDecl->hasAnyDependentBases())
2973 Dependent = true;
2974 else
2975 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2976 << BaseType << Context.getTypeDeclType(ClassDecl)
2977 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2978 }
2979 }
2980
2981 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002982 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002983
Sebastian Redla74948d2011-09-24 17:48:25 +00002984 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2985 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002986 InitRange.getBegin(), Init,
2987 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002988 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002989
2990 // C++ [base.class.init]p2:
2991 // If a mem-initializer-id is ambiguous because it designates both
2992 // a direct non-virtual base class and an inherited virtual base
2993 // class, the mem-initializer is ill-formed.
2994 if (DirectBaseSpec && VirtualBaseSpec)
2995 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002996 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002997
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002998 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002999 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003000 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003001
3002 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003003 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003004 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003005 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003006 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003007 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003008 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003009
3010 InitializedEntity BaseEntity =
3011 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3012 InitializationKind Kind =
3013 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3014 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3015 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003016 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003017 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003018 if (BaseInit.isInvalid())
3019 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003020
Richard Smith945f8d32013-01-14 22:39:08 +00003021 // C++11 [class.base.init]p7:
3022 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003023 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003024 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003025 if (BaseInit.isInvalid())
3026 return true;
3027
3028 // If we are in a dependent context, template instantiation will
3029 // perform this type-checking again. Just save the arguments that we
3030 // received in a ParenListExpr.
3031 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3032 // of the information that we have about the base
3033 // initializer. However, deconstructing the ASTs is a dicey process,
3034 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003035 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003036 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003037
Alexis Hunt1d792652011-01-08 20:30:50 +00003038 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003039 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003040 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003041 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003042 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003043}
3044
Sebastian Redl22653ba2011-08-30 19:58:05 +00003045// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003046static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3047 if (T.isNull()) T = E->getType();
3048 QualType TargetType = SemaRef.BuildReferenceType(
3049 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003050 SourceLocation ExprLoc = E->getLocStart();
3051 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3052 TargetType, ExprLoc);
3053
3054 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3055 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003056 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003057}
3058
Anders Carlsson1b00e242010-04-23 03:10:23 +00003059/// ImplicitInitializerKind - How an implicit base or member initializer should
3060/// initialize its base or member.
3061enum ImplicitInitializerKind {
3062 IIK_Default,
3063 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003064 IIK_Move,
3065 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003066};
3067
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003068static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003069BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003070 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003071 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003072 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003073 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003074 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003075 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3076 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003077
John McCalldadc5752010-08-24 06:29:42 +00003078 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003079
3080 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003081 case IIK_Inherit: {
3082 const CXXRecordDecl *Inherited =
3083 Constructor->getInheritedConstructor()->getParent();
3084 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3085 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3086 // C++11 [class.inhctor]p8:
3087 // Each expression in the expression-list is of the form
3088 // static_cast<T&&>(p), where p is the name of the corresponding
3089 // constructor parameter and T is the declared type of p.
3090 SmallVector<Expr*, 16> Args;
3091 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3092 ParmVarDecl *PD = Constructor->getParamDecl(I);
3093 ExprResult ArgExpr =
3094 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3095 VK_LValue, SourceLocation());
3096 if (ArgExpr.isInvalid())
3097 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003098 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003099 }
3100
3101 InitializationKind InitKind = InitializationKind::CreateDirect(
3102 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003103 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003104 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3105 break;
3106 }
3107 }
3108 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003109 case IIK_Default: {
3110 InitializationKind InitKind
3111 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003112 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3113 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003114 break;
3115 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003116
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003118 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003120 ParmVarDecl *Param = Constructor->getParamDecl(0);
3121 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003122
Anders Carlsson1b00e242010-04-23 03:10:23 +00003123 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003124 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003125 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003126 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003127 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003128
Eli Friedmanfa0df832012-02-02 03:46:19 +00003129 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3130
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003131 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003132 QualType ArgTy =
3133 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3134 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003135
Sebastian Redl22653ba2011-08-30 19:58:05 +00003136 if (Moving) {
3137 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3138 }
3139
John McCallcf142162010-08-07 06:22:56 +00003140 CXXCastPath BasePath;
3141 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003142 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3143 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003144 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003145 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003146
Anders Carlsson1b00e242010-04-23 03:10:23 +00003147 InitializationKind InitKind
3148 = InitializationKind::CreateDirect(Constructor->getLocation(),
3149 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003150 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3151 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003152 break;
3153 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003154 }
John McCallb268a282010-08-23 23:25:46 +00003155
Douglas Gregora40433a2010-12-07 00:41:46 +00003156 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003157 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003158 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003159
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003160 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003161 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003162 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3163 SourceLocation()),
3164 BaseSpec->isVirtual(),
3165 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003166 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003167 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003168 SourceLocation());
3169
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003170 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003171}
3172
Sebastian Redl22653ba2011-08-30 19:58:05 +00003173static bool RefersToRValueRef(Expr *MemRef) {
3174 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3175 return Referenced->getType()->isRValueReferenceType();
3176}
3177
Anders Carlsson3c1db572010-04-23 02:15:47 +00003178static bool
3179BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003180 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003181 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003182 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003183 if (Field->isInvalidDecl())
3184 return true;
3185
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003186 SourceLocation Loc = Constructor->getLocation();
3187
Sebastian Redl22653ba2011-08-30 19:58:05 +00003188 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3189 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003190 ParmVarDecl *Param = Constructor->getParamDecl(0);
3191 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003192
3193 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003194 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3195 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003196
Anders Carlsson423f5d82010-04-23 16:04:08 +00003197 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003198 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003199 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003201
Eli Friedmanfa0df832012-02-02 03:46:19 +00003202 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3203
Sebastian Redl22653ba2011-08-30 19:58:05 +00003204 if (Moving) {
3205 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3206 }
3207
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 // Build a reference to this field within the parameter.
3209 CXXScopeSpec SS;
3210 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3211 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003212 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3213 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003214 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003215 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003216 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003217 ParamType, Loc,
3218 /*IsArrow=*/false,
3219 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003220 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003221 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003222 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003223 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003224 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003225 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003226
3227 // C++11 [class.copy]p15:
3228 // - if a member m has rvalue reference type T&&, it is direct-initialized
3229 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003230 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003231 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003232 }
3233
Douglas Gregor94f9a482010-05-05 05:51:00 +00003234 // When the field we are copying is an array, create index variables for
3235 // each dimension of the array. We use these index variables to subscript
3236 // the source array, and other clients (e.g., CodeGen) will perform the
3237 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003238 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003239 QualType BaseType = Field->getType();
3240 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003241 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003242 while (const ConstantArrayType *Array
3243 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003244 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003245 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003246 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003247 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003248 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003249 llvm::raw_svector_ostream OS(Str);
3250 OS << "__i" << IndexVariables.size();
3251 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3252 }
3253 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003254 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003255 IterationVarName, SizeType,
3256 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003257 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003258 IndexVariables.push_back(IterationVar);
3259
3260 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003261 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003262 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003263 assert(!IterationVarRef.isInvalid() &&
3264 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003265 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003266 assert(!IterationVarRef.isInvalid() &&
3267 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003268
Douglas Gregor94f9a482010-05-05 05:51:00 +00003269 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3271 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003272 Loc);
3273 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003274 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003275
Douglas Gregor94f9a482010-05-05 05:51:00 +00003276 BaseType = Array->getElementType();
3277 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003278
3279 // The array subscript expression is an lvalue, which is wrong for moving.
3280 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003281 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003282
Douglas Gregor94f9a482010-05-05 05:51:00 +00003283 // Construct the entity that we will be initializing. For an array, this
3284 // will be first element in the array, which may require several levels
3285 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003287 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003288 if (Indirect)
3289 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3290 else
3291 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003292 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3293 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3294 0,
3295 Entities.back()));
3296
3297 // Direct-initialize to use the copy constructor.
3298 InitializationKind InitKind =
3299 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3300
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003301 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003302 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003303
John McCalldadc5752010-08-24 06:29:42 +00003304 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003305 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003306 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003307 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003308 if (MemberInit.isInvalid())
3309 return true;
3310
Douglas Gregor493627b2011-08-10 15:22:55 +00003311 if (Indirect) {
3312 assert(IndexVariables.size() == 0 &&
3313 "Indirect field improperly initialized");
3314 CXXMemberInit
3315 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3316 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003317 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003318 Loc);
3319 } else
3320 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003321 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003322 Loc,
3323 IndexVariables.data(),
3324 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003325 return false;
3326 }
3327
Richard Smithc2bc61b2013-03-18 21:12:30 +00003328 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3329 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003330
Anders Carlsson3c1db572010-04-23 02:15:47 +00003331 QualType FieldBaseElementType =
3332 SemaRef.Context.getBaseElementType(Field->getType());
3333
Anders Carlsson3c1db572010-04-23 02:15:47 +00003334 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003335 InitializedEntity InitEntity
3336 = Indirect? InitializedEntity::InitializeMember(Indirect)
3337 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003338 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003339 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003340
3341 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3342 ExprResult MemberInit =
3343 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003344
Douglas Gregora40433a2010-12-07 00:41:46 +00003345 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003346 if (MemberInit.isInvalid())
3347 return true;
3348
Douglas Gregor493627b2011-08-10 15:22:55 +00003349 if (Indirect)
3350 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3351 Indirect, Loc,
3352 Loc,
3353 MemberInit.get(),
3354 Loc);
3355 else
3356 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3357 Field, Loc, Loc,
3358 MemberInit.get(),
3359 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003360 return false;
3361 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003362
Alexis Hunt8b455182011-05-17 00:19:05 +00003363 if (!Field->getParent()->isUnion()) {
3364 if (FieldBaseElementType->isReferenceType()) {
3365 SemaRef.Diag(Constructor->getLocation(),
3366 diag::err_uninitialized_member_in_ctor)
3367 << (int)Constructor->isImplicit()
3368 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3369 << 0 << Field->getDeclName();
3370 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3371 return true;
3372 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003373
Alexis Hunt8b455182011-05-17 00:19:05 +00003374 if (FieldBaseElementType.isConstQualified()) {
3375 SemaRef.Diag(Constructor->getLocation(),
3376 diag::err_uninitialized_member_in_ctor)
3377 << (int)Constructor->isImplicit()
3378 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3379 << 1 << Field->getDeclName();
3380 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3381 return true;
3382 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003383 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003384
David Blaikiebbafb8a2012-03-11 07:00:24 +00003385 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003386 FieldBaseElementType->isObjCRetainableType() &&
3387 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3388 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003389 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003390 // Default-initialize Objective-C pointers to NULL.
3391 CXXMemberInit
3392 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3393 Loc, Loc,
3394 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3395 Loc);
3396 return false;
3397 }
3398
Anders Carlsson3c1db572010-04-23 02:15:47 +00003399 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003400 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003401 return false;
3402}
John McCallbc83b3f2010-05-20 23:23:51 +00003403
3404namespace {
3405struct BaseAndFieldInfo {
3406 Sema &S;
3407 CXXConstructorDecl *Ctor;
3408 bool AnyErrorsInInits;
3409 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003410 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003412 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003413
3414 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3415 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003416 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3417 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003418 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003419 else if (Generated && Ctor->isMoveConstructor())
3420 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003421 else if (Ctor->getInheritedConstructor())
3422 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003423 else
3424 IIK = IIK_Default;
3425 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003426
3427 bool isImplicitCopyOrMove() const {
3428 switch (IIK) {
3429 case IIK_Copy:
3430 case IIK_Move:
3431 return true;
3432
3433 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003434 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003435 return false;
3436 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003437
3438 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003439 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003440
3441 bool addFieldInitializer(CXXCtorInitializer *Init) {
3442 AllToInit.push_back(Init);
3443
3444 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003445 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003446 S.UnusedPrivateFields.remove(Init->getAnyMember());
3447
3448 return false;
3449 }
John McCallbc83b3f2010-05-20 23:23:51 +00003450
Richard Smithab44d5b2013-12-10 08:25:00 +00003451 bool isInactiveUnionMember(FieldDecl *Field) {
3452 RecordDecl *Record = Field->getParent();
3453 if (!Record->isUnion())
3454 return false;
3455
Richard Smith8d183852013-12-10 20:56:03 +00003456 if (FieldDecl *Active =
3457 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003458 return Active != Field->getCanonicalDecl();
3459
3460 // In an implicit copy or move constructor, ignore any in-class initializer.
3461 if (isImplicitCopyOrMove())
3462 return true;
3463
3464 // If there's no explicit initialization, the field is active only if it
3465 // has an in-class initializer...
3466 if (Field->hasInClassInitializer())
3467 return false;
3468 // ... or it's an anonymous struct or union whose class has an in-class
3469 // initializer.
3470 if (!Field->isAnonymousStructOrUnion())
3471 return true;
3472 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3473 return !FieldRD->hasInClassInitializer();
3474 }
3475
3476 /// \brief Determine whether the given field is, or is within, a union member
3477 /// that is inactive (because there was an initializer given for a different
3478 /// member of the union, or because the union was not initialized at all).
3479 bool isWithinInactiveUnionMember(FieldDecl *Field,
3480 IndirectFieldDecl *Indirect) {
3481 if (!Indirect)
3482 return isInactiveUnionMember(Field);
3483
Aaron Ballman29c94602014-03-07 18:36:15 +00003484 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003485 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003486 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003487 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003488 }
3489 return false;
3490 }
3491};
Richard Smithc94ec842011-09-19 13:34:43 +00003492}
3493
Douglas Gregor10f939c2011-11-02 23:04:16 +00003494/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3495/// array type.
3496static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3497 if (T->isIncompleteArrayType())
3498 return true;
3499
3500 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3501 if (!ArrayT->getSize())
3502 return true;
3503
3504 T = ArrayT->getElementType();
3505 }
3506
3507 return false;
3508}
3509
Richard Smith938f40b2011-06-11 17:19:42 +00003510static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003511 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003513 if (Field->isInvalidDecl())
3514 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003515
Chandler Carruth139e9622010-06-30 02:59:29 +00003516 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003517 if (CXXCtorInitializer *Init =
3518 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003519 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003520
Richard Smithab44d5b2013-12-10 08:25:00 +00003521 // C++11 [class.base.init]p8:
3522 // if the entity is a non-static data member that has a
3523 // brace-or-equal-initializer and either
3524 // -- the constructor's class is a union and no other variant member of that
3525 // union is designated by a mem-initializer-id or
3526 // -- the constructor's class is not a union, and, if the entity is a member
3527 // of an anonymous union, no other member of that union is designated by
3528 // a mem-initializer-id,
3529 // the entity is initialized as specified in [dcl.init].
3530 //
3531 // We also apply the same rules to handle anonymous structs within anonymous
3532 // unions.
3533 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3534 return false;
3535
Douglas Gregor7db3e952011-11-28 20:03:15 +00003536 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003537 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3538 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003539 CXXCtorInitializer *Init;
3540 if (Indirect)
3541 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3542 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003543 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003544 SourceLocation());
3545 else
3546 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3547 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003548 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003549 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003550 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003551 }
3552
Douglas Gregor10f939c2011-11-02 23:04:16 +00003553 // Don't initialize incomplete or zero-length arrays.
3554 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3555 return false;
3556
John McCallbc83b3f2010-05-20 23:23:51 +00003557 // Don't try to build an implicit initializer if there were semantic
3558 // errors in any of the initializers (and therefore we might be
3559 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003560 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003561 return false;
3562
Craig Topperc3ec1492014-05-26 06:22:03 +00003563 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003564 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3565 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003566 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003567
Richard Smith0a8cfc72012-08-07 21:30:42 +00003568 if (!Init)
3569 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003570
Richard Smith0a8cfc72012-08-07 21:30:42 +00003571 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003572}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003573
3574bool
3575Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3576 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003577 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003578 Constructor->setNumCtorInitializers(1);
3579 CXXCtorInitializer **initializer =
3580 new (Context) CXXCtorInitializer*[1];
3581 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3582 Constructor->setCtorInitializers(initializer);
3583
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003584 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003585 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003586 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3587 }
3588
Alexis Hunte2622992011-05-05 00:05:47 +00003589 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003590
Alexis Hunt61bc1732011-05-01 07:04:31 +00003591 return false;
3592}
Douglas Gregor493627b2011-08-10 15:22:55 +00003593
David Blaikie3fc2f912013-01-17 05:26:25 +00003594bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3595 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003596 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003597 // Just store the initializers as written, they will be checked during
3598 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003599 if (!Initializers.empty()) {
3600 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003601 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003602 new (Context) CXXCtorInitializer*[Initializers.size()];
3603 memcpy(baseOrMemberInitializers, Initializers.data(),
3604 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003605 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003606 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003607
3608 // Let template instantiation know whether we had errors.
3609 if (AnyErrors)
3610 Constructor->setInvalidDecl();
3611
Anders Carlssondb0a9652010-04-02 06:26:44 +00003612 return false;
3613 }
3614
John McCallbc83b3f2010-05-20 23:23:51 +00003615 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003616
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003617 // We need to build the initializer AST according to order of construction
3618 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003619 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003620 if (!ClassDecl)
3621 return true;
3622
Eli Friedman9cf6b592009-11-09 19:20:36 +00003623 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003624
David Blaikie3fc2f912013-01-17 05:26:25 +00003625 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003626 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003627
Anders Carlssondb0a9652010-04-02 06:26:44 +00003628 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003629 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003630 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003631 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003632
3633 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003634 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003635 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003636 if (FD && FD->getParent()->isUnion())
3637 Info.ActiveUnionMember.insert(std::make_pair(
3638 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3639 }
3640 } else if (FieldDecl *FD = Member->getMember()) {
3641 if (FD->getParent()->isUnion())
3642 Info.ActiveUnionMember.insert(std::make_pair(
3643 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3644 }
3645 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003646 }
3647
Anders Carlsson43c64af2010-04-21 19:52:01 +00003648 // Keep track of the direct virtual bases.
3649 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003650 for (auto &I : ClassDecl->bases()) {
3651 if (I.isVirtual())
3652 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003653 }
3654
Anders Carlssondb0a9652010-04-02 06:26:44 +00003655 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003656 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003657 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003658 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003659 // [class.base.init]p7, per DR257:
3660 // A mem-initializer where the mem-initializer-id names a virtual base
3661 // class is ignored during execution of a constructor of any class that
3662 // is not the most derived class.
3663 if (ClassDecl->isAbstract()) {
3664 // FIXME: Provide a fixit to remove the base specifier. This requires
3665 // tracking the location of the associated comma for a base specifier.
3666 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003667 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003668 DiagnoseAbstractType(ClassDecl);
3669 }
3670
John McCallbc83b3f2010-05-20 23:23:51 +00003671 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003672 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3673 // [class.base.init]p8, per DR257:
3674 // If a given [...] base class is not named by a mem-initializer-id
3675 // [...] and the entity is not a virtual base class of an abstract
3676 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003677 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003678 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003679 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003680 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003681 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003682 HadError = true;
3683 continue;
3684 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003685
John McCallbc83b3f2010-05-20 23:23:51 +00003686 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003687 }
3688 }
Mike Stump11289f42009-09-09 15:08:12 +00003689
John McCallbc83b3f2010-05-20 23:23:51 +00003690 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003691 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003692 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003693 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003694 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003695
Alexis Hunt1d792652011-01-08 20:30:50 +00003696 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003697 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003698 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003699 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003700 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003701 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003702 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003703 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003704 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003705 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003706 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003707
John McCallbc83b3f2010-05-20 23:23:51 +00003708 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003709 }
3710 }
Mike Stump11289f42009-09-09 15:08:12 +00003711
John McCallbc83b3f2010-05-20 23:23:51 +00003712 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003713 for (auto *Mem : ClassDecl->decls()) {
3714 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003715 // C++ [class.bit]p2:
3716 // A declaration for a bit-field that omits the identifier declares an
3717 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3718 // initialized.
3719 if (F->isUnnamedBitfield())
3720 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003721
Sebastian Redl22653ba2011-08-30 19:58:05 +00003722 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003723 // handle anonymous struct/union fields based on their individual
3724 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003725 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003726 continue;
3727
3728 if (CollectFieldInitializer(*this, Info, F))
3729 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003730 continue;
3731 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003732
3733 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003734 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003735 continue;
3736
Aaron Ballman629afae2014-03-07 19:56:05 +00003737 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003738 if (F->getType()->isIncompleteArrayType()) {
3739 assert(ClassDecl->hasFlexibleArrayMember() &&
3740 "Incomplete array type is not valid");
3741 continue;
3742 }
3743
Douglas Gregor493627b2011-08-10 15:22:55 +00003744 // Initialize each field of an anonymous struct individually.
3745 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3746 HadError = true;
3747
3748 continue;
3749 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003750 }
Mike Stump11289f42009-09-09 15:08:12 +00003751
David Blaikie3fc2f912013-01-17 05:26:25 +00003752 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003753 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003754 Constructor->setNumCtorInitializers(NumInitializers);
3755 CXXCtorInitializer **baseOrMemberInitializers =
3756 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003757 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003758 NumInitializers * sizeof(CXXCtorInitializer*));
3759 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003760
John McCalla6309952010-03-16 21:39:52 +00003761 // Constructors implicitly reference the base and member
3762 // destructors.
3763 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3764 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003765 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003766
3767 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003768}
3769
David Blaikieb61b8152013-01-17 08:49:22 +00003770static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003771 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003772 const RecordDecl *RD = RT->getDecl();
3773 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003774 for (auto *Field : RD->fields())
3775 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003776 return;
3777 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003778 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003779 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003780}
3781
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003782static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3783 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003784}
3785
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003786static const void *GetKeyForMember(ASTContext &Context,
3787 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003788 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003789 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003790
Richard Smithcd45dbc2014-04-19 03:48:30 +00003791 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003792}
3793
David Blaikie3fc2f912013-01-17 05:26:25 +00003794static void DiagnoseBaseOrMemInitializerOrder(
3795 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3796 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003797 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003798 return;
Mike Stump11289f42009-09-09 15:08:12 +00003799
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003800 // Don't check initializers order unless the warning is enabled at the
3801 // location of at least one initializer.
3802 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003803 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003804 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003805 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3806 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003807 ShouldCheckOrder = true;
3808 break;
3809 }
3810 }
3811 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003812 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003813
John McCallbb7b6582010-04-10 07:37:23 +00003814 // Build the list of bases and members in the order that they'll
3815 // actually be initialized. The explicit initializers should be in
3816 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003817 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003818
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003819 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3820
John McCallbb7b6582010-04-10 07:37:23 +00003821 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003822 for (const auto &VBase : ClassDecl->vbases())
3823 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003824
John McCallbb7b6582010-04-10 07:37:23 +00003825 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003826 for (const auto &Base : ClassDecl->bases()) {
3827 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003828 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003829 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
John McCallbb7b6582010-04-10 07:37:23 +00003832 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003833 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003834 if (Field->isUnnamedBitfield())
3835 continue;
3836
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003837 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003838 }
3839
John McCallbb7b6582010-04-10 07:37:23 +00003840 unsigned NumIdealInits = IdealInitKeys.size();
3841 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003842
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003844 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003845 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003846 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003847
3848 // Scan forward to try to find this initializer in the idealized
3849 // initializers list.
3850 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3851 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003852 break;
John McCallbb7b6582010-04-10 07:37:23 +00003853
3854 // If we didn't find this initializer, it must be because we
3855 // scanned past it on a previous iteration. That can only
3856 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003857 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003858 Sema::SemaDiagnosticBuilder D =
3859 SemaRef.Diag(PrevInit->getSourceLocation(),
3860 diag::warn_initializer_out_of_order);
3861
Francois Pichetd583da02010-12-04 09:14:42 +00003862 if (PrevInit->isAnyMemberInitializer())
3863 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003864 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003865 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003866
Francois Pichetd583da02010-12-04 09:14:42 +00003867 if (Init->isAnyMemberInitializer())
3868 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003869 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003870 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003871
3872 // Move back to the initializer's location in the ideal list.
3873 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3874 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003875 break;
John McCallbb7b6582010-04-10 07:37:23 +00003876
3877 assert(IdealIndex != NumIdealInits &&
3878 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003879 }
John McCallbb7b6582010-04-10 07:37:23 +00003880
3881 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003882 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003883}
3884
John McCall23eebd92010-04-10 09:28:51 +00003885namespace {
3886bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003887 CXXCtorInitializer *Init,
3888 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003889 if (!PrevInit) {
3890 PrevInit = Init;
3891 return false;
3892 }
3893
Douglas Gregorea306a12013-03-25 23:28:23 +00003894 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003895 S.Diag(Init->getSourceLocation(),
3896 diag::err_multiple_mem_initialization)
3897 << Field->getDeclName()
3898 << Init->getSourceRange();
3899 else {
John McCall424cec92011-01-19 06:33:43 +00003900 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003901 assert(BaseClass && "neither field nor base");
3902 S.Diag(Init->getSourceLocation(),
3903 diag::err_multiple_base_initialization)
3904 << QualType(BaseClass, 0)
3905 << Init->getSourceRange();
3906 }
3907 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3908 << 0 << PrevInit->getSourceRange();
3909
3910 return true;
3911}
3912
Alexis Hunt1d792652011-01-08 20:30:50 +00003913typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003914typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3915
3916bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003917 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003918 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003919 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003920 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003921 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003922
3923 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003924 if (Parent->isUnion()) {
3925 UnionEntry &En = Unions[Parent];
3926 if (En.first && En.first != Child) {
3927 S.Diag(Init->getSourceLocation(),
3928 diag::err_multiple_mem_union_initialization)
3929 << Field->getDeclName()
3930 << Init->getSourceRange();
3931 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3932 << 0 << En.second->getSourceRange();
3933 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003934 }
3935 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003936 En.first = Child;
3937 En.second = Init;
3938 }
David Blaikie0f65d592011-11-17 06:01:57 +00003939 if (!Parent->isAnonymousStructOrUnion())
3940 return false;
John McCall23eebd92010-04-10 09:28:51 +00003941 }
3942
3943 Child = Parent;
3944 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003945 }
John McCall23eebd92010-04-10 09:28:51 +00003946
3947 return false;
3948}
3949}
3950
Anders Carlssone857b292010-04-02 03:37:03 +00003951/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003952void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003953 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003954 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003955 bool AnyErrors) {
3956 if (!ConstructorDecl)
3957 return;
3958
3959 AdjustDeclIfTemplate(ConstructorDecl);
3960
3961 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003962 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003963
3964 if (!Constructor) {
3965 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3966 return;
3967 }
3968
John McCall23eebd92010-04-10 09:28:51 +00003969 // Mapping for the duplicate initializers check.
3970 // For member initializers, this is keyed with a FieldDecl*.
3971 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003972 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003973
3974 // Mapping for the inconsistent anonymous-union initializers check.
3975 RedundantUnionMap MemberUnions;
3976
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003977 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003978 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003979 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003980
Abramo Bagnara341d7832010-05-26 18:09:23 +00003981 // Set the source order index.
3982 Init->setSourceOrder(i);
3983
Francois Pichetd583da02010-12-04 09:14:42 +00003984 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003985 const void *Key = GetKeyForMember(Context, Init);
3986 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003987 CheckRedundantUnionInit(*this, Init, MemberUnions))
3988 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003989 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003990 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003991 if (CheckRedundantInit(*this, Init, Members[Key]))
3992 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003993 } else {
3994 assert(Init->isDelegatingInitializer());
3995 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003996 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003997 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003998 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003999 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004000 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004001 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004002 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004003 // Return immediately as the initializer is set.
4004 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004005 }
Anders Carlssone857b292010-04-02 03:37:03 +00004006 }
4007
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004008 if (HadError)
4009 return;
4010
David Blaikie3fc2f912013-01-17 05:26:25 +00004011 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004012
David Blaikie3fc2f912013-01-17 05:26:25 +00004013 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004014
Richard Trieuef64e942013-10-25 00:56:00 +00004015 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004016}
4017
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004018void
John McCalla6309952010-03-16 21:39:52 +00004019Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4020 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004021 // Ignore dependent contexts. Also ignore unions, since their members never
4022 // have destructors implicitly called.
4023 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004024 return;
John McCall1064d7e2010-03-16 05:22:47 +00004025
4026 // FIXME: all the access-control diagnostics are positioned on the
4027 // field/base declaration. That's probably good; that said, the
4028 // user might reasonably want to know why the destructor is being
4029 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004030
Anders Carlssondee9a302009-11-17 04:44:12 +00004031 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004032 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004033 if (Field->isInvalidDecl())
4034 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004035
4036 // Don't destroy incomplete or zero-length arrays.
4037 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4038 continue;
4039
Anders Carlssondee9a302009-11-17 04:44:12 +00004040 QualType FieldType = Context.getBaseElementType(Field->getType());
4041
4042 const RecordType* RT = FieldType->getAs<RecordType>();
4043 if (!RT)
4044 continue;
4045
4046 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004047 if (FieldClassDecl->isInvalidDecl())
4048 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004049 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004050 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004051 // The destructor for an implicit anonymous union member is never invoked.
4052 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4053 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004054
Douglas Gregore71edda2010-07-01 22:47:18 +00004055 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004056 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004057 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004058 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004059 << Field->getDeclName()
4060 << FieldType);
4061
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004062 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004063 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004064 }
4065
John McCall1064d7e2010-03-16 05:22:47 +00004066 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4067
Anders Carlssondee9a302009-11-17 04:44:12 +00004068 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004069 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004070 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004071 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004072
4073 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004074 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004075 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004076
John McCall1064d7e2010-03-16 05:22:47 +00004077 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004078 // If our base class is invalid, we probably can't get its dtor anyway.
4079 if (BaseClassDecl->isInvalidDecl())
4080 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004081 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004082 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004083
Douglas Gregore71edda2010-07-01 22:47:18 +00004084 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004085 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004086
4087 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004088 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004089 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004090 << Base.getType()
4091 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004092 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004093
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004094 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004095 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004096 }
4097
4098 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004099 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004100 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004101 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004102
4103 // Ignore direct virtual bases.
4104 if (DirectVirtualBases.count(RT))
4105 continue;
4106
John McCall1064d7e2010-03-16 05:22:47 +00004107 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004108 // If our base class is invalid, we probably can't get its dtor anyway.
4109 if (BaseClassDecl->isInvalidDecl())
4110 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004111 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004112 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004113
Douglas Gregore71edda2010-07-01 22:47:18 +00004114 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004115 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004116 if (CheckDestructorAccess(
4117 ClassDecl->getLocation(), Dtor,
4118 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004119 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004120 Context.getTypeDeclType(ClassDecl)) ==
4121 AR_accessible) {
4122 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004123 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004124 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004125 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004126 }
John McCall1064d7e2010-03-16 05:22:47 +00004127
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004128 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004129 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004130 }
4131}
4132
John McCall48871652010-08-21 09:40:31 +00004133void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004134 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004135 return;
Mike Stump11289f42009-09-09 15:08:12 +00004136
Mike Stump11289f42009-09-09 15:08:12 +00004137 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004138 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004139 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004140 DiagnoseUninitializedFields(*this, Constructor);
4141 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004142}
4143
Mike Stump11289f42009-09-09 15:08:12 +00004144bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004145 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004146 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4147 unsigned DiagID;
4148 AbstractDiagSelID SelID;
4149
4150 public:
4151 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4152 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004153
Craig Toppera798a9d2014-03-02 09:32:10 +00004154 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004155 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004156 if (SelID == -1)
4157 S.Diag(Loc, DiagID) << T;
4158 else
4159 S.Diag(Loc, DiagID) << SelID << T;
4160 }
4161 } Diagnoser(DiagID, SelID);
4162
4163 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004164}
4165
Anders Carlssoneabf7702009-08-27 00:13:57 +00004166bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004167 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004168 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004169 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004170
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004171 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004172 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004173
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004174 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004175 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004176 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004177 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004178
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004179 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004180 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004181 }
Mike Stump11289f42009-09-09 15:08:12 +00004182
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004183 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004184 if (!RT)
4185 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCall67da35c2010-02-04 22:26:26 +00004187 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004188
John McCall02db245d2010-08-18 09:41:07 +00004189 // We can't answer whether something is abstract until it has a
4190 // definition. If it's currently being defined, we'll walk back
4191 // over all the declarations when we have a full definition.
4192 const CXXRecordDecl *Def = RD->getDefinition();
4193 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004194 return false;
4195
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004196 if (!RD->isAbstract())
4197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004198
Douglas Gregorae298422012-05-04 17:09:59 +00004199 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004200 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004201
John McCall02db245d2010-08-18 09:41:07 +00004202 return true;
4203}
4204
4205void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4206 // Check if we've already emitted the list of pure virtual functions
4207 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004208 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004209 return;
Mike Stump11289f42009-09-09 15:08:12 +00004210
Richard Smithbc46e432013-07-22 02:56:56 +00004211 // If the diagnostic is suppressed, don't emit the notes. We're only
4212 // going to emit them once, so try to attach them to a diagnostic we're
4213 // actually going to show.
4214 if (Diags.isLastDiagnosticIgnored())
4215 return;
4216
Douglas Gregor4165bd62010-03-23 23:47:56 +00004217 CXXFinalOverriderMap FinalOverriders;
4218 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004219
Anders Carlssona2f74f32010-06-03 01:00:02 +00004220 // Keep a set of seen pure methods so we won't diagnose the same method
4221 // more than once.
4222 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4223
Douglas Gregor4165bd62010-03-23 23:47:56 +00004224 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4225 MEnd = FinalOverriders.end();
4226 M != MEnd;
4227 ++M) {
4228 for (OverridingMethods::iterator SO = M->second.begin(),
4229 SOEnd = M->second.end();
4230 SO != SOEnd; ++SO) {
4231 // C++ [class.abstract]p4:
4232 // A class is abstract if it contains or inherits at least one
4233 // pure virtual function for which the final overrider is pure
4234 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004235
Douglas Gregor4165bd62010-03-23 23:47:56 +00004236 //
4237 if (SO->second.size() != 1)
4238 continue;
4239
4240 if (!SO->second.front().Method->isPure())
4241 continue;
4242
Anders Carlssona2f74f32010-06-03 01:00:02 +00004243 if (!SeenPureMethods.insert(SO->second.front().Method))
4244 continue;
4245
Douglas Gregor4165bd62010-03-23 23:47:56 +00004246 Diag(SO->second.front().Method->getLocation(),
4247 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004248 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004249 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004250 }
4251
4252 if (!PureVirtualClassDiagSet)
4253 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4254 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004255}
4256
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004257namespace {
John McCall02db245d2010-08-18 09:41:07 +00004258struct AbstractUsageInfo {
4259 Sema &S;
4260 CXXRecordDecl *Record;
4261 CanQualType AbstractType;
4262 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCall02db245d2010-08-18 09:41:07 +00004264 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4265 : S(S), Record(Record),
4266 AbstractType(S.Context.getCanonicalType(
4267 S.Context.getTypeDeclType(Record))),
4268 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004269
John McCall02db245d2010-08-18 09:41:07 +00004270 void DiagnoseAbstractType() {
4271 if (Invalid) return;
4272 S.DiagnoseAbstractType(Record);
4273 Invalid = true;
4274 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004275
John McCall02db245d2010-08-18 09:41:07 +00004276 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4277};
4278
4279struct CheckAbstractUsage {
4280 AbstractUsageInfo &Info;
4281 const NamedDecl *Ctx;
4282
4283 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4284 : Info(Info), Ctx(Ctx) {}
4285
4286 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4287 switch (TL.getTypeLocClass()) {
4288#define ABSTRACT_TYPELOC(CLASS, PARENT)
4289#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004290 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004291#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004292 }
John McCall02db245d2010-08-18 09:41:07 +00004293 }
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall02db245d2010-08-18 09:41:07 +00004295 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004296 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004297 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4298 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004299 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004300
4301 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004302 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004303 }
John McCall02db245d2010-08-18 09:41:07 +00004304 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004305
John McCall02db245d2010-08-18 09:41:07 +00004306 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4307 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4308 }
Mike Stump11289f42009-09-09 15:08:12 +00004309
John McCall02db245d2010-08-18 09:41:07 +00004310 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4311 // Visit the type parameters from a permissive context.
4312 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4313 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4314 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4315 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4316 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4317 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004318 }
John McCall02db245d2010-08-18 09:41:07 +00004319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
John McCall02db245d2010-08-18 09:41:07 +00004321 // Visit pointee types from a permissive context.
4322#define CheckPolymorphic(Type) \
4323 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4324 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4325 }
4326 CheckPolymorphic(PointerTypeLoc)
4327 CheckPolymorphic(ReferenceTypeLoc)
4328 CheckPolymorphic(MemberPointerTypeLoc)
4329 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004330 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004331
John McCall02db245d2010-08-18 09:41:07 +00004332 /// Handle all the types we haven't given a more specific
4333 /// implementation for above.
4334 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4335 // Every other kind of type that we haven't called out already
4336 // that has an inner type is either (1) sugar or (2) contains that
4337 // inner type in some way as a subobject.
4338 if (TypeLoc Next = TL.getNextTypeLoc())
4339 return Visit(Next, Sel);
4340
4341 // If there's no inner type and we're in a permissive context,
4342 // don't diagnose.
4343 if (Sel == Sema::AbstractNone) return;
4344
4345 // Check whether the type matches the abstract type.
4346 QualType T = TL.getType();
4347 if (T->isArrayType()) {
4348 Sel = Sema::AbstractArrayType;
4349 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004350 }
John McCall02db245d2010-08-18 09:41:07 +00004351 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4352 if (CT != Info.AbstractType) return;
4353
4354 // It matched; do some magic.
4355 if (Sel == Sema::AbstractArrayType) {
4356 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4357 << T << TL.getSourceRange();
4358 } else {
4359 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4360 << Sel << T << TL.getSourceRange();
4361 }
4362 Info.DiagnoseAbstractType();
4363 }
4364};
4365
4366void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4367 Sema::AbstractDiagSelID Sel) {
4368 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4369}
4370
4371}
4372
4373/// Check for invalid uses of an abstract type in a method declaration.
4374static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4375 CXXMethodDecl *MD) {
4376 // No need to do the check on definitions, which require that
4377 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004378 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004379 return;
4380
4381 // For safety's sake, just ignore it if we don't have type source
4382 // information. This should never happen for non-implicit methods,
4383 // but...
4384 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4385 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4386}
4387
4388/// Check for invalid uses of an abstract type within a class definition.
4389static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4390 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004391 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004392 if (D->isImplicit()) continue;
4393
4394 // Methods and method templates.
4395 if (isa<CXXMethodDecl>(D)) {
4396 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4397 } else if (isa<FunctionTemplateDecl>(D)) {
4398 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4399 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4400
4401 // Fields and static variables.
4402 } else if (isa<FieldDecl>(D)) {
4403 FieldDecl *FD = cast<FieldDecl>(D);
4404 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4405 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4406 } else if (isa<VarDecl>(D)) {
4407 VarDecl *VD = cast<VarDecl>(D);
4408 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4409 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4410
4411 // Nested classes and class templates.
4412 } else if (isa<CXXRecordDecl>(D)) {
4413 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4414 } else if (isa<ClassTemplateDecl>(D)) {
4415 CheckAbstractClassUsage(Info,
4416 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4417 }
4418 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004419}
4420
Hans Wennborg853ae942014-05-30 16:59:42 +00004421/// \brief Check class-level dllimport/dllexport attribute.
4422static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4423 Attr *ClassAttr = getDLLAttr(Class);
4424 if (!ClassAttr)
4425 return;
4426
4427 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4428
4429 // Force declaration of implicit members so they can inherit the attribute.
4430 S.ForceDeclarationOfImplicitMembers(Class);
4431
4432 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4433 // seem to be true in practice?
4434
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004435 TemplateSpecializationKind TSK =
4436 Class->getTemplateSpecializationKind();
4437
Hans Wennborg853ae942014-05-30 16:59:42 +00004438 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004439 VarDecl *VD = dyn_cast<VarDecl>(Member);
4440 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4441
4442 // Only methods and static fields inherit the attributes.
4443 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004444 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004445
4446 // Don't process deleted methods.
4447 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004448 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004449
Hans Wennborge8ad3832014-06-11 22:44:39 +00004450 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4451 MD->isInlined()) {
4452 // Current MSVC versions don't export the move assignment operators, so
4453 // don't attempt to import them if we have a definition.
4454 continue;
4455 }
4456
Hans Wennborg496524b2014-05-31 02:08:49 +00004457 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4458 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00004459 !MemberAttr->isInherited() && !ClassAttr->isInherited()) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004460 S.Diag(MemberAttr->getLocation(),
4461 diag::err_attribute_dll_member_of_dll_class)
4462 << MemberAttr << ClassAttr;
4463 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4464 Member->setInvalidDecl();
4465 continue;
4466 }
4467 } else {
4468 auto *NewAttr =
4469 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4470 NewAttr->setInherited(true);
4471 Member->addAttr(NewAttr);
4472 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004473
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004474 if (MD && ClassExported) {
4475 if (MD->isUserProvided()) {
4476 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004477
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004478 // .. except for certain kinds of template specializations.
4479 if (TSK == TSK_ExplicitInstantiationDeclaration)
4480 continue;
4481 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4482 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004483
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004484 S.MarkFunctionReferenced(Class->getLocation(), MD);
4485 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4486 MD->isCopyAssignmentOperator() ||
4487 MD->isMoveAssignmentOperator()) {
4488 // Instantiate non-trivial or explicitly defaulted methods, and the
4489 // copy assignment / move assignment operators.
4490 S.MarkFunctionReferenced(Class->getLocation(), MD);
4491 // Resolve its exception specification; CodeGen needs it.
4492 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4493 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4494 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004495 }
4496 }
4497 }
4498}
4499
Douglas Gregorc99f1552009-12-03 18:33:45 +00004500/// \brief Perform semantic checks on a class definition that has been
4501/// completing, introducing implicitly-declared members, checking for
4502/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004503void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004504 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004505 return;
4506
John McCall02db245d2010-08-18 09:41:07 +00004507 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4508 AbstractUsageInfo Info(*this, Record);
4509 CheckAbstractClassUsage(Info, Record);
4510 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004511
4512 // If this is not an aggregate type and has no user-declared constructor,
4513 // complain about any non-static data members of reference or const scalar
4514 // type, since they will never get initializers.
4515 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004516 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4517 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004518 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004519 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004520 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004521 continue;
4522
Douglas Gregor454a5b62010-04-15 00:00:53 +00004523 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004524 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004525 if (!Complained) {
4526 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4527 << Record->getTagKind() << Record;
4528 Complained = true;
4529 }
4530
4531 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4532 << F->getType()->isReferenceType()
4533 << F->getDeclName();
4534 }
4535 }
4536 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004537
Anders Carlssone771e762011-01-25 18:08:22 +00004538 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004539 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004540
4541 if (Record->getIdentifier()) {
4542 // C++ [class.mem]p13:
4543 // If T is the name of a class, then each of the following shall have a
4544 // name different from T:
4545 // - every member of every anonymous union that is a member of class T.
4546 //
4547 // C++ [class.mem]p14:
4548 // In addition, if class T has a user-declared constructor (12.1), every
4549 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004550 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4551 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4552 ++I) {
4553 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004554 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4555 isa<IndirectFieldDecl>(D)) {
4556 Diag(D->getLocation(), diag::err_member_name_of_class)
4557 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004558 break;
4559 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004560 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004561 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004562
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004563 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004564 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004565 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004566 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4567 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004568 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4569 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4570 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004571
David Majnemera5433082013-10-18 00:33:31 +00004572 if (Record->isAbstract()) {
4573 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4574 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4575 << FA->isSpelledAsSealed();
4576 DiagnoseAbstractType(Record);
4577 }
David Blaikie348df502012-09-21 03:21:07 +00004578 }
4579
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004580 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004581 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004582 // See if a method overloads virtual methods in a base
4583 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004584 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004585 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004586
4587 // Check whether the explicitly-defaulted special members are valid.
4588 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004589 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004590
4591 // For an explicitly defaulted or deleted special member, we defer
4592 // determining triviality until the class is complete. That time is now!
4593 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004594 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004595 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004596 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004597
4598 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004599 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004600 }
4601 }
4602 }
4603 }
4604
4605 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4606 // function that is not a constructor declares that member function to be
4607 // const. [...] The class of which that function is a member shall be
4608 // a literal type.
4609 //
4610 // If the class has virtual bases, any constexpr members will already have
4611 // been diagnosed by the checks performed on the member declaration, so
4612 // suppress this (less useful) diagnostic.
4613 //
4614 // We delay this until we know whether an explicitly-defaulted (or deleted)
4615 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004616 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004617 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004618 for (const auto *M : Record->methods()) {
4619 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004620 switch (Record->getTemplateSpecializationKind()) {
4621 case TSK_ImplicitInstantiation:
4622 case TSK_ExplicitInstantiationDeclaration:
4623 case TSK_ExplicitInstantiationDefinition:
4624 // If a template instantiates to a non-literal type, but its members
4625 // instantiate to constexpr functions, the template is technically
4626 // ill-formed, but we allow it for sanity.
4627 continue;
4628
4629 case TSK_Undeclared:
4630 case TSK_ExplicitSpecialization:
4631 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4632 diag::err_constexpr_method_non_literal);
4633 break;
4634 }
4635
4636 // Only produce one error per class.
4637 break;
4638 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004639 }
4640 }
Sebastian Redl08905022011-02-05 19:23:19 +00004641
John McCall95833f32014-02-27 20:30:49 +00004642 // ms_struct is a request to use the same ABI rules as MSVC. Check
4643 // whether this class uses any C++ features that are implemented
4644 // completely differently in MSVC, and if so, emit a diagnostic.
4645 // That diagnostic defaults to an error, but we allow projects to
4646 // map it down to a warning (or ignore it). It's a fairly common
4647 // practice among users of the ms_struct pragma to mass-annotate
4648 // headers, sweeping up a bunch of types that the project doesn't
4649 // really rely on MSVC-compatible layout for. We must therefore
4650 // support "ms_struct except for C++ stuff" as a secondary ABI.
4651 if (Record->isMsStruct(Context) &&
4652 (Record->isPolymorphic() || Record->getNumBases())) {
4653 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004654 }
4655
Richard Smithc2bc61b2013-03-18 21:12:30 +00004656 // Declare inheriting constructors. We do this eagerly here because:
4657 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004658 // constructors from different classes.
4659 // - The lazy declaration of the other implicit constructors is so as to not
4660 // waste space and performance on classes that are not meant to be
4661 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004662 // have inheriting constructors.
4663 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004664
4665 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004666}
4667
Richard Smith41c35d62013-11-27 03:39:20 +00004668/// Look up the special member function that would be called by a special
4669/// member function for a subobject of class type.
4670///
4671/// \param Class The class type of the subobject.
4672/// \param CSM The kind of special member function.
4673/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4674/// \param ConstRHS True if this is a copy operation with a const object
4675/// on its RHS, that is, if the argument to the outer special member
4676/// function is 'const' and this is not a field marked 'mutable'.
4677static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4678 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4679 unsigned FieldQuals, bool ConstRHS) {
4680 unsigned LHSQuals = 0;
4681 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4682 LHSQuals = FieldQuals;
4683
4684 unsigned RHSQuals = FieldQuals;
4685 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4686 RHSQuals = 0;
4687 else if (ConstRHS)
4688 RHSQuals |= Qualifiers::Const;
4689
4690 return S.LookupSpecialMember(Class, CSM,
4691 RHSQuals & Qualifiers::Const,
4692 RHSQuals & Qualifiers::Volatile,
4693 false,
4694 LHSQuals & Qualifiers::Const,
4695 LHSQuals & Qualifiers::Volatile);
4696}
4697
Richard Smithb5800092012-06-10 05:43:50 +00004698/// Is the special member function which would be selected to perform the
4699/// specified operation on the specified class type a constexpr constructor?
4700static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4701 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004702 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004703 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004704 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004705 if (!SMOR || !SMOR->getMethod())
4706 // A constructor we wouldn't select can't be "involved in initializing"
4707 // anything.
4708 return true;
4709 return SMOR->getMethod()->isConstexpr();
4710}
4711
4712/// Determine whether the specified special member function would be constexpr
4713/// if it were implicitly defined.
4714static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4715 Sema::CXXSpecialMember CSM,
4716 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004717 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004718 return false;
4719
4720 // C++11 [dcl.constexpr]p4:
4721 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004722 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004723 switch (CSM) {
4724 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004725 // Since default constructor lookup is essentially trivial (and cannot
4726 // involve, for instance, template instantiation), we compute whether a
4727 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4728 //
4729 // This is important for performance; we need to know whether the default
4730 // constructor is constexpr to determine whether the type is a literal type.
4731 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4732
Richard Smithb5800092012-06-10 05:43:50 +00004733 case Sema::CXXCopyConstructor:
4734 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004735 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004736 break;
4737
4738 case Sema::CXXCopyAssignment:
4739 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004740 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00004741 return false;
4742 // In C++1y, we need to perform overload resolution.
4743 Ctor = false;
4744 break;
4745
Richard Smithb5800092012-06-10 05:43:50 +00004746 case Sema::CXXDestructor:
4747 case Sema::CXXInvalid:
4748 return false;
4749 }
4750
4751 // -- if the class is a non-empty union, or for each non-empty anonymous
4752 // union member of a non-union class, exactly one non-static data member
4753 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004754 //
4755 // If we squint, this is guaranteed, since exactly one non-static data member
4756 // will be initialized (if the constructor isn't deleted), we just don't know
4757 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004758 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004759 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004760
4761 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004762 if (Ctor && ClassDecl->getNumVBases())
4763 return false;
4764
4765 // C++1y [class.copy]p26:
4766 // -- [the class] is a literal type, and
4767 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004768 return false;
4769
4770 // -- every constructor involved in initializing [...] base class
4771 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004772 // -- the assignment operator selected to copy/move each direct base
4773 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004774 for (const auto &B : ClassDecl->bases()) {
4775 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004776 if (!BaseType) continue;
4777
4778 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004779 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004780 return false;
4781 }
4782
4783 // -- every constructor involved in initializing non-static data members
4784 // [...] shall be a constexpr constructor;
4785 // -- every non-static data member and base class sub-object shall be
4786 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004787 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004788 // thereof), the assignment operator selected to copy/move that member is
4789 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004790 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004791 if (F->isInvalidDecl())
4792 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004793 QualType BaseType = S.Context.getBaseElementType(F->getType());
4794 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004795 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004796 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4797 BaseType.getCVRQualifiers(),
4798 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004799 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004800 }
4801 }
4802
4803 // All OK, it's constexpr!
4804 return true;
4805}
4806
Richard Smithd3b5c9082012-07-27 04:22:15 +00004807static Sema::ImplicitExceptionSpecification
4808computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4809 switch (S.getSpecialMember(MD)) {
4810 case Sema::CXXDefaultConstructor:
4811 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4812 case Sema::CXXCopyConstructor:
4813 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4814 case Sema::CXXCopyAssignment:
4815 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4816 case Sema::CXXMoveConstructor:
4817 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4818 case Sema::CXXMoveAssignment:
4819 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4820 case Sema::CXXDestructor:
4821 return S.ComputeDefaultedDtorExceptionSpec(MD);
4822 case Sema::CXXInvalid:
4823 break;
4824 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004825 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4826 "only special members have implicit exception specs");
4827 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004828}
4829
Reid Kleckner78af0702013-08-27 23:08:25 +00004830static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4831 CXXMethodDecl *MD) {
4832 FunctionProtoType::ExtProtoInfo EPI;
4833
4834 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00004835 EPI.ExceptionSpec.Type = EST_Unevaluated;
4836 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00004837
4838 // Set the calling convention to the default for C++ instance methods.
4839 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4840 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4841 /*IsCXXMethod=*/true));
4842 return EPI;
4843}
4844
Richard Smithd3b5c9082012-07-27 04:22:15 +00004845void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4846 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4847 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4848 return;
4849
Richard Smith7f782272012-07-30 23:48:14 +00004850 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00004851 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00004852
Richard Smith7f782272012-07-30 23:48:14 +00004853 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00004854 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00004855
4856 // A user-provided destructor can be defined outside the class. When that
4857 // happens, be sure to update the exception specification on both
4858 // declarations.
4859 const FunctionProtoType *CanonicalFPT =
4860 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4861 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00004862 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004863}
4864
Richard Smithb9e90b12012-05-15 04:39:51 +00004865void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4866 CXXRecordDecl *RD = MD->getParent();
4867 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004868
Richard Smithb9e90b12012-05-15 04:39:51 +00004869 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4870 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004871
4872 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004873 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004874 bool First = MD == MD->getCanonicalDecl();
4875
4876 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004877
4878 // C++11 [dcl.fct.def.default]p1:
4879 // A function that is explicitly defaulted shall
4880 // -- be a special member function (checked elsewhere),
4881 // -- have the same type (except for ref-qualifiers, and except that a
4882 // copy operation can take a non-const reference) as an implicit
4883 // declaration, and
4884 // -- not have default arguments.
4885 unsigned ExpectedParams = 1;
4886 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4887 ExpectedParams = 0;
4888 if (MD->getNumParams() != ExpectedParams) {
4889 // This also checks for default arguments: a copy or move constructor with a
4890 // default argument is classified as a default constructor, and assignment
4891 // operations and destructors can't have default arguments.
4892 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4893 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004894 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004895 } else if (MD->isVariadic()) {
4896 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4897 << CSM << MD->getSourceRange();
4898 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004899 }
4900
Richard Smithb9e90b12012-05-15 04:39:51 +00004901 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004902
Richard Smithb5800092012-06-10 05:43:50 +00004903 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004904 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004905 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004906 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004907 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004908
Richard Smithb9e90b12012-05-15 04:39:51 +00004909 QualType ReturnType = Context.VoidTy;
4910 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4911 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004912 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004913 QualType ExpectedReturnType =
4914 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4915 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4916 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4917 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4918 HadError = true;
4919 }
4920
4921 // A defaulted special member cannot have cv-qualifiers.
4922 if (Type->getTypeQuals()) {
4923 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004924 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00004925 HadError = true;
4926 }
4927 }
4928
4929 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004930 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004931 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004932 if (ExpectedParams && ArgType->isReferenceType()) {
4933 // Argument must be reference to possibly-const T.
4934 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004935 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004936
4937 if (ReferentType.isVolatileQualified()) {
4938 Diag(MD->getLocation(),
4939 diag::err_defaulted_special_member_volatile_param) << CSM;
4940 HadError = true;
4941 }
4942
Richard Smithb5800092012-06-10 05:43:50 +00004943 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004944 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4945 Diag(MD->getLocation(),
4946 diag::err_defaulted_special_member_copy_const_param)
4947 << (CSM == CXXCopyAssignment);
4948 // FIXME: Explain why this special member can't be const.
4949 } else {
4950 Diag(MD->getLocation(),
4951 diag::err_defaulted_special_member_move_const_param)
4952 << (CSM == CXXMoveAssignment);
4953 }
4954 HadError = true;
4955 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004956 } else if (ExpectedParams) {
4957 // A copy assignment operator can take its argument by value, but a
4958 // defaulted one cannot.
4959 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004960 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004961 HadError = true;
4962 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004963
Richard Smithcc36f692011-12-22 02:22:31 +00004964 // C++11 [dcl.fct.def.default]p2:
4965 // An explicitly-defaulted function may be declared constexpr only if it
4966 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004967 // Do not apply this rule to members of class templates, since core issue 1358
4968 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004969 // functions which cannot be constexpr (for non-constructors in C++11 and for
4970 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004971 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4972 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004973 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00004974 : isa<CXXConstructorDecl>(MD)) &&
4975 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004976 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4977 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004978 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004979 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004980 }
Richard Smithbd305122012-12-11 01:14:52 +00004981
Richard Smithcc36f692011-12-22 02:22:31 +00004982 // and may have an explicit exception-specification only if it is compatible
4983 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004984 if (Type->hasExceptionSpec()) {
4985 // Delay the check if this is the first declaration of the special member,
4986 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004987 if (First) {
4988 // If the exception specification needs to be instantiated, do so now,
4989 // before we clobber it with an EST_Unevaluated specification below.
4990 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4991 InstantiateExceptionSpec(MD->getLocStart(), MD);
4992 Type = MD->getType()->getAs<FunctionProtoType>();
4993 }
Richard Smithbd305122012-12-11 01:14:52 +00004994 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004995 } else
Richard Smithbd305122012-12-11 01:14:52 +00004996 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4997 }
Richard Smithcc36f692011-12-22 02:22:31 +00004998
4999 // If a function is explicitly defaulted on its first declaration,
5000 if (First) {
5001 // -- it is implicitly considered to be constexpr if the implicit
5002 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005003 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005004
Richard Smithb9e90b12012-05-15 04:39:51 +00005005 // -- it is implicitly considered to have the same exception-specification
5006 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005007 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005008 EPI.ExceptionSpec.Type = EST_Unevaluated;
5009 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005010 MD->setType(Context.getFunctionType(ReturnType,
5011 ArrayRef<QualType>(&ArgType,
5012 ExpectedParams),
5013 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005014 }
5015
Richard Smithb9e90b12012-05-15 04:39:51 +00005016 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005017 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005018 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005019 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005020 // C++11 [dcl.fct.def.default]p4:
5021 // [For a] user-provided explicitly-defaulted function [...] if such a
5022 // function is implicitly defined as deleted, the program is ill-formed.
5023 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005024 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005025 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005026 }
5027 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005028
Richard Smithb9e90b12012-05-15 04:39:51 +00005029 if (HadError)
5030 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005031}
5032
Richard Smithbd305122012-12-11 01:14:52 +00005033/// Check whether the exception specification provided for an
5034/// explicitly-defaulted special member matches the exception specification
5035/// that would have been generated for an implicit special member, per
5036/// C++11 [dcl.fct.def.default]p2.
5037void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5038 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5039 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005040 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5041 /*IsCXXMethod=*/true);
5042 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005043 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5044 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005045 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005046 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005047
5048 // Ensure that it matches.
5049 CheckEquivalentExceptionSpec(
5050 PDiag(diag::err_incorrect_defaulted_exception_spec)
5051 << getSpecialMember(MD), PDiag(),
5052 ImplicitType, SourceLocation(),
5053 SpecifiedType, MD->getLocation());
5054}
5055
Alp Tokerae3a9442013-10-18 05:54:19 +00005056void Sema::CheckDelayedMemberExceptionSpecs() {
5057 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5058 2> Checks;
5059 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005060
Alp Tokerae3a9442013-10-18 05:54:19 +00005061 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5062 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5063
5064 // Perform any deferred checking of exception specifications for virtual
5065 // destructors.
5066 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5067 const CXXDestructorDecl *Dtor = Checks[i].first;
5068 assert(!Dtor->getParent()->isDependentType() &&
5069 "Should not ever add destructors of templates into the list.");
5070 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5071 }
5072
5073 // Check that any explicitly-defaulted methods have exception specifications
5074 // compatible with their implicit exception specifications.
5075 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5076 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5077 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005078}
5079
Richard Smithd951a1d2012-02-18 02:02:13 +00005080namespace {
5081struct SpecialMemberDeletionInfo {
5082 Sema &S;
5083 CXXMethodDecl *MD;
5084 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005085 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005086
5087 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005088 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005089 SourceLocation Loc;
5090
5091 bool AllFieldsAreConst;
5092
5093 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005094 Sema::CXXSpecialMember CSM, bool Diagnose)
5095 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005096 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005097 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005098 AllFieldsAreConst(true) {
5099 switch (CSM) {
5100 case Sema::CXXDefaultConstructor:
5101 case Sema::CXXCopyConstructor:
5102 IsConstructor = true;
5103 break;
5104 case Sema::CXXMoveConstructor:
5105 IsConstructor = true;
5106 IsMove = true;
5107 break;
5108 case Sema::CXXCopyAssignment:
5109 IsAssignment = true;
5110 break;
5111 case Sema::CXXMoveAssignment:
5112 IsAssignment = true;
5113 IsMove = true;
5114 break;
5115 case Sema::CXXDestructor:
5116 break;
5117 case Sema::CXXInvalid:
5118 llvm_unreachable("invalid special member kind");
5119 }
5120
5121 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005122 if (const ReferenceType *RT =
5123 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5124 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005125 }
5126 }
5127
5128 bool inUnion() const { return MD->getParent()->isUnion(); }
5129
5130 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005131 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005132 unsigned Quals, bool IsMutable) {
5133 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5134 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005135 }
5136
Richard Smith852265f2012-03-30 20:53:28 +00005137 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005138
Richard Smith852265f2012-03-30 20:53:28 +00005139 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005140 bool shouldDeleteForField(FieldDecl *FD);
5141 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005142
Richard Smithaf136f82012-07-18 03:51:16 +00005143 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5144 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005145 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5146 Sema::SpecialMemberOverloadResult *SMOR,
5147 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005148
5149 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005150};
5151}
5152
John McCalld4274212012-04-09 20:53:23 +00005153/// Is the given special member inaccessible when used on the given
5154/// sub-object.
5155bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5156 CXXMethodDecl *target) {
5157 /// If we're operating on a base class, the object type is the
5158 /// type of this special member.
5159 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005160 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005161 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5162 objectTy = S.Context.getTypeDeclType(MD->getParent());
5163 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5164
5165 // If we're operating on a field, the object type is the type of the field.
5166 } else {
5167 objectTy = S.Context.getTypeDeclType(target->getParent());
5168 }
5169
5170 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5171}
5172
Richard Smith852265f2012-03-30 20:53:28 +00005173/// Check whether we should delete a special member due to the implicit
5174/// definition containing a call to a special member of a subobject.
5175bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5176 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5177 bool IsDtorCallInCtor) {
5178 CXXMethodDecl *Decl = SMOR->getMethod();
5179 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5180
5181 int DiagKind = -1;
5182
5183 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5184 DiagKind = !Decl ? 0 : 1;
5185 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5186 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005187 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005188 DiagKind = 3;
5189 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5190 !Decl->isTrivial()) {
5191 // A member of a union must have a trivial corresponding special member.
5192 // As a weird special case, a destructor call from a union's constructor
5193 // must be accessible and non-deleted, but need not be trivial. Such a
5194 // destructor is never actually called, but is semantically checked as
5195 // if it were.
5196 DiagKind = 4;
5197 }
5198
5199 if (DiagKind == -1)
5200 return false;
5201
5202 if (Diagnose) {
5203 if (Field) {
5204 S.Diag(Field->getLocation(),
5205 diag::note_deleted_special_member_class_subobject)
5206 << CSM << MD->getParent() << /*IsField*/true
5207 << Field << DiagKind << IsDtorCallInCtor;
5208 } else {
5209 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5210 S.Diag(Base->getLocStart(),
5211 diag::note_deleted_special_member_class_subobject)
5212 << CSM << MD->getParent() << /*IsField*/false
5213 << Base->getType() << DiagKind << IsDtorCallInCtor;
5214 }
5215
5216 if (DiagKind == 1)
5217 S.NoteDeletedFunction(Decl);
5218 // FIXME: Explain inaccessibility if DiagKind == 3.
5219 }
5220
5221 return true;
5222}
5223
Richard Smith921bd202012-02-26 09:11:52 +00005224/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005225/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005226bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005227 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005228 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005229 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005230
5231 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005232 // -- any direct or virtual base class, or non-static data member with no
5233 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005234 // either M has no default constructor or overload resolution as applied
5235 // to M's default constructor results in an ambiguity or in a function
5236 // that is deleted or inaccessible
5237 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5238 // -- a direct or virtual base class B that cannot be copied/moved because
5239 // overload resolution, as applied to B's corresponding special member,
5240 // results in an ambiguity or a function that is deleted or inaccessible
5241 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005242 // C++11 [class.dtor]p5:
5243 // -- any direct or virtual base class [...] has a type with a destructor
5244 // that is deleted or inaccessible
5245 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005246 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005247 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5248 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005249 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005250
Richard Smith852265f2012-03-30 20:53:28 +00005251 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5252 // -- any direct or virtual base class or non-static data member has a
5253 // type with a destructor that is deleted or inaccessible
5254 if (IsConstructor) {
5255 Sema::SpecialMemberOverloadResult *SMOR =
5256 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5257 false, false, false, false, false);
5258 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5259 return true;
5260 }
5261
Richard Smith921bd202012-02-26 09:11:52 +00005262 return false;
5263}
5264
5265/// Check whether we should delete a special member function due to the class
5266/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005267bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005268 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005269 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005270}
5271
5272/// Check whether we should delete a special member function due to the class
5273/// having a particular non-static data member.
5274bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5275 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5276 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5277
5278 if (CSM == Sema::CXXDefaultConstructor) {
5279 // For a default constructor, all references must be initialized in-class
5280 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005281 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5282 if (Diagnose)
5283 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5284 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005285 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005286 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005287 // C++11 [class.ctor]p5: any non-variant non-static data member of
5288 // const-qualified type (or array thereof) with no
5289 // brace-or-equal-initializer does not have a user-provided default
5290 // constructor.
5291 if (!inUnion() && FieldType.isConstQualified() &&
5292 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005293 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5294 if (Diagnose)
5295 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005296 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005297 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005298 }
5299
5300 if (inUnion() && !FieldType.isConstQualified())
5301 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005302 } else if (CSM == Sema::CXXCopyConstructor) {
5303 // For a copy constructor, data members must not be of rvalue reference
5304 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005305 if (FieldType->isRValueReferenceType()) {
5306 if (Diagnose)
5307 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5308 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005309 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005310 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005311 } else if (IsAssignment) {
5312 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005313 if (FieldType->isReferenceType()) {
5314 if (Diagnose)
5315 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5316 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005317 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005318 }
5319 if (!FieldRecord && FieldType.isConstQualified()) {
5320 // C++11 [class.copy]p23:
5321 // -- a non-static data member of const non-class type (or array thereof)
5322 if (Diagnose)
5323 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005324 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005325 return true;
5326 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005327 }
5328
5329 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005330 // Some additional restrictions exist on the variant members.
5331 if (!inUnion() && FieldRecord->isUnion() &&
5332 FieldRecord->isAnonymousStructOrUnion()) {
5333 bool AllVariantFieldsAreConst = true;
5334
Richard Smith5704fe82012-03-29 19:00:10 +00005335 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005336 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005337 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005338
5339 if (!UnionFieldType.isConstQualified())
5340 AllVariantFieldsAreConst = false;
5341
Richard Smith921bd202012-02-26 09:11:52 +00005342 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5343 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005344 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005345 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005346 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005347 }
5348
5349 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005350 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005351 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005352 if (Diagnose)
5353 S.Diag(FieldRecord->getLocation(),
5354 diag::note_deleted_default_ctor_all_const)
5355 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005356 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005357 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005358
Richard Smith5704fe82012-03-29 19:00:10 +00005359 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005360 // This is technically non-conformant, but sanity demands it.
5361 return false;
5362 }
5363
Richard Smithaf136f82012-07-18 03:51:16 +00005364 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5365 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005366 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005367 }
5368
5369 return false;
5370}
5371
5372/// C++11 [class.ctor] p5:
5373/// A defaulted default constructor for a class X is defined as deleted if
5374/// X is a union and all of its variant members are of const-qualified type.
5375bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005376 // This is a silly definition, because it gives an empty union a deleted
5377 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005378 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005379 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005380 if (Diagnose)
5381 S.Diag(MD->getParent()->getLocation(),
5382 diag::note_deleted_default_ctor_all_const)
5383 << MD->getParent() << /*not anonymous union*/0;
5384 return true;
5385 }
5386 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005387}
5388
5389/// Determine whether a defaulted special member function should be defined as
5390/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5391/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005392bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5393 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005394 if (MD->isInvalidDecl())
5395 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005396 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005397 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005398 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005399 return false;
5400
Richard Smithd951a1d2012-02-18 02:02:13 +00005401 // C++11 [expr.lambda.prim]p19:
5402 // The closure type associated with a lambda-expression has a
5403 // deleted (8.4.3) default constructor and a deleted copy
5404 // assignment operator.
5405 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005406 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5407 if (Diagnose)
5408 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005409 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005410 }
5411
Richard Smith6f1e2c62012-04-02 20:59:25 +00005412 // For an anonymous struct or union, the copy and assignment special members
5413 // will never be used, so skip the check. For an anonymous union declared at
5414 // namespace scope, the constructor and destructor are used.
5415 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5416 RD->isAnonymousStructOrUnion())
5417 return false;
5418
Richard Smith852265f2012-03-30 20:53:28 +00005419 // C++11 [class.copy]p7, p18:
5420 // If the class definition declares a move constructor or move assignment
5421 // operator, an implicitly declared copy constructor or copy assignment
5422 // operator is defined as deleted.
5423 if (MD->isImplicit() &&
5424 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005425 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005426
5427 // In Microsoft mode, a user-declared move only causes the deletion of the
5428 // corresponding copy operation, not both copy operations.
5429 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005430 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005431 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005432
5433 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005434 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005435 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005436 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005437 break;
5438 }
5439 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005440 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005441 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005442 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005443 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005444
5445 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005446 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005447 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005448 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005449 break;
5450 }
5451 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005452 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005453 }
5454
5455 if (UserDeclaredMove) {
5456 Diag(UserDeclaredMove->getLocation(),
5457 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005458 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005459 << UserDeclaredMove->isMoveAssignmentOperator();
5460 return true;
5461 }
5462 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005463
Richard Smith6f1e2c62012-04-02 20:59:25 +00005464 // Do access control from the special member function
5465 ContextRAII MethodContext(*this, MD);
5466
Richard Smith921bd202012-02-26 09:11:52 +00005467 // C++11 [class.dtor]p5:
5468 // -- for a virtual destructor, lookup of the non-array deallocation function
5469 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005470 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005471 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005472 DeclarationName Name =
5473 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5474 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005475 OperatorDelete, false)) {
5476 if (Diagnose)
5477 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005478 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005479 }
Richard Smith921bd202012-02-26 09:11:52 +00005480 }
5481
Richard Smith852265f2012-03-30 20:53:28 +00005482 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005483
Aaron Ballman574705e2014-03-13 15:41:46 +00005484 for (auto &BI : RD->bases())
5485 if (!BI.isVirtual() &&
5486 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005487 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005488
Richard Smithd1627032013-07-22 18:06:23 +00005489 // Per DR1611, do not consider virtual bases of constructors of abstract
5490 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005491 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005492 for (auto &BI : RD->vbases())
5493 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005494 return true;
5495 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005496
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005497 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005498 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005499 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005500 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005501
Richard Smithd951a1d2012-02-18 02:02:13 +00005502 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005503 return true;
5504
5505 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005506}
5507
Richard Smith92f241f2012-12-08 02:53:02 +00005508/// Perform lookup for a special member of the specified kind, and determine
5509/// whether it is trivial. If the triviality can be determined without the
5510/// lookup, skip it. This is intended for use when determining whether a
5511/// special member of a containing object is trivial, and thus does not ever
5512/// perform overload resolution for default constructors.
5513///
5514/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5515/// member that was most likely to be intended to be trivial, if any.
5516static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5517 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005518 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005519 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005520 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005521
5522 switch (CSM) {
5523 case Sema::CXXInvalid:
5524 llvm_unreachable("not a special member");
5525
5526 case Sema::CXXDefaultConstructor:
5527 // C++11 [class.ctor]p5:
5528 // A default constructor is trivial if:
5529 // - all the [direct subobjects] have trivial default constructors
5530 //
5531 // Note, no overload resolution is performed in this case.
5532 if (RD->hasTrivialDefaultConstructor())
5533 return true;
5534
5535 if (Selected) {
5536 // If there's a default constructor which could have been trivial, dig it
5537 // out. Otherwise, if there's any user-provided default constructor, point
5538 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005539 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005540 if (RD->needsImplicitDefaultConstructor())
5541 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005542 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005543 if (!CI->isDefaultConstructor())
5544 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005545 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005546 if (!DefCtor->isUserProvided())
5547 break;
5548 }
5549
5550 *Selected = DefCtor;
5551 }
5552
5553 return false;
5554
5555 case Sema::CXXDestructor:
5556 // C++11 [class.dtor]p5:
5557 // A destructor is trivial if:
5558 // - all the direct [subobjects] have trivial destructors
5559 if (RD->hasTrivialDestructor())
5560 return true;
5561
5562 if (Selected) {
5563 if (RD->needsImplicitDestructor())
5564 S.DeclareImplicitDestructor(RD);
5565 *Selected = RD->getDestructor();
5566 }
5567
5568 return false;
5569
5570 case Sema::CXXCopyConstructor:
5571 // C++11 [class.copy]p12:
5572 // A copy constructor is trivial if:
5573 // - the constructor selected to copy each direct [subobject] is trivial
5574 if (RD->hasTrivialCopyConstructor()) {
5575 if (Quals == Qualifiers::Const)
5576 // We must either select the trivial copy constructor or reach an
5577 // ambiguity; no need to actually perform overload resolution.
5578 return true;
5579 } else if (!Selected) {
5580 return false;
5581 }
5582 // In C++98, we are not supposed to perform overload resolution here, but we
5583 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5584 // cases like B as having a non-trivial copy constructor:
5585 // struct A { template<typename T> A(T&); };
5586 // struct B { mutable A a; };
5587 goto NeedOverloadResolution;
5588
5589 case Sema::CXXCopyAssignment:
5590 // C++11 [class.copy]p25:
5591 // A copy assignment operator is trivial if:
5592 // - the assignment operator selected to copy each direct [subobject] is
5593 // trivial
5594 if (RD->hasTrivialCopyAssignment()) {
5595 if (Quals == Qualifiers::Const)
5596 return true;
5597 } else if (!Selected) {
5598 return false;
5599 }
5600 // In C++98, we are not supposed to perform overload resolution here, but we
5601 // treat that as a language defect.
5602 goto NeedOverloadResolution;
5603
5604 case Sema::CXXMoveConstructor:
5605 case Sema::CXXMoveAssignment:
5606 NeedOverloadResolution:
5607 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005608 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005609
5610 // The standard doesn't describe how to behave if the lookup is ambiguous.
5611 // We treat it as not making the member non-trivial, just like the standard
5612 // mandates for the default constructor. This should rarely matter, because
5613 // the member will also be deleted.
5614 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5615 return true;
5616
5617 if (!SMOR->getMethod()) {
5618 assert(SMOR->getKind() ==
5619 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5620 return false;
5621 }
5622
5623 // We deliberately don't check if we found a deleted special member. We're
5624 // not supposed to!
5625 if (Selected)
5626 *Selected = SMOR->getMethod();
5627 return SMOR->getMethod()->isTrivial();
5628 }
5629
5630 llvm_unreachable("unknown special method kind");
5631}
5632
Benjamin Kramer3e350262013-02-15 12:30:38 +00005633static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005634 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005635 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005636 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005637
5638 // Look for constructor templates.
5639 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5640 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5641 if (CXXConstructorDecl *CD =
5642 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5643 return CD;
5644 }
5645
Craig Topperc3ec1492014-05-26 06:22:03 +00005646 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005647}
5648
5649/// The kind of subobject we are checking for triviality. The values of this
5650/// enumeration are used in diagnostics.
5651enum TrivialSubobjectKind {
5652 /// The subobject is a base class.
5653 TSK_BaseClass,
5654 /// The subobject is a non-static data member.
5655 TSK_Field,
5656 /// The object is actually the complete object.
5657 TSK_CompleteObject
5658};
5659
5660/// Check whether the special member selected for a given type would be trivial.
5661static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005662 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005663 Sema::CXXSpecialMember CSM,
5664 TrivialSubobjectKind Kind,
5665 bool Diagnose) {
5666 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5667 if (!SubRD)
5668 return true;
5669
5670 CXXMethodDecl *Selected;
5671 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005672 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005673 return true;
5674
5675 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005676 if (ConstRHS)
5677 SubType.addConst();
5678
Richard Smith92f241f2012-12-08 02:53:02 +00005679 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5680 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5681 << Kind << SubType.getUnqualifiedType();
5682 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5683 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5684 } else if (!Selected)
5685 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5686 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5687 else if (Selected->isUserProvided()) {
5688 if (Kind == TSK_CompleteObject)
5689 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5690 << Kind << SubType.getUnqualifiedType() << CSM;
5691 else {
5692 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5693 << Kind << SubType.getUnqualifiedType() << CSM;
5694 S.Diag(Selected->getLocation(), diag::note_declared_at);
5695 }
5696 } else {
5697 if (Kind != TSK_CompleteObject)
5698 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5699 << Kind << SubType.getUnqualifiedType() << CSM;
5700
5701 // Explain why the defaulted or deleted special member isn't trivial.
5702 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5703 }
5704 }
5705
5706 return false;
5707}
5708
5709/// Check whether the members of a class type allow a special member to be
5710/// trivial.
5711static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5712 Sema::CXXSpecialMember CSM,
5713 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005714 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005715 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5716 continue;
5717
5718 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5719
5720 // Pretend anonymous struct or union members are members of this class.
5721 if (FI->isAnonymousStructOrUnion()) {
5722 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5723 CSM, ConstArg, Diagnose))
5724 return false;
5725 continue;
5726 }
5727
5728 // C++11 [class.ctor]p5:
5729 // A default constructor is trivial if [...]
5730 // -- no non-static data member of its class has a
5731 // brace-or-equal-initializer
5732 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5733 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005734 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005735 return false;
5736 }
5737
5738 // Objective C ARC 4.3.5:
5739 // [...] nontrivally ownership-qualified types are [...] not trivially
5740 // default constructible, copy constructible, move constructible, copy
5741 // assignable, move assignable, or destructible [...]
5742 if (S.getLangOpts().ObjCAutoRefCount &&
5743 FieldType.hasNonTrivialObjCLifetime()) {
5744 if (Diagnose)
5745 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5746 << RD << FieldType.getObjCLifetime();
5747 return false;
5748 }
5749
Richard Smith41c35d62013-11-27 03:39:20 +00005750 bool ConstRHS = ConstArg && !FI->isMutable();
5751 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5752 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005753 return false;
5754 }
5755
5756 return true;
5757}
5758
5759/// Diagnose why the specified class does not have a trivial special member of
5760/// the given kind.
5761void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5762 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005763
Richard Smith41c35d62013-11-27 03:39:20 +00005764 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5765 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005766 TSK_CompleteObject, /*Diagnose*/true);
5767}
5768
5769/// Determine whether a defaulted or deleted special member function is trivial,
5770/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5771/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5772bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5773 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005774 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5775
5776 CXXRecordDecl *RD = MD->getParent();
5777
5778 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005779
Richard Smith2002bfe2013-11-04 02:02:27 +00005780 // C++11 [class.copy]p12, p25: [DR1593]
5781 // A [special member] is trivial if [...] its parameter-type-list is
5782 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005783 switch (CSM) {
5784 case CXXDefaultConstructor:
5785 case CXXDestructor:
5786 // Trivial default constructors and destructors cannot have parameters.
5787 break;
5788
5789 case CXXCopyConstructor:
5790 case CXXCopyAssignment: {
5791 // Trivial copy operations always have const, non-volatile parameter types.
5792 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005793 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005794 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5795 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5796 if (Diagnose)
5797 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5798 << Param0->getSourceRange() << Param0->getType()
5799 << Context.getLValueReferenceType(
5800 Context.getRecordType(RD).withConst());
5801 return false;
5802 }
5803 break;
5804 }
5805
5806 case CXXMoveConstructor:
5807 case CXXMoveAssignment: {
5808 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005809 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005810 const RValueReferenceType *RT =
5811 Param0->getType()->getAs<RValueReferenceType>();
5812 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5813 if (Diagnose)
5814 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5815 << Param0->getSourceRange() << Param0->getType()
5816 << Context.getRValueReferenceType(Context.getRecordType(RD));
5817 return false;
5818 }
5819 break;
5820 }
5821
5822 case CXXInvalid:
5823 llvm_unreachable("not a special member");
5824 }
5825
Richard Smith92f241f2012-12-08 02:53:02 +00005826 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5827 if (Diagnose)
5828 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5829 diag::note_nontrivial_default_arg)
5830 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5831 return false;
5832 }
5833 if (MD->isVariadic()) {
5834 if (Diagnose)
5835 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5836 return false;
5837 }
5838
5839 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5840 // A copy/move [constructor or assignment operator] is trivial if
5841 // -- the [member] selected to copy/move each direct base class subobject
5842 // is trivial
5843 //
5844 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5845 // A [default constructor or destructor] is trivial if
5846 // -- all the direct base classes have trivial [default constructors or
5847 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005848 for (const auto &BI : RD->bases())
5849 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005850 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005851 return false;
5852
5853 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5854 // A copy/move [constructor or assignment operator] for a class X is
5855 // trivial if
5856 // -- for each non-static data member of X that is of class type (or array
5857 // thereof), the constructor selected to copy/move that member is
5858 // trivial
5859 //
5860 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5861 // A [default constructor or destructor] is trivial if
5862 // -- for all of the non-static data members of its class that are of class
5863 // type (or array thereof), each such class has a trivial [default
5864 // constructor or destructor]
5865 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5866 return false;
5867
5868 // C++11 [class.dtor]p5:
5869 // A destructor is trivial if [...]
5870 // -- the destructor is not virtual
5871 if (CSM == CXXDestructor && MD->isVirtual()) {
5872 if (Diagnose)
5873 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5874 return false;
5875 }
5876
5877 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5878 // A [special member] for class X is trivial if [...]
5879 // -- class X has no virtual functions and no virtual base classes
5880 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5881 if (!Diagnose)
5882 return false;
5883
5884 if (RD->getNumVBases()) {
5885 // Check for virtual bases. We already know that the corresponding
5886 // member in all bases is trivial, so vbases must all be direct.
5887 CXXBaseSpecifier &BS = *RD->vbases_begin();
5888 assert(BS.isVirtual());
5889 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5890 return false;
5891 }
5892
5893 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005894 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005895 if (MI->isVirtual()) {
5896 SourceLocation MLoc = MI->getLocStart();
5897 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5898 return false;
5899 }
5900 }
5901
5902 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5903 }
5904
5905 // Looks like it's trivial!
5906 return true;
5907}
5908
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005909/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005910namespace {
5911 struct FindHiddenVirtualMethodData {
5912 Sema *S;
5913 CXXMethodDecl *Method;
5914 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005915 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005916 };
5917}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005918
David Blaikie282c92a2012-10-19 00:53:08 +00005919/// \brief Check whether any most overriden method from MD in Methods
5920static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00005921 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00005922 if (MD->size_overridden_methods() == 0)
5923 return Methods.count(MD->getCanonicalDecl());
5924 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5925 E = MD->end_overridden_methods();
5926 I != E; ++I)
5927 if (CheckMostOverridenMethods(*I, Methods))
5928 return true;
5929 return false;
5930}
5931
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005932/// \brief Member lookup function that determines whether a given C++
5933/// method overloads virtual methods in a base class without overriding any,
5934/// to be used with CXXRecordDecl::lookupInBases().
5935static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5936 CXXBasePath &Path,
5937 void *UserData) {
5938 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5939
5940 FindHiddenVirtualMethodData &Data
5941 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5942
5943 DeclarationName Name = Data.Method->getDeclName();
5944 assert(Name.getNameKind() == DeclarationName::Identifier);
5945
5946 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005947 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005948 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005949 !Path.Decls.empty();
5950 Path.Decls = Path.Decls.slice(1)) {
5951 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005953 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005954 foundSameNameMethod = true;
5955 // Interested only in hidden virtual methods.
5956 if (!MD->isVirtual())
5957 continue;
5958 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00005959 // don't warn about the other overloaded methods. Clang deviates from GCC
5960 // by only diagnosing overloads of inherited virtual functions that do not
5961 // override any other virtual functions in the base. GCC's
5962 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
5963 // function from a base class. These cases may be better served by a
5964 // warning (not specific to virtual functions) on call sites when the call
5965 // would select a different function from the base class, were it visible.
5966 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005967 if (!Data.S->IsOverload(Data.Method, MD, false))
5968 return true;
5969 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005970 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005971 overloadedMethods.push_back(MD);
5972 }
5973 }
5974
5975 if (foundSameNameMethod)
5976 Data.OverloadedMethods.append(overloadedMethods.begin(),
5977 overloadedMethods.end());
5978 return foundSameNameMethod;
5979}
5980
David Blaikie282c92a2012-10-19 00:53:08 +00005981/// \brief Add the most overriden methods from MD to Methods
5982static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00005983 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00005984 if (MD->size_overridden_methods() == 0)
5985 Methods.insert(MD->getCanonicalDecl());
5986 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5987 E = MD->end_overridden_methods();
5988 I != E; ++I)
5989 AddMostOverridenMethods(*I, Methods);
5990}
5991
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005992/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005993/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005994void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5995 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005996 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005997 return;
5998
5999 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6000 /*bool RecordPaths=*/false,
6001 /*bool DetectVirtual=*/false);
6002 FindHiddenVirtualMethodData Data;
6003 Data.Method = MD;
6004 Data.S = this;
6005
6006 // Keep the base methods that were overriden or introduced in the subclass
6007 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006008 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006009 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6010 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6011 NamedDecl *ND = *I;
6012 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006013 ND = shad->getTargetDecl();
6014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6015 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006016 }
6017
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006018 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6019 OverloadedMethods = Data.OverloadedMethods;
6020}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006021
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006022void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6023 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6024 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6025 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6026 PartialDiagnostic PD = PDiag(
6027 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6028 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6029 Diag(overloadedMD->getLocation(), PD);
6030 }
6031}
6032
6033/// \brief Diagnose methods which overload virtual methods in a base class
6034/// without overriding any.
6035void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6036 if (MD->isInvalidDecl())
6037 return;
6038
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006039 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006040 return;
6041
6042 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6043 FindHiddenVirtualMethods(MD, OverloadedMethods);
6044 if (!OverloadedMethods.empty()) {
6045 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6046 << MD << (OverloadedMethods.size() > 1);
6047
6048 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006049 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006050}
6051
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006052void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006053 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006054 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006055 SourceLocation RBrac,
6056 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006057 if (!TagDecl)
6058 return;
Mike Stump11289f42009-09-09 15:08:12 +00006059
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006060 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006061
Rafael Espindola06e1b132012-07-12 04:32:30 +00006062 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6063 if (l->getKind() != AttributeList::AT_Visibility)
6064 continue;
6065 l->setInvalid();
6066 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6067 l->getName();
6068 }
6069
David Blaikie751c5582011-09-22 02:58:26 +00006070 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006071 // strict aliasing violation!
6072 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006073 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006074
Douglas Gregor0be31a22010-07-02 17:43:08 +00006075 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006076 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006077}
6078
Douglas Gregor05379422008-11-03 17:51:48 +00006079/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6080/// special functions, such as the default constructor, copy
6081/// constructor, or destructor, to the given C++ class (C++
6082/// [special]p1). This routine can only be executed just before the
6083/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006084void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006085 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006086 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006087
Richard Smith6b02d462012-12-08 08:32:28 +00006088 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006089 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006090
Richard Smith6b02d462012-12-08 08:32:28 +00006091 // If the properties or semantics of the copy constructor couldn't be
6092 // determined while the class was being declared, force a declaration
6093 // of it now.
6094 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6095 DeclareImplicitCopyConstructor(ClassDecl);
6096 }
6097
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006098 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006099 ++ASTContext::NumImplicitMoveConstructors;
6100
Richard Smith6b02d462012-12-08 08:32:28 +00006101 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6102 DeclareImplicitMoveConstructor(ClassDecl);
6103 }
6104
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006105 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6106 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006107
6108 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006109 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006110 // it shows up in the right place in the vtable and that we diagnose
6111 // problems with the implicit exception specification.
6112 if (ClassDecl->isDynamicClass() ||
6113 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006114 DeclareImplicitCopyAssignment(ClassDecl);
6115 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006116
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006117 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006118 ++ASTContext::NumImplicitMoveAssignmentOperators;
6119
6120 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006121 if (ClassDecl->isDynamicClass() ||
6122 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006123 DeclareImplicitMoveAssignment(ClassDecl);
6124 }
6125
Douglas Gregor7454c562010-07-02 20:37:36 +00006126 if (!ClassDecl->hasUserDeclaredDestructor()) {
6127 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006128
6129 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006130 // have to declare the destructor immediately. This ensures that, e.g., it
6131 // shows up in the right place in the vtable and that we diagnose problems
6132 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006133 if (ClassDecl->isDynamicClass() ||
6134 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006135 DeclareImplicitDestructor(ClassDecl);
6136 }
Douglas Gregor05379422008-11-03 17:51:48 +00006137}
6138
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006139unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006140 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006141 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006142
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006143 // The order of template parameters is not important here. All names
6144 // get added to the same scope.
6145 SmallVector<TemplateParameterList *, 4> ParameterLists;
6146
6147 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6148 D = TD->getTemplatedDecl();
6149
6150 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6151 ParameterLists.push_back(PSD->getTemplateParameters());
6152
6153 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6154 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6155 ParameterLists.push_back(DD->getTemplateParameterList(i));
6156
6157 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6158 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6159 ParameterLists.push_back(FTD->getTemplateParameters());
6160 }
6161 }
6162
6163 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6164 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6165 ParameterLists.push_back(TD->getTemplateParameterList(i));
6166
6167 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6168 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6169 ParameterLists.push_back(CTD->getTemplateParameters());
6170 }
6171 }
6172
6173 unsigned Count = 0;
6174 for (TemplateParameterList *Params : ParameterLists) {
6175 if (Params->size() > 0)
6176 // Ignore explicit specializations; they don't contribute to the template
6177 // depth.
6178 ++Count;
6179 for (NamedDecl *Param : *Params) {
6180 if (Param->getDeclName()) {
6181 S->AddDecl(Param);
6182 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006183 }
6184 }
6185 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006186
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006187 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006188}
6189
John McCall48871652010-08-21 09:40:31 +00006190void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006191 if (!RecordD) return;
6192 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006193 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006194 PushDeclContext(S, Record);
6195}
6196
John McCall48871652010-08-21 09:40:31 +00006197void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006198 if (!RecordD) return;
6199 PopDeclContext();
6200}
6201
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006202/// This is used to implement the constant expression evaluation part of the
6203/// attribute enable_if extension. There is nothing in standard C++ which would
6204/// require reentering parameters.
6205void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6206 if (!Param)
6207 return;
6208
6209 S->AddDecl(Param);
6210 if (Param->getDeclName())
6211 IdResolver.AddDecl(Param);
6212}
6213
Douglas Gregor4d87df52008-12-16 21:30:33 +00006214/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6215/// parsing a top-level (non-nested) C++ class, and we are now
6216/// parsing those parts of the given Method declaration that could
6217/// not be parsed earlier (C++ [class.mem]p2), such as default
6218/// arguments. This action should enter the scope of the given
6219/// Method declaration as if we had just parsed the qualified method
6220/// name. However, it should not bring the parameters into scope;
6221/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006222void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006223}
6224
6225/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6226/// C++ method declaration. We're (re-)introducing the given
6227/// function parameter into scope for use in parsing later parts of
6228/// the method declaration. For example, we could see an
6229/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006230void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006231 if (!ParamD)
6232 return;
Mike Stump11289f42009-09-09 15:08:12 +00006233
John McCall48871652010-08-21 09:40:31 +00006234 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006235
6236 // If this parameter has an unparsed default argument, clear it out
6237 // to make way for the parsed default argument.
6238 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006239 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006240
John McCall48871652010-08-21 09:40:31 +00006241 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006242 if (Param->getDeclName())
6243 IdResolver.AddDecl(Param);
6244}
6245
6246/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6247/// processing the delayed method declaration for Method. The method
6248/// declaration is now considered finished. There may be a separate
6249/// ActOnStartOfFunctionDef action later (not necessarily
6250/// immediately!) for this method, if it was also defined inside the
6251/// class body.
John McCall48871652010-08-21 09:40:31 +00006252void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006253 if (!MethodD)
6254 return;
Mike Stump11289f42009-09-09 15:08:12 +00006255
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006256 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006257
John McCall48871652010-08-21 09:40:31 +00006258 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006259
6260 // Now that we have our default arguments, check the constructor
6261 // again. It could produce additional diagnostics or affect whether
6262 // the class has implicitly-declared destructors, among other
6263 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006264 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6265 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006266
6267 // Check the default arguments, which we may have added.
6268 if (!Method->isInvalidDecl())
6269 CheckCXXDefaultArguments(Method);
6270}
6271
Douglas Gregor831c93f2008-11-05 20:51:48 +00006272/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006273/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006274/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006275/// emit diagnostics and set the invalid bit to true. In any case, the type
6276/// will be updated to reflect a well-formed type for the constructor and
6277/// returned.
6278QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006279 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006280 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006281
6282 // C++ [class.ctor]p3:
6283 // A constructor shall not be virtual (10.3) or static (9.4). A
6284 // constructor can be invoked for a const, volatile or const
6285 // volatile object. A constructor shall not be declared const,
6286 // volatile, or const volatile (9.3.2).
6287 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006288 if (!D.isInvalidType())
6289 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6290 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6291 << SourceRange(D.getIdentifierLoc());
6292 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006293 }
John McCall8e7d6562010-08-26 03:08:43 +00006294 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006295 if (!D.isInvalidType())
6296 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6297 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6298 << SourceRange(D.getIdentifierLoc());
6299 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006300 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006301 }
Mike Stump11289f42009-09-09 15:08:12 +00006302
David Majnemer03f705f2014-07-08 18:18:04 +00006303 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6304 diagnoseIgnoredQualifiers(
6305 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6306 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6307 D.getDeclSpec().getRestrictSpecLoc(),
6308 D.getDeclSpec().getAtomicSpecLoc());
6309 D.setInvalidType();
6310 }
6311
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006312 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006313 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006314 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006315 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6316 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006317 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006318 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6319 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006320 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006321 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6322 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006323 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006324 }
Mike Stump11289f42009-09-09 15:08:12 +00006325
Douglas Gregordb9d6642011-01-26 05:01:58 +00006326 // C++0x [class.ctor]p4:
6327 // A constructor shall not be declared with a ref-qualifier.
6328 if (FTI.hasRefQualifier()) {
6329 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6330 << FTI.RefQualifierIsLValueRef
6331 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6332 D.setInvalidType();
6333 }
6334
Douglas Gregor831c93f2008-11-05 20:51:48 +00006335 // Rebuild the function type "R" without any type qualifiers (in
6336 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006337 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006338 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006339 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006340 return R;
6341
6342 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6343 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006344 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006345
6346 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006347}
6348
Douglas Gregor4d87df52008-12-16 21:30:33 +00006349/// CheckConstructor - Checks a fully-formed constructor for
6350/// well-formedness, issuing any diagnostics required. Returns true if
6351/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006352void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006353 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006354 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6355 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006356 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006357
6358 // C++ [class.copy]p3:
6359 // A declaration of a constructor for a class X is ill-formed if
6360 // its first parameter is of type (optionally cv-qualified) X and
6361 // either there are no other parameters or else all other
6362 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006363 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006364 ((Constructor->getNumParams() == 1) ||
6365 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006366 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6367 Constructor->getTemplateSpecializationKind()
6368 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006369 QualType ParamType = Constructor->getParamDecl(0)->getType();
6370 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6371 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006372 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006373 const char *ConstRef
6374 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6375 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006376 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006377 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006378
6379 // FIXME: Rather that making the constructor invalid, we should endeavor
6380 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006381 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006382 }
6383 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006384}
6385
John McCalldeb646e2010-08-04 01:04:25 +00006386/// CheckDestructor - Checks a fully-formed destructor definition for
6387/// well-formedness, issuing any diagnostics required. Returns true
6388/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006389bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006390 CXXRecordDecl *RD = Destructor->getParent();
6391
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006392 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006393 SourceLocation Loc;
6394
6395 if (!Destructor->isImplicit())
6396 Loc = Destructor->getLocation();
6397 else
6398 Loc = RD->getLocation();
6399
6400 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006401 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006402 DeclarationName Name =
6403 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006404 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006405 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006406 // If there's no class-specific operator delete, look up the global
6407 // non-array delete.
6408 if (!OperatorDelete)
6409 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006410
Eli Friedmanfa0df832012-02-02 03:46:19 +00006411 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006412
6413 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006414 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006415
6416 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006417}
6418
Douglas Gregor831c93f2008-11-05 20:51:48 +00006419/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6420/// the well-formednes of the destructor declarator @p D with type @p
6421/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006422/// emit diagnostics and set the declarator to invalid. Even if this happens,
6423/// will be updated to reflect a well-formed type for the destructor and
6424/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006425QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006426 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006427 // C++ [class.dtor]p1:
6428 // [...] A typedef-name that names a class is a class-name
6429 // (7.1.3); however, a typedef-name that names a class shall not
6430 // be used as the identifier in the declarator for a destructor
6431 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006432 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006433 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006434 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006435 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006436 else if (const TemplateSpecializationType *TST =
6437 DeclaratorType->getAs<TemplateSpecializationType>())
6438 if (TST->isTypeAlias())
6439 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6440 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006441
6442 // C++ [class.dtor]p2:
6443 // A destructor is used to destroy objects of its class type. A
6444 // destructor takes no parameters, and no return type can be
6445 // specified for it (not even void). The address of a destructor
6446 // shall not be taken. A destructor shall not be static. A
6447 // destructor can be invoked for a const, volatile or const
6448 // volatile object. A destructor shall not be declared const,
6449 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006450 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006451 if (!D.isInvalidType())
6452 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6453 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006454 << SourceRange(D.getIdentifierLoc())
6455 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6456
John McCall8e7d6562010-08-26 03:08:43 +00006457 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006458 }
David Majnemer03f705f2014-07-08 18:18:04 +00006459 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006460 // Destructors don't have return types, but the parser will
6461 // happily parse something like:
6462 //
6463 // class X {
6464 // float ~X();
6465 // };
6466 //
6467 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006468 if (D.getDeclSpec().hasTypeSpecifier())
6469 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6470 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6471 << SourceRange(D.getIdentifierLoc());
6472 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6473 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6474 SourceLocation(),
6475 D.getDeclSpec().getConstSpecLoc(),
6476 D.getDeclSpec().getVolatileSpecLoc(),
6477 D.getDeclSpec().getRestrictSpecLoc(),
6478 D.getDeclSpec().getAtomicSpecLoc());
6479 D.setInvalidType();
6480 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006481 }
Mike Stump11289f42009-09-09 15:08:12 +00006482
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006483 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006484 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006485 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006486 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6487 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006488 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006489 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6490 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006491 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006492 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6493 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006494 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006495 }
6496
Douglas Gregordb9d6642011-01-26 05:01:58 +00006497 // C++0x [class.dtor]p2:
6498 // A destructor shall not be declared with a ref-qualifier.
6499 if (FTI.hasRefQualifier()) {
6500 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6501 << FTI.RefQualifierIsLValueRef
6502 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6503 D.setInvalidType();
6504 }
6505
Douglas Gregor831c93f2008-11-05 20:51:48 +00006506 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006507 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006508 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6509
6510 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006511 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006512 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006513 }
6514
Mike Stump11289f42009-09-09 15:08:12 +00006515 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006516 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006517 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006518 D.setInvalidType();
6519 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006520
6521 // Rebuild the function type "R" without any type qualifiers or
6522 // parameters (in case any of the errors above fired) and with
6523 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006524 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006525 if (!D.isInvalidType())
6526 return R;
6527
Douglas Gregor95755162010-07-01 05:10:53 +00006528 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006529 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6530 EPI.Variadic = false;
6531 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006532 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006533 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006534}
6535
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006536/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6537/// well-formednes of the conversion function declarator @p D with
6538/// type @p R. If there are any errors in the declarator, this routine
6539/// will emit diagnostics and return true. Otherwise, it will return
6540/// false. Either way, the type @p R will be updated to reflect a
6541/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006542void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006543 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006544 // C++ [class.conv.fct]p1:
6545 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006546 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006547 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006548 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006549 if (!D.isInvalidType())
6550 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006551 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6552 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006553 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006554 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006555 }
John McCall212fa2e2010-04-13 00:04:31 +00006556
6557 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6558
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006559 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006560 // Conversion functions don't have return types, but the parser will
6561 // happily parse something like:
6562 //
6563 // class X {
6564 // float operator bool();
6565 // };
6566 //
6567 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006568 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6569 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6570 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006571 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006572 }
6573
John McCall212fa2e2010-04-13 00:04:31 +00006574 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6575
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006576 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006577 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006578 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6579
6580 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006581 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006582 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006583 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006584 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006585 D.setInvalidType();
6586 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006587
John McCall212fa2e2010-04-13 00:04:31 +00006588 // Diagnose "&operator bool()" and other such nonsense. This
6589 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006590 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006591 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006592 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006593 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006594 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006595 }
6596
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006597 // C++ [class.conv.fct]p4:
6598 // The conversion-type-id shall not represent a function type nor
6599 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006600 if (ConvType->isArrayType()) {
6601 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6602 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006603 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006604 } else if (ConvType->isFunctionType()) {
6605 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6606 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006607 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006608 }
6609
6610 // Rebuild the function type "R" without any parameters (in case any
6611 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006612 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006613 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006614 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006615
Douglas Gregor5fb53972009-01-14 15:45:31 +00006616 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006617 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006618 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006619 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006620 diag::warn_cxx98_compat_explicit_conversion_functions :
6621 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006622 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006623}
6624
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006625/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6626/// the declaration of the given C++ conversion function. This routine
6627/// is responsible for recording the conversion function in the C++
6628/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006629Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006630 assert(Conversion && "Expected to receive a conversion function declaration");
6631
Douglas Gregor4287b372008-12-12 08:25:50 +00006632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006633
6634 // Make sure we aren't redeclaring the conversion function.
6635 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006636
6637 // C++ [class.conv.fct]p1:
6638 // [...] A conversion function is never used to convert a
6639 // (possibly cv-qualified) object to the (possibly cv-qualified)
6640 // same object type (or a reference to it), to a (possibly
6641 // cv-qualified) base class of that type (or a reference to it),
6642 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006643 // FIXME: Suppress this warning if the conversion function ends up being a
6644 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006645 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006646 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006647 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006648 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006649 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6650 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006651 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006652 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006653 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6654 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006655 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006656 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006657 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006658 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006659 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006660 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006661 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006662 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006663 }
6664
Douglas Gregor457104e2010-09-29 04:25:11 +00006665 if (FunctionTemplateDecl *ConversionTemplate
6666 = Conversion->getDescribedFunctionTemplate())
6667 return ConversionTemplate;
6668
John McCall48871652010-08-21 09:40:31 +00006669 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006670}
6671
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006672//===----------------------------------------------------------------------===//
6673// Namespace Handling
6674//===----------------------------------------------------------------------===//
6675
Richard Smith45bb8852012-10-04 22:13:39 +00006676/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6677/// reopened.
6678static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6679 SourceLocation Loc,
6680 IdentifierInfo *II, bool *IsInline,
6681 NamespaceDecl *PrevNS) {
6682 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006683
Richard Smithf501cc32012-10-05 01:46:25 +00006684 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6685 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6686 // inline namespaces, with the intention of bringing names into namespace std.
6687 //
6688 // We support this just well enough to get that case working; this is not
6689 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006690 if (*IsInline && II && II->getName().startswith("__atomic") &&
6691 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006692 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006693 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6694 NS = NS->getPreviousDecl())
6695 NS->setInline(*IsInline);
6696 // Patch up the lookup table for the containing namespace. This isn't really
6697 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006698 for (auto *I : PrevNS->decls())
6699 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006700 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6701 return;
6702 }
6703
6704 if (PrevNS->isInline())
6705 // The user probably just forgot the 'inline', so suggest that it
6706 // be added back.
6707 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6708 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6709 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006710 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006711
6712 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6713 *IsInline = PrevNS->isInline();
6714}
John McCallb1be5232010-08-26 09:15:37 +00006715
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006716/// ActOnStartNamespaceDef - This is called at the start of a namespace
6717/// definition.
John McCall48871652010-08-21 09:40:31 +00006718Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006719 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006720 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006721 SourceLocation IdentLoc,
6722 IdentifierInfo *II,
6723 SourceLocation LBrace,
6724 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006725 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6726 // For anonymous namespace, take the location of the left brace.
6727 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006728 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006729 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006730 bool IsStd = false;
6731 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006732 Scope *DeclRegionScope = NamespcScope->getParent();
6733
Craig Topperc3ec1492014-05-26 06:22:03 +00006734 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006735 if (II) {
6736 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006737 // The identifier in an original-namespace-definition shall not
6738 // have been previously defined in the declarative region in
6739 // which the original-namespace-definition appears. The
6740 // identifier in an original-namespace-definition is the name of
6741 // the namespace. Subsequently in that declarative region, it is
6742 // treated as an original-namespace-name.
6743 //
6744 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006745 // look through using directives, just look for any ordinary names.
6746
6747 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006748 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6749 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006750 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006751 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6752 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6753 ++I) {
6754 if ((*I)->getIdentifierNamespace() & IDNS) {
6755 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006756 break;
6757 }
6758 }
6759
Douglas Gregore57e7522012-01-07 09:11:48 +00006760 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6761
6762 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006763 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006764 if (IsInline != PrevNS->isInline())
6765 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6766 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006767 } else if (PrevDecl) {
6768 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006769 Diag(Loc, diag::err_redefinition_different_kind)
6770 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006771 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006772 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006773 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006774 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006775 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006776 // This is the first "real" definition of the namespace "std", so update
6777 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006778 PrevNS = getStdNamespace();
6779 IsStd = true;
6780 AddToKnown = !IsInline;
6781 } else {
6782 // We've seen this namespace for the first time.
6783 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006784 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006785 } else {
John McCall4fa53422009-10-01 00:25:31 +00006786 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006787
6788 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006789 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006790 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006791 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006792 } else {
6793 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006794 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006795 }
6796
Richard Smith45bb8852012-10-04 22:13:39 +00006797 if (PrevNS && IsInline != PrevNS->isInline())
6798 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6799 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006800 }
6801
6802 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6803 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006804 if (IsInvalid)
6805 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006806
6807 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006808
Douglas Gregore57e7522012-01-07 09:11:48 +00006809 // FIXME: Should we be merging attributes?
6810 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006811 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006812
6813 if (IsStd)
6814 StdNamespace = Namespc;
6815 if (AddToKnown)
6816 KnownNamespaces[Namespc] = false;
6817
6818 if (II) {
6819 PushOnScopeChains(Namespc, DeclRegionScope);
6820 } else {
6821 // Link the anonymous namespace into its parent.
6822 DeclContext *Parent = CurContext->getRedeclContext();
6823 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6824 TU->setAnonymousNamespace(Namespc);
6825 } else {
6826 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006827 }
John McCall4fa53422009-10-01 00:25:31 +00006828
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006829 CurContext->addDecl(Namespc);
6830
John McCall4fa53422009-10-01 00:25:31 +00006831 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6832 // behaves as if it were replaced by
6833 // namespace unique { /* empty body */ }
6834 // using namespace unique;
6835 // namespace unique { namespace-body }
6836 // where all occurrences of 'unique' in a translation unit are
6837 // replaced by the same identifier and this identifier differs
6838 // from all other identifiers in the entire program.
6839
6840 // We just create the namespace with an empty name and then add an
6841 // implicit using declaration, just like the standard suggests.
6842 //
6843 // CodeGen enforces the "universally unique" aspect by giving all
6844 // declarations semantically contained within an anonymous
6845 // namespace internal linkage.
6846
Douglas Gregore57e7522012-01-07 09:11:48 +00006847 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006848 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006849 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006850 /* 'using' */ LBrace,
6851 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006852 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006853 /* identifier */ SourceLocation(),
6854 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006855 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006856 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006857 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006858 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006859 }
6860
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006861 ActOnDocumentableDecl(Namespc);
6862
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006863 // Although we could have an invalid decl (i.e. the namespace name is a
6864 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006865 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6866 // for the namespace has the declarations that showed up in that particular
6867 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006868 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006869 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006870}
6871
Sebastian Redla6602e92009-11-23 15:34:23 +00006872/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6873/// is a namespace alias, returns the namespace it points to.
6874static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6875 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6876 return AD->getNamespace();
6877 return dyn_cast_or_null<NamespaceDecl>(D);
6878}
6879
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006880/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6881/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006882void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006883 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6884 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006885 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006886 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006887 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006888 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006889}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006890
John McCall28a0cf72010-08-25 07:42:41 +00006891CXXRecordDecl *Sema::getStdBadAlloc() const {
6892 return cast_or_null<CXXRecordDecl>(
6893 StdBadAlloc.get(Context.getExternalSource()));
6894}
6895
6896NamespaceDecl *Sema::getStdNamespace() const {
6897 return cast_or_null<NamespaceDecl>(
6898 StdNamespace.get(Context.getExternalSource()));
6899}
6900
Douglas Gregorcdf87022010-06-29 17:53:46 +00006901/// \brief Retrieve the special "std" namespace, which may require us to
6902/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006903NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006904 if (!StdNamespace) {
6905 // The "std" namespace has not yet been defined, so build one implicitly.
6906 StdNamespace = NamespaceDecl::Create(Context,
6907 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006908 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006909 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006910 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006911 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006912 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006913 }
6914
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006915 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006916}
6917
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006918bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006919 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006920 "Looking for std::initializer_list outside of C++.");
6921
6922 // We're looking for implicit instantiations of
6923 // template <typename E> class std::initializer_list.
6924
6925 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6926 return false;
6927
Craig Topperc3ec1492014-05-26 06:22:03 +00006928 ClassTemplateDecl *Template = nullptr;
6929 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006930
Sebastian Redl43144e72012-01-17 22:49:58 +00006931 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006932
Sebastian Redl43144e72012-01-17 22:49:58 +00006933 ClassTemplateSpecializationDecl *Specialization =
6934 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6935 if (!Specialization)
6936 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006937
Sebastian Redl43144e72012-01-17 22:49:58 +00006938 Template = Specialization->getSpecializedTemplate();
6939 Arguments = Specialization->getTemplateArgs().data();
6940 } else if (const TemplateSpecializationType *TST =
6941 Ty->getAs<TemplateSpecializationType>()) {
6942 Template = dyn_cast_or_null<ClassTemplateDecl>(
6943 TST->getTemplateName().getAsTemplateDecl());
6944 Arguments = TST->getArgs();
6945 }
6946 if (!Template)
6947 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006948
6949 if (!StdInitializerList) {
6950 // Haven't recognized std::initializer_list yet, maybe this is it.
6951 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6952 if (TemplateClass->getIdentifier() !=
6953 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006954 !getStdNamespace()->InEnclosingNamespaceSetOf(
6955 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006956 return false;
6957 // This is a template called std::initializer_list, but is it the right
6958 // template?
6959 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006960 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006961 return false;
6962 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6963 return false;
6964
6965 // It's the right template.
6966 StdInitializerList = Template;
6967 }
6968
6969 if (Template != StdInitializerList)
6970 return false;
6971
6972 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006973 if (Element)
6974 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006975 return true;
6976}
6977
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006978static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6979 NamespaceDecl *Std = S.getStdNamespace();
6980 if (!Std) {
6981 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006982 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006983 }
6984
6985 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6986 Loc, Sema::LookupOrdinaryName);
6987 if (!S.LookupQualifiedName(Result, Std)) {
6988 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006989 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006990 }
6991 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6992 if (!Template) {
6993 Result.suppressDiagnostics();
6994 // We found something weird. Complain about the first thing we found.
6995 NamedDecl *Found = *Result.begin();
6996 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00006997 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006998 }
6999
7000 // We found some template called std::initializer_list. Now verify that it's
7001 // correct.
7002 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007003 if (Params->getMinRequiredArguments() != 1 ||
7004 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007005 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007006 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007007 }
7008
7009 return Template;
7010}
7011
7012QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7013 if (!StdInitializerList) {
7014 StdInitializerList = LookupStdInitializerList(*this, Loc);
7015 if (!StdInitializerList)
7016 return QualType();
7017 }
7018
7019 TemplateArgumentListInfo Args(Loc, Loc);
7020 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7021 Context.getTrivialTypeSourceInfo(Element,
7022 Loc)));
7023 return Context.getCanonicalType(
7024 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7025}
7026
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007027bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7028 // C++ [dcl.init.list]p2:
7029 // A constructor is an initializer-list constructor if its first parameter
7030 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7031 // std::initializer_list<E> for some type E, and either there are no other
7032 // parameters or else all other parameters have default arguments.
7033 if (Ctor->getNumParams() < 1 ||
7034 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7035 return false;
7036
7037 QualType ArgType = Ctor->getParamDecl(0)->getType();
7038 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7039 ArgType = RT->getPointeeType().getUnqualifiedType();
7040
Craig Topperc3ec1492014-05-26 06:22:03 +00007041 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007042}
7043
Douglas Gregora172e082011-03-26 22:25:30 +00007044/// \brief Determine whether a using statement is in a context where it will be
7045/// apply in all contexts.
7046static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7047 switch (CurContext->getDeclKind()) {
7048 case Decl::TranslationUnit:
7049 return true;
7050 case Decl::LinkageSpec:
7051 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7052 default:
7053 return false;
7054 }
7055}
7056
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007057namespace {
7058
7059// Callback to only accept typo corrections that are namespaces.
7060class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007061public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007062 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007063 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007064 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007065 return false;
7066 }
7067};
7068
7069}
7070
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007071static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7072 CXXScopeSpec &SS,
7073 SourceLocation IdentLoc,
7074 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007075 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007076 R.clear();
7077 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007078 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00007079 Validator,
7080 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007081 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007082 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7083 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007084 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007085 S.diagnoseTypo(Corrected,
7086 S.PDiag(diag::err_using_directive_member_suggest)
7087 << Ident << DC << DroppedSpecifier << SS.getRange(),
7088 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007089 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007090 S.diagnoseTypo(Corrected,
7091 S.PDiag(diag::err_using_directive_suggest) << Ident,
7092 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007093 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007094 R.addDecl(Corrected.getCorrectionDecl());
7095 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007096 }
7097 return false;
7098}
7099
John McCall48871652010-08-21 09:40:31 +00007100Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007101 SourceLocation UsingLoc,
7102 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007103 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007104 SourceLocation IdentLoc,
7105 IdentifierInfo *NamespcName,
7106 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007107 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7108 assert(NamespcName && "Invalid NamespcName.");
7109 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007110
7111 // This can only happen along a recovery path.
7112 while (S->getFlags() & Scope::TemplateParamScope)
7113 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007114 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007115
Craig Topperc3ec1492014-05-26 06:22:03 +00007116 UsingDirectiveDecl *UDir = nullptr;
7117 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007118 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007119 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007120
Douglas Gregor34074322009-01-14 22:20:51 +00007121 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007122 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7123 LookupParsedName(R, S, &SS);
7124 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007125 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007126
Douglas Gregorcdf87022010-06-29 17:53:46 +00007127 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007128 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007129 // Allow "using namespace std;" or "using namespace ::std;" even if
7130 // "std" hasn't been defined yet, for GCC compatibility.
7131 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7132 NamespcName->isStr("std")) {
7133 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007134 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007135 R.resolveKind();
7136 }
7137 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007138 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007139 }
7140
John McCall9f3059a2009-10-09 21:13:30 +00007141 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007142 NamedDecl *Named = R.getFoundDecl();
7143 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7144 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007145 // C++ [namespace.udir]p1:
7146 // A using-directive specifies that the names in the nominated
7147 // namespace can be used in the scope in which the
7148 // using-directive appears after the using-directive. During
7149 // unqualified name lookup (3.4.1), the names appear as if they
7150 // were declared in the nearest enclosing namespace which
7151 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007152 // namespace. [Note: in this context, "contains" means "contains
7153 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007154
7155 // Find enclosing context containing both using-directive and
7156 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007157 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007158 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7159 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7160 CommonAncestor = CommonAncestor->getParent();
7161
Sebastian Redla6602e92009-11-23 15:34:23 +00007162 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007163 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007164 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007165
Douglas Gregora172e082011-03-26 22:25:30 +00007166 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007167 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007168 Diag(IdentLoc, diag::warn_using_directive_in_header);
7169 }
7170
Douglas Gregor889ceb72009-02-03 19:21:40 +00007171 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007172 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007173 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007174 }
7175
Richard Smith54ecd982013-02-20 19:22:51 +00007176 if (UDir)
7177 ProcessDeclAttributeList(S, UDir, AttrList);
7178
John McCall48871652010-08-21 09:40:31 +00007179 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007180}
7181
7182void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007183 // If the scope has an associated entity and the using directive is at
7184 // namespace or translation unit scope, add the UsingDirectiveDecl into
7185 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007186 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007187 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007188 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007189 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007190 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007191 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007192 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007193}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007194
Douglas Gregorfec52632009-06-20 00:51:54 +00007195
John McCall48871652010-08-21 09:40:31 +00007196Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007197 AccessSpecifier AS,
7198 bool HasUsingKeyword,
7199 SourceLocation UsingLoc,
7200 CXXScopeSpec &SS,
7201 UnqualifiedId &Name,
7202 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007203 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007204 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007205 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007206
Douglas Gregor220f4272009-11-04 16:30:06 +00007207 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007208 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007209 case UnqualifiedId::IK_Identifier:
7210 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007211 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007212 case UnqualifiedId::IK_ConversionFunctionId:
7213 break;
7214
7215 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007216 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007217 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007218 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007219 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007220 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007221 diag::err_using_decl_constructor)
7222 << SS.getRange();
7223
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007224 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007225
Craig Topperc3ec1492014-05-26 06:22:03 +00007226 return nullptr;
7227
Douglas Gregor220f4272009-11-04 16:30:06 +00007228 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007229 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007230 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007231 return nullptr;
7232
Douglas Gregor220f4272009-11-04 16:30:06 +00007233 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007234 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007235 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007236 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007237 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007238
7239 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7240 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007241 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007242 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007243
Richard Smithc2bc61b2013-03-18 21:12:30 +00007244 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007245 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007246 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007247 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7248 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007249 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007250 }
7251
Douglas Gregorc4356532010-12-16 00:46:58 +00007252 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7253 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007254 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007255
John McCall3f746822009-11-17 05:59:44 +00007256 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007257 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007258 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007259 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007260 if (UD)
7261 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007262
John McCall48871652010-08-21 09:40:31 +00007263 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007264}
7265
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007266/// \brief Determine whether a using declaration considers the given
7267/// declarations as "equivalent", e.g., if they are redeclarations of
7268/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007269static bool
7270IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7271 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007272 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007273
Richard Smithdda56e42011-04-15 14:24:37 +00007274 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007275 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007276 return Context.hasSameType(TD1->getUnderlyingType(),
7277 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007278
7279 return false;
7280}
7281
7282
John McCall84d87672009-12-10 09:41:52 +00007283/// Determines whether to create a using shadow decl for a particular
7284/// decl, given the set of decls existing prior to this using lookup.
7285bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007286 const LookupResult &Previous,
7287 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007288 // Diagnose finding a decl which is not from a base class of the
7289 // current class. We do this now because there are cases where this
7290 // function will silently decide not to build a shadow decl, which
7291 // will pre-empt further diagnostics.
7292 //
7293 // We don't need to do this in C++0x because we do the check once on
7294 // the qualifier.
7295 //
7296 // FIXME: diagnose the following if we care enough:
7297 // struct A { int foo; };
7298 // struct B : A { using A::foo; };
7299 // template <class T> struct C : A {};
7300 // template <class T> struct D : C<T> { using B::foo; } // <---
7301 // This is invalid (during instantiation) in C++03 because B::foo
7302 // resolves to the using decl in B, which is not a base class of D<T>.
7303 // We can't diagnose it immediately because C<T> is an unknown
7304 // specialization. The UsingShadowDecl in D<T> then points directly
7305 // to A::foo, which will look well-formed when we instantiate.
7306 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007307 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007308 DeclContext *OrigDC = Orig->getDeclContext();
7309
7310 // Handle enums and anonymous structs.
7311 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7312 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7313 while (OrigRec->isAnonymousStructOrUnion())
7314 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7315
7316 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7317 if (OrigDC == CurContext) {
7318 Diag(Using->getLocation(),
7319 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007320 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007321 Diag(Orig->getLocation(), diag::note_using_decl_target);
7322 return true;
7323 }
7324
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007325 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007326 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007327 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007328 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007329 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007330 Diag(Orig->getLocation(), diag::note_using_decl_target);
7331 return true;
7332 }
7333 }
7334
7335 if (Previous.empty()) return false;
7336
7337 NamedDecl *Target = Orig;
7338 if (isa<UsingShadowDecl>(Target))
7339 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7340
John McCalla17e83e2009-12-11 02:33:26 +00007341 // If the target happens to be one of the previous declarations, we
7342 // don't have a conflict.
7343 //
7344 // FIXME: but we might be increasing its access, in which case we
7345 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007346 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007347 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007348 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7349 I != E; ++I) {
7350 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007351 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7352 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7353 PrevShadow = Shadow;
7354 FoundEquivalentDecl = true;
7355 }
John McCalla17e83e2009-12-11 02:33:26 +00007356
7357 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7358 }
7359
Richard Smithfd8634a2013-10-23 02:17:46 +00007360 if (FoundEquivalentDecl)
7361 return false;
7362
Alp Tokera2794f92014-01-22 07:29:52 +00007363 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007364 NamedDecl *OldDecl = nullptr;
7365 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7366 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007367 case Ovl_Overload:
7368 return false;
7369
7370 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007371 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007372 break;
Richard Smith18819302014-02-06 01:31:33 +00007373
John McCall84d87672009-12-10 09:41:52 +00007374 // We found a decl with the exact signature.
7375 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007376 // If we're in a record, we want to hide the target, so we
7377 // return true (without a diagnostic) to tell the caller not to
7378 // build a shadow decl.
7379 if (CurContext->isRecord())
7380 return true;
7381
7382 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007383 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007384 break;
7385 }
7386
7387 Diag(Target->getLocation(), diag::note_using_decl_target);
7388 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7389 return true;
7390 }
7391
7392 // Target is not a function.
7393
John McCall84d87672009-12-10 09:41:52 +00007394 if (isa<TagDecl>(Target)) {
7395 // No conflict between a tag and a non-tag.
7396 if (!Tag) return false;
7397
John McCalle29c5cd2009-12-10 19:51:03 +00007398 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007399 Diag(Target->getLocation(), diag::note_using_decl_target);
7400 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7401 return true;
7402 }
7403
7404 // No conflict between a tag and a non-tag.
7405 if (!NonTag) return false;
7406
John McCalle29c5cd2009-12-10 19:51:03 +00007407 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007408 Diag(Target->getLocation(), diag::note_using_decl_target);
7409 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7410 return true;
7411}
7412
John McCall3f746822009-11-17 05:59:44 +00007413/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007414UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007415 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007416 NamedDecl *Orig,
7417 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007418
7419 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007420 NamedDecl *Target = Orig;
7421 if (isa<UsingShadowDecl>(Target)) {
7422 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7423 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007424 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007425
John McCall3f746822009-11-17 05:59:44 +00007426 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007427 = UsingShadowDecl::Create(Context, CurContext,
7428 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007429 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007430
Douglas Gregor457104e2010-09-29 04:25:11 +00007431 Shadow->setAccess(UD->getAccess());
7432 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7433 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007434
7435 Shadow->setPreviousDecl(PrevDecl);
7436
John McCall3f746822009-11-17 05:59:44 +00007437 if (S)
John McCall3969e302009-12-08 07:46:18 +00007438 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007439 else
John McCall3969e302009-12-08 07:46:18 +00007440 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007441
John McCall3969e302009-12-08 07:46:18 +00007442
John McCall84d87672009-12-10 09:41:52 +00007443 return Shadow;
7444}
John McCall3969e302009-12-08 07:46:18 +00007445
John McCall84d87672009-12-10 09:41:52 +00007446/// Hides a using shadow declaration. This is required by the current
7447/// using-decl implementation when a resolvable using declaration in a
7448/// class is followed by a declaration which would hide or override
7449/// one or more of the using decl's targets; for example:
7450///
7451/// struct Base { void foo(int); };
7452/// struct Derived : Base {
7453/// using Base::foo;
7454/// void foo(int);
7455/// };
7456///
7457/// The governing language is C++03 [namespace.udecl]p12:
7458///
7459/// When a using-declaration brings names from a base class into a
7460/// derived class scope, member functions in the derived class
7461/// override and/or hide member functions with the same name and
7462/// parameter types in a base class (rather than conflicting).
7463///
7464/// There are two ways to implement this:
7465/// (1) optimistically create shadow decls when they're not hidden
7466/// by existing declarations, or
7467/// (2) don't create any shadow decls (or at least don't make them
7468/// visible) until we've fully parsed/instantiated the class.
7469/// The problem with (1) is that we might have to retroactively remove
7470/// a shadow decl, which requires several O(n) operations because the
7471/// decl structures are (very reasonably) not designed for removal.
7472/// (2) avoids this but is very fiddly and phase-dependent.
7473void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007474 if (Shadow->getDeclName().getNameKind() ==
7475 DeclarationName::CXXConversionFunctionName)
7476 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7477
John McCall84d87672009-12-10 09:41:52 +00007478 // Remove it from the DeclContext...
7479 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007480
John McCall84d87672009-12-10 09:41:52 +00007481 // ...and the scope, if applicable...
7482 if (S) {
John McCall48871652010-08-21 09:40:31 +00007483 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007484 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007485 }
7486
John McCall84d87672009-12-10 09:41:52 +00007487 // ...and the using decl.
7488 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7489
7490 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007491 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007492}
7493
Richard Smith09d5b3a2014-05-01 00:35:04 +00007494/// Find the base specifier for a base class with the given type.
7495static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7496 QualType DesiredBase,
7497 bool &AnyDependentBases) {
7498 // Check whether the named type is a direct base class.
7499 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7500 for (auto &Base : Derived->bases()) {
7501 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7502 if (CanonicalDesiredBase == BaseType)
7503 return &Base;
7504 if (BaseType->isDependentType())
7505 AnyDependentBases = true;
7506 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007507 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007508}
7509
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007510namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007511class UsingValidatorCCC : public CorrectionCandidateCallback {
7512public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007513 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007514 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007515 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007516 IsInstantiation(IsInstantiation), OldNNS(NNS),
7517 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007518
Craig Toppera798a9d2014-03-02 09:32:10 +00007519 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007520 NamedDecl *ND = Candidate.getCorrectionDecl();
7521
7522 // Keywords are not valid here.
7523 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007524 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007525
7526 // Completely unqualified names are invalid for a 'using' declaration.
7527 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7528 return false;
7529
Richard Smith09d5b3a2014-05-01 00:35:04 +00007530 if (RequireMemberOf) {
7531 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7532 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7533 // No-one ever wants a using-declaration to name an injected-class-name
7534 // of a base class, unless they're declaring an inheriting constructor.
7535 ASTContext &Ctx = ND->getASTContext();
7536 if (!Ctx.getLangOpts().CPlusPlus11)
7537 return false;
7538 QualType FoundType = Ctx.getRecordType(FoundRecord);
7539
7540 // Check that the injected-class-name is named as a member of its own
7541 // type; we don't want to suggest 'using Derived::Base;', since that
7542 // means something else.
7543 NestedNameSpecifier *Specifier =
7544 Candidate.WillReplaceSpecifier()
7545 ? Candidate.getCorrectionSpecifier()
7546 : OldNNS;
7547 if (!Specifier->getAsType() ||
7548 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7549 return false;
7550
7551 // Check that this inheriting constructor declaration actually names a
7552 // direct base class of the current class.
7553 bool AnyDependentBases = false;
7554 if (!findDirectBaseWithType(RequireMemberOf,
7555 Ctx.getRecordType(FoundRecord),
7556 AnyDependentBases) &&
7557 !AnyDependentBases)
7558 return false;
7559 } else {
7560 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7561 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7562 return false;
7563
7564 // FIXME: Check that the base class member is accessible?
7565 }
7566 }
7567
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007568 if (isa<TypeDecl>(ND))
7569 return HasTypenameKeyword || !IsInstantiation;
7570
7571 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007572 }
7573
7574private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007575 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007576 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007577 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007578 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007579};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007580} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007581
John McCalle61f2ba2009-11-18 02:36:19 +00007582/// Builds a using declaration.
7583///
7584/// \param IsInstantiation - Whether this call arises from an
7585/// instantiation of an unresolved using declaration. We treat
7586/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007587NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7588 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007589 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007590 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007591 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007592 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007593 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007594 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007595 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007596 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007597 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007598
Anders Carlssonf038fc22009-08-28 05:49:21 +00007599 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007600
Anders Carlsson59140b32009-08-28 03:16:11 +00007601 if (SS.isEmpty()) {
7602 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007603 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007604 }
Mike Stump11289f42009-09-09 15:08:12 +00007605
John McCall84d87672009-12-10 09:41:52 +00007606 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007607 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007608 ForRedeclaration);
7609 Previous.setHideTags(false);
7610 if (S) {
7611 LookupName(Previous, S);
7612
7613 // It is really dumb that we have to do this.
7614 LookupResult::Filter F = Previous.makeFilter();
7615 while (F.hasNext()) {
7616 NamedDecl *D = F.next();
7617 if (!isDeclInScope(D, CurContext, S))
7618 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007619 // If we found a local extern declaration that's not ordinarily visible,
7620 // and this declaration is being added to a non-block scope, ignore it.
7621 // We're only checking for scope conflicts here, not also for violations
7622 // of the linkage rules.
7623 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7624 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7625 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007626 }
7627 F.done();
7628 } else {
7629 assert(IsInstantiation && "no scope in non-instantiation");
7630 assert(CurContext->isRecord() && "scope not record in instantiation");
7631 LookupQualifiedName(Previous, CurContext);
7632 }
7633
John McCall84d87672009-12-10 09:41:52 +00007634 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007635 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7636 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007637 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007638
7639 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007640 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007641 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007642
John McCall84c16cf2009-11-12 03:15:40 +00007643 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007644 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007645 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007646 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007647 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007648 // FIXME: not all declaration name kinds are legal here
7649 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7650 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007651 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007652 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007653 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007654 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7655 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007656 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007657 D->setAccess(AS);
7658 CurContext->addDecl(D);
7659 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007660 }
John McCallb96ec562009-12-04 22:46:56 +00007661
Richard Smith09d5b3a2014-05-01 00:35:04 +00007662 auto Build = [&](bool Invalid) {
7663 UsingDecl *UD =
7664 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7665 HasTypenameKeyword);
7666 UD->setAccess(AS);
7667 CurContext->addDecl(UD);
7668 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007669 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007670 };
7671 auto BuildInvalid = [&]{ return Build(true); };
7672 auto BuildValid = [&]{ return Build(false); };
7673
7674 if (RequireCompleteDeclContext(SS, LookupContext))
7675 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007676
Richard Smith23d55872012-04-02 01:30:27 +00007677 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007678 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007679 UsingDecl *UD = BuildValid();
7680 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007681 return UD;
7682 }
7683
7684 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007685
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007686 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007687
John McCall3969e302009-12-08 07:46:18 +00007688 // Unlike most lookups, we don't always want to hide tag
7689 // declarations: tag names are visible through the using declaration
7690 // even if hidden by ordinary names, *except* in a dependent context
7691 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007692 if (!IsInstantiation)
7693 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007694
John McCall5dadb652012-04-07 03:04:20 +00007695 // For the purposes of this lookup, we have a base object type
7696 // equal to that of the current context.
7697 if (CurContext->isRecord()) {
7698 R.setBaseObjectType(
7699 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7700 }
7701
John McCall27b18f82009-11-17 02:14:36 +00007702 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007703
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007704 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007705 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007706 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007707 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007708 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007709 R.getLookupKind(), S, &SS, CCC,
7710 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007711 // We reject any correction for which ND would be NULL.
7712 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007713
Richard Smithf9b15102013-08-17 00:46:16 +00007714 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007715 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007716 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7717 << NameInfo.getName() << LookupContext << 0
7718 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007719
7720 // If we corrected to an inheriting constructor, handle it as one.
7721 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7722 if (RD && RD->isInjectedClassName()) {
7723 // Fix up the information we'll use to build the using declaration.
7724 if (Corrected.WillReplaceSpecifier()) {
7725 NestedNameSpecifierLocBuilder Builder;
7726 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7727 QualifierLoc.getSourceRange());
7728 QualifierLoc = Builder.getWithLocInContext(Context);
7729 }
7730
7731 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7732 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007733 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007734
7735 // Build it and process it as an inheriting constructor.
7736 UsingDecl *UD = BuildValid();
7737 CheckInheritingConstructorUsingDecl(UD);
7738 return UD;
7739 }
7740
7741 // FIXME: Pick up all the declarations if we found an overloaded function.
7742 R.setLookupName(Corrected.getCorrection());
7743 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007744 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007745 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007746 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007747 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007748 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007749 }
7750
Richard Smith09d5b3a2014-05-01 00:35:04 +00007751 if (R.isAmbiguous())
7752 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007753
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007754 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007755 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007756 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007757 Diag(IdentLoc, diag::err_using_typename_non_type);
7758 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7759 Diag((*I)->getUnderlyingDecl()->getLocation(),
7760 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007761 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007762 }
7763 } else {
7764 // If we asked for a non-typename and we got a type, error out,
7765 // but only if this is an instantiation of an unresolved using
7766 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007767 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007768 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7769 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007770 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007771 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007772 }
7773
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007774 // C++0x N2914 [namespace.udecl]p6:
7775 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007776 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007777 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7778 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007779 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007780 }
Mike Stump11289f42009-09-09 15:08:12 +00007781
Richard Smith09d5b3a2014-05-01 00:35:04 +00007782 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007783 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007784 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007785 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7786 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007787 }
John McCall3f746822009-11-17 05:59:44 +00007788
7789 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007790}
7791
Sebastian Redl08905022011-02-05 19:23:19 +00007792/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007793bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007794 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007795
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007796 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007797 assert(SourceType &&
7798 "Using decl naming constructor doesn't have type in scope spec.");
7799 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7800
7801 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007802 bool AnyDependentBases = false;
7803 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7804 AnyDependentBases);
7805 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007806 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007807 diag::err_using_decl_constructor_not_in_direct_base)
7808 << UD->getNameInfo().getSourceRange()
7809 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007810 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007811 return true;
7812 }
7813
Richard Smith09d5b3a2014-05-01 00:35:04 +00007814 if (Base)
7815 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007816
7817 return false;
7818}
7819
John McCall84d87672009-12-10 09:41:52 +00007820/// Checks that the given using declaration is not an invalid
7821/// redeclaration. Note that this is checking only for the using decl
7822/// itself, not for any ill-formedness among the UsingShadowDecls.
7823bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007824 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007825 const CXXScopeSpec &SS,
7826 SourceLocation NameLoc,
7827 const LookupResult &Prev) {
7828 // C++03 [namespace.udecl]p8:
7829 // C++0x [namespace.udecl]p10:
7830 // A using-declaration is a declaration and can therefore be used
7831 // repeatedly where (and only where) multiple declarations are
7832 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007833 //
John McCall032092f2010-11-29 18:01:58 +00007834 // That's in non-member contexts.
7835 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007836 return false;
7837
Aaron Ballman4a979672014-01-03 13:56:08 +00007838 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007839
7840 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7841 NamedDecl *D = *I;
7842
7843 bool DTypename;
7844 NestedNameSpecifier *DQual;
7845 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007846 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007847 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007848 } else if (UnresolvedUsingValueDecl *UD
7849 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7850 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007851 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007852 } else if (UnresolvedUsingTypenameDecl *UD
7853 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7854 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007855 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007856 } else continue;
7857
7858 // using decls differ if one says 'typename' and the other doesn't.
7859 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007860 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007861
7862 // using decls differ if they name different scopes (but note that
7863 // template instantiation can cause this check to trigger when it
7864 // didn't before instantiation).
7865 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7866 Context.getCanonicalNestedNameSpecifier(DQual))
7867 continue;
7868
7869 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007870 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007871 return true;
7872 }
7873
7874 return false;
7875}
7876
John McCall3969e302009-12-08 07:46:18 +00007877
John McCallb96ec562009-12-04 22:46:56 +00007878/// Checks that the given nested-name qualifier used in a using decl
7879/// in the current context is appropriately related to the current
7880/// scope. If an error is found, diagnoses it and returns true.
7881bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7882 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007883 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007884 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007885 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007886
John McCall3969e302009-12-08 07:46:18 +00007887 if (!CurContext->isRecord()) {
7888 // C++03 [namespace.udecl]p3:
7889 // C++0x [namespace.udecl]p8:
7890 // A using-declaration for a class member shall be a member-declaration.
7891
7892 // If we weren't able to compute a valid scope, it must be a
7893 // dependent class scope.
7894 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007895 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7896 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007897 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007898
John McCall3969e302009-12-08 07:46:18 +00007899 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7900 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007901
7902 // If we have a complete, non-dependent source type, try to suggest a
7903 // way to get the same effect.
7904 if (!RD)
7905 return true;
7906
7907 // Find what this using-declaration was referring to.
7908 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7909 R.setHideTags(false);
7910 R.suppressDiagnostics();
7911 LookupQualifiedName(R, RD);
7912
7913 if (R.getAsSingle<TypeDecl>()) {
7914 if (getLangOpts().CPlusPlus11) {
7915 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7916 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7917 << 0 // alias declaration
7918 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7919 NameInfo.getName().getAsString() +
7920 " = ");
7921 } else {
7922 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7923 SourceLocation InsertLoc =
7924 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7925 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7926 << 1 // typedef declaration
7927 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7928 << FixItHint::CreateInsertion(
7929 InsertLoc, " " + NameInfo.getName().getAsString());
7930 }
7931 } else if (R.getAsSingle<VarDecl>()) {
7932 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7933 // repeating the type of the static data member here.
7934 FixItHint FixIt;
7935 if (getLangOpts().CPlusPlus11) {
7936 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7937 FixIt = FixItHint::CreateReplacement(
7938 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7939 }
7940
7941 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7942 << 2 // reference declaration
7943 << FixIt;
7944 }
John McCall3969e302009-12-08 07:46:18 +00007945 return true;
7946 }
7947
7948 // Otherwise, everything is known to be fine.
7949 return false;
7950 }
7951
7952 // The current scope is a record.
7953
7954 // If the named context is dependent, we can't decide much.
7955 if (!NamedContext) {
7956 // FIXME: in C++0x, we can diagnose if we can prove that the
7957 // nested-name-specifier does not refer to a base class, which is
7958 // still possible in some cases.
7959
7960 // Otherwise we have to conservatively report that things might be
7961 // okay.
7962 return false;
7963 }
7964
7965 if (!NamedContext->isRecord()) {
7966 // Ideally this would point at the last name in the specifier,
7967 // but we don't have that level of source info.
7968 Diag(SS.getRange().getBegin(),
7969 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007970 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007971 return true;
7972 }
7973
Douglas Gregor7c842292010-12-21 07:41:49 +00007974 if (!NamedContext->isDependentContext() &&
7975 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7976 return true;
7977
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007978 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007979 // C++0x [namespace.udecl]p3:
7980 // In a using-declaration used as a member-declaration, the
7981 // nested-name-specifier shall name a base class of the class
7982 // being defined.
7983
7984 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7985 cast<CXXRecordDecl>(NamedContext))) {
7986 if (CurContext == NamedContext) {
7987 Diag(NameLoc,
7988 diag::err_using_decl_nested_name_specifier_is_current_class)
7989 << SS.getRange();
7990 return true;
7991 }
7992
7993 Diag(SS.getRange().getBegin(),
7994 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007995 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007996 << cast<CXXRecordDecl>(CurContext)
7997 << SS.getRange();
7998 return true;
7999 }
8000
8001 return false;
8002 }
8003
8004 // C++03 [namespace.udecl]p4:
8005 // A using-declaration used as a member-declaration shall refer
8006 // to a member of a base class of the class being defined [etc.].
8007
8008 // Salient point: SS doesn't have to name a base class as long as
8009 // lookup only finds members from base classes. Therefore we can
8010 // diagnose here only if we can prove that that can't happen,
8011 // i.e. if the class hierarchies provably don't intersect.
8012
8013 // TODO: it would be nice if "definitely valid" results were cached
8014 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8015 // need to be repeated.
8016
8017 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008018 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008019
8020 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8021 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8022 Data->Bases.insert(Base);
8023 return true;
8024 }
8025
8026 bool hasDependentBases(const CXXRecordDecl *Class) {
8027 return !Class->forallBases(collect, this);
8028 }
8029
8030 /// Returns true if the base is dependent or is one of the
8031 /// accumulated base classes.
8032 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8033 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8034 return !Data->Bases.count(Base);
8035 }
8036
8037 bool mightShareBases(const CXXRecordDecl *Class) {
8038 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8039 }
8040 };
8041
8042 UserData Data;
8043
8044 // Returns false if we find a dependent base.
8045 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8046 return false;
8047
8048 // Returns false if the class has a dependent base or if it or one
8049 // of its bases is present in the base set of the current context.
8050 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8051 return false;
8052
8053 Diag(SS.getRange().getBegin(),
8054 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008055 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008056 << cast<CXXRecordDecl>(CurContext)
8057 << SS.getRange();
8058
8059 return true;
John McCallb96ec562009-12-04 22:46:56 +00008060}
8061
Richard Smithdda56e42011-04-15 14:24:37 +00008062Decl *Sema::ActOnAliasDeclaration(Scope *S,
8063 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008064 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008065 SourceLocation UsingLoc,
8066 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008067 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008068 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008069 // Skip up to the relevant declaration scope.
8070 while (S->getFlags() & Scope::TemplateParamScope)
8071 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008072 assert((S->getFlags() & Scope::DeclScope) &&
8073 "got alias-declaration outside of declaration scope");
8074
8075 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008076 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008077
8078 bool Invalid = false;
8079 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008080 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008081 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008082
8083 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008084 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008085
8086 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008087 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008088 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008089 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8090 TInfo->getTypeLoc().getBeginLoc());
8091 }
Richard Smithdda56e42011-04-15 14:24:37 +00008092
8093 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8094 LookupName(Previous, S);
8095
8096 // Warn about shadowing the name of a template parameter.
8097 if (Previous.isSingleResult() &&
8098 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008099 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008100 Previous.clear();
8101 }
8102
8103 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8104 "name in alias declaration must be an identifier");
8105 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8106 Name.StartLocation,
8107 Name.Identifier, TInfo);
8108
8109 NewTD->setAccess(AS);
8110
8111 if (Invalid)
8112 NewTD->setInvalidDecl();
8113
Richard Smith54ecd982013-02-20 19:22:51 +00008114 ProcessDeclAttributeList(S, NewTD, AttrList);
8115
Richard Smith3f1b5d02011-05-05 21:57:07 +00008116 CheckTypedefForVariablyModifiedType(S, NewTD);
8117 Invalid |= NewTD->isInvalidDecl();
8118
Richard Smithdda56e42011-04-15 14:24:37 +00008119 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008120
8121 NamedDecl *NewND;
8122 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008123 TypeAliasTemplateDecl *OldDecl = nullptr;
8124 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008125
8126 if (TemplateParamLists.size() != 1) {
8127 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008128 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8129 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008130 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008131 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008132
8133 // Only consider previous declarations in the same scope.
8134 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8135 /*ExplicitInstantiationOrSpecialization*/false);
8136 if (!Previous.empty()) {
8137 Redeclaration = true;
8138
8139 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8140 if (!OldDecl && !Invalid) {
8141 Diag(UsingLoc, diag::err_redefinition_different_kind)
8142 << Name.Identifier;
8143
8144 NamedDecl *OldD = Previous.getRepresentativeDecl();
8145 if (OldD->getLocation().isValid())
8146 Diag(OldD->getLocation(), diag::note_previous_definition);
8147
8148 Invalid = true;
8149 }
8150
8151 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8152 if (TemplateParameterListsAreEqual(TemplateParams,
8153 OldDecl->getTemplateParameters(),
8154 /*Complain=*/true,
8155 TPL_TemplateMatch))
8156 OldTemplateParams = OldDecl->getTemplateParameters();
8157 else
8158 Invalid = true;
8159
8160 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8161 if (!Invalid &&
8162 !Context.hasSameType(OldTD->getUnderlyingType(),
8163 NewTD->getUnderlyingType())) {
8164 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8165 // but we can't reasonably accept it.
8166 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8167 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8168 if (OldTD->getLocation().isValid())
8169 Diag(OldTD->getLocation(), diag::note_previous_definition);
8170 Invalid = true;
8171 }
8172 }
8173 }
8174
8175 // Merge any previous default template arguments into our parameters,
8176 // and check the parameter list.
8177 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8178 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008179 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008180
8181 TypeAliasTemplateDecl *NewDecl =
8182 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8183 Name.Identifier, TemplateParams,
8184 NewTD);
8185
8186 NewDecl->setAccess(AS);
8187
8188 if (Invalid)
8189 NewDecl->setInvalidDecl();
8190 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008191 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008192
8193 NewND = NewDecl;
8194 } else {
8195 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8196 NewND = NewTD;
8197 }
Richard Smithdda56e42011-04-15 14:24:37 +00008198
8199 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008200 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008201
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008202 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008203 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008204}
8205
John McCall48871652010-08-21 09:40:31 +00008206Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008207 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008208 SourceLocation AliasLoc,
8209 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008210 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008211 SourceLocation IdentLoc,
8212 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008213
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008214 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008215 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8216 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008217
Anders Carlssondca83c42009-03-28 06:23:46 +00008218 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008219 NamedDecl *PrevDecl
8220 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8221 ForRedeclaration);
8222 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Craig Topperc3ec1492014-05-26 06:22:03 +00008223 PrevDecl = nullptr;
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008224
8225 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008226 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008227 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008228 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008229 // FIXME: At some point, we'll want to create the (redundant)
8230 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008231 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008232 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00008233 return nullptr;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008234 }
Mike Stump11289f42009-09-09 15:08:12 +00008235
Anders Carlssondca83c42009-03-28 06:23:46 +00008236 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8237 diag::err_redefinition_different_kind;
8238 Diag(AliasLoc, DiagID) << Alias;
8239 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00008240 return nullptr;
Anders Carlssondca83c42009-03-28 06:23:46 +00008241 }
8242
John McCall27b18f82009-11-17 02:14:36 +00008243 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008244 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008245
John McCall9f3059a2009-10-09 21:13:30 +00008246 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008247 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008248 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008249 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008250 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008251 }
Mike Stump11289f42009-09-09 15:08:12 +00008252
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008253 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008254 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008255 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008256 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008257
John McCalld8d0d432010-02-16 06:53:13 +00008258 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008259 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008260}
8261
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008262Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008263Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8264 CXXMethodDecl *MD) {
8265 CXXRecordDecl *ClassDecl = MD->getParent();
8266
Douglas Gregor6d880b12010-07-01 22:31:05 +00008267 // C++ [except.spec]p14:
8268 // An implicitly declared special member function (Clause 12) shall have an
8269 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008270 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008271 if (ClassDecl->isInvalidDecl())
8272 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008273
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008274 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008275 for (const auto &B : ClassDecl->bases()) {
8276 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008277 continue;
8278
Aaron Ballman574705e2014-03-13 15:41:46 +00008279 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008280 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008281 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8282 // If this is a deleted function, add it anyway. This might be conformant
8283 // with the standard. This might not. I'm not sure. It might not matter.
8284 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008285 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008286 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008287 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008288
8289 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008290 for (const auto &B : ClassDecl->vbases()) {
8291 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008292 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008293 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8294 // If this is a deleted function, add it anyway. This might be conformant
8295 // with the standard. This might not. I'm not sure. It might not matter.
8296 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008297 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008298 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008299 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008300
8301 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008302 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008303 if (F->hasInClassInitializer()) {
8304 if (Expr *E = F->getInClassInitializer())
8305 ExceptSpec.CalledExpr(E);
8306 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008307 // DR1351:
8308 // If the brace-or-equal-initializer of a non-static data member
8309 // invokes a defaulted default constructor of its class or of an
8310 // enclosing class in a potentially evaluated subexpression, the
8311 // program is ill-formed.
8312 //
8313 // This resolution is unworkable: the exception specification of the
8314 // default constructor can be needed in an unevaluated context, in
8315 // particular, in the operand of a noexcept-expression, and we can be
8316 // unable to compute an exception specification for an enclosed class.
8317 //
8318 // We do not allow an in-class initializer to require the evaluation
8319 // of the exception specification for any in-class initializer whose
8320 // definition is not lexically complete.
8321 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008322 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008323 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008324 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8325 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8326 // If this is a deleted function, add it anyway. This might be conformant
8327 // with the standard. This might not. I'm not sure. It might not matter.
8328 // In particular, the problem is that this function never gets called. It
8329 // might just be ill-formed because this function attempts to refer to
8330 // a deleted function here.
8331 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008332 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008333 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008334 }
John McCalldb40c7f2010-12-14 08:05:40 +00008335
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008336 return ExceptSpec;
8337}
8338
Richard Smithc2bc61b2013-03-18 21:12:30 +00008339Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008340Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8341 CXXRecordDecl *ClassDecl = CD->getParent();
8342
8343 // C++ [except.spec]p14:
8344 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008345 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008346 if (ClassDecl->isInvalidDecl())
8347 return ExceptSpec;
8348
8349 // Inherited constructor.
8350 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8351 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8352 // FIXME: Copying or moving the parameters could add extra exceptions to the
8353 // set, as could the default arguments for the inherited constructor. This
8354 // will be addressed when we implement the resolution of core issue 1351.
8355 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8356
8357 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008358 for (const auto &B : ClassDecl->bases()) {
8359 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008360 continue;
8361
Aaron Ballman574705e2014-03-13 15:41:46 +00008362 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008363 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8364 if (BaseClassDecl == InheritedDecl)
8365 continue;
8366 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8367 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008368 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008369 }
8370 }
8371
8372 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008373 for (const auto &B : ClassDecl->vbases()) {
8374 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008375 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8376 if (BaseClassDecl == InheritedDecl)
8377 continue;
8378 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8379 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008380 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008381 }
8382 }
8383
8384 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008385 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008386 if (F->hasInClassInitializer()) {
8387 if (Expr *E = F->getInClassInitializer())
8388 ExceptSpec.CalledExpr(E);
8389 else if (!F->isInvalidDecl())
8390 Diag(CD->getLocation(),
8391 diag::err_in_class_initializer_references_def_ctor) << CD;
8392 } else if (const RecordType *RecordTy
8393 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8394 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8395 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8396 if (Constructor)
8397 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8398 }
8399 }
8400
Richard Smithc2bc61b2013-03-18 21:12:30 +00008401 return ExceptSpec;
8402}
8403
Richard Smith8bf22e52012-11-29 01:34:07 +00008404namespace {
8405/// RAII object to register a special member as being currently declared.
8406struct DeclaringSpecialMember {
8407 Sema &S;
8408 Sema::SpecialMemberDecl D;
8409 bool WasAlreadyBeingDeclared;
8410
8411 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8412 : S(S), D(RD, CSM) {
8413 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8414 if (WasAlreadyBeingDeclared)
8415 // This almost never happens, but if it does, ensure that our cache
8416 // doesn't contain a stale result.
8417 S.SpecialMemberCache.clear();
8418
8419 // FIXME: Register a note to be produced if we encounter an error while
8420 // declaring the special member.
8421 }
8422 ~DeclaringSpecialMember() {
8423 if (!WasAlreadyBeingDeclared)
8424 S.SpecialMembersBeingDeclared.erase(D);
8425 }
8426
8427 /// \brief Are we already trying to declare this special member?
8428 bool isAlreadyBeingDeclared() const {
8429 return WasAlreadyBeingDeclared;
8430 }
8431};
8432}
8433
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008434CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8435 CXXRecordDecl *ClassDecl) {
8436 // C++ [class.ctor]p5:
8437 // A default constructor for a class X is a constructor of class X
8438 // that can be called without an argument. If there is no
8439 // user-declared constructor for class X, a default constructor is
8440 // implicitly declared. An implicitly-declared default constructor
8441 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008442 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008443 "Should not build implicit default constructor!");
8444
Richard Smith8bf22e52012-11-29 01:34:07 +00008445 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8446 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008447 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008448
Richard Smithb5800092012-06-10 05:43:50 +00008449 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8450 CXXDefaultConstructor,
8451 false);
8452
Douglas Gregor6d880b12010-07-01 22:31:05 +00008453 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008454 CanQualType ClassType
8455 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008456 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008457 DeclarationName Name
8458 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008459 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008460 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008461 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8462 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8463 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008464 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008465 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008466 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008467
8468 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008469 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008470 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008471
Richard Smith6b02d462012-12-08 08:32:28 +00008472 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8473 // constructors is easy to compute.
8474 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8475
8476 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008477 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008478
Douglas Gregor9672f922010-07-03 00:47:00 +00008479 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008480 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008481
Douglas Gregor0be31a22010-07-02 17:43:08 +00008482 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008483 PushOnScopeChains(DefaultCon, S, false);
8484 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008485
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008486 return DefaultCon;
8487}
8488
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008489void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8490 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008491 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008492 !Constructor->doesThisDeclarationHaveABody() &&
8493 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008494 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008495
Anders Carlsson423f5d82010-04-23 16:04:08 +00008496 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008497 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008498
Eli Friedmaneaf34142012-10-18 20:14:08 +00008499 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008500 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008501 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008502 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008503 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008504 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008505 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008506 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008507 }
Douglas Gregor73193272010-09-20 16:48:21 +00008508
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008509 SourceLocation Loc = Constructor->getLocEnd().isValid()
8510 ? Constructor->getLocEnd()
8511 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008512 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008513
Eli Friedman276dd182013-09-05 00:02:25 +00008514 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008515 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008516
8517 if (ASTMutationListener *L = getASTMutationListener()) {
8518 L->CompletedImplicitDefinition(Constructor);
8519 }
Richard Trieuef64e942013-10-25 00:56:00 +00008520
8521 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008522}
8523
Richard Smith938f40b2011-06-11 17:19:42 +00008524void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008525 // Perform any delayed checks on exception specifications.
8526 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008527}
8528
Richard Smith185be182013-04-10 05:48:59 +00008529namespace {
8530/// Information on inheriting constructors to declare.
8531class InheritingConstructorInfo {
8532public:
8533 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8534 : SemaRef(SemaRef), Derived(Derived) {
8535 // Mark the constructors that we already have in the derived class.
8536 //
8537 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8538 // unless there is a user-declared constructor with the same signature in
8539 // the class where the using-declaration appears.
8540 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8541 }
8542
8543 void inheritAll(CXXRecordDecl *RD) {
8544 visitAll(RD, &InheritingConstructorInfo::inherit);
8545 }
8546
8547private:
8548 /// Information about an inheriting constructor.
8549 struct InheritingConstructor {
8550 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008551 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008552
8553 /// If \c true, a constructor with this signature is already declared
8554 /// in the derived class.
8555 bool DeclaredInDerived;
8556
8557 /// The constructor which is inherited.
8558 const CXXConstructorDecl *BaseCtor;
8559
8560 /// The derived constructor we declared.
8561 CXXConstructorDecl *DerivedCtor;
8562 };
8563
8564 /// Inheriting constructors with a given canonical type. There can be at
8565 /// most one such non-template constructor, and any number of templated
8566 /// constructors.
8567 struct InheritingConstructorsForType {
8568 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008569 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8570 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008571
8572 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8573 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8574 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8575 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8576 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8577 false, S.TPL_TemplateMatch))
8578 return Templates[I].second;
8579 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8580 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008581 }
Richard Smith185be182013-04-10 05:48:59 +00008582
8583 return NonTemplate;
8584 }
8585 };
8586
8587 /// Get or create the inheriting constructor record for a constructor.
8588 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8589 QualType CtorType) {
8590 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8591 .getEntry(SemaRef, Ctor);
8592 }
8593
8594 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8595
8596 /// Process all constructors for a class.
8597 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008598 for (const auto *Ctor : RD->ctors())
8599 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008600 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8601 I(RD->decls_begin()), E(RD->decls_end());
8602 I != E; ++I) {
8603 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8604 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8605 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008606 }
8607 }
Richard Smith185be182013-04-10 05:48:59 +00008608
8609 /// Note that a constructor (or constructor template) was declared in Derived.
8610 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8611 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8612 }
8613
8614 /// Inherit a single constructor.
8615 void inherit(const CXXConstructorDecl *Ctor) {
8616 const FunctionProtoType *CtorType =
8617 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008618 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008619 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8620
8621 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8622
8623 // Core issue (no number yet): the ellipsis is always discarded.
8624 if (EPI.Variadic) {
8625 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8626 SemaRef.Diag(Ctor->getLocation(),
8627 diag::note_using_decl_constructor_ellipsis);
8628 EPI.Variadic = false;
8629 }
8630
8631 // Declare a constructor for each number of parameters.
8632 //
8633 // C++11 [class.inhctor]p1:
8634 // The candidate set of inherited constructors from the class X named in
8635 // the using-declaration consists of [... modulo defects ...] for each
8636 // constructor or constructor template of X, the set of constructors or
8637 // constructor templates that results from omitting any ellipsis parameter
8638 // specification and successively omitting parameters with a default
8639 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008640 unsigned MinParams = minParamsToInherit(Ctor);
8641 unsigned Params = Ctor->getNumParams();
8642 if (Params >= MinParams) {
8643 do
8644 declareCtor(UsingLoc, Ctor,
8645 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008646 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008647 while (Params > MinParams &&
8648 Ctor->getParamDecl(--Params)->hasDefaultArg());
8649 }
Richard Smith185be182013-04-10 05:48:59 +00008650 }
8651
8652 /// Find the using-declaration which specified that we should inherit the
8653 /// constructors of \p Base.
8654 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8655 // No fancy lookup required; just look for the base constructor name
8656 // directly within the derived class.
8657 ASTContext &Context = SemaRef.Context;
8658 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8659 Context.getCanonicalType(Context.getRecordType(Base)));
8660 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8661 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8662 }
8663
8664 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8665 // C++11 [class.inhctor]p3:
8666 // [F]or each constructor template in the candidate set of inherited
8667 // constructors, a constructor template is implicitly declared
8668 if (Ctor->getDescribedFunctionTemplate())
8669 return 0;
8670
8671 // For each non-template constructor in the candidate set of inherited
8672 // constructors other than a constructor having no parameters or a
8673 // copy/move constructor having a single parameter, a constructor is
8674 // implicitly declared [...]
8675 if (Ctor->getNumParams() == 0)
8676 return 1;
8677 if (Ctor->isCopyOrMoveConstructor())
8678 return 2;
8679
8680 // Per discussion on core reflector, never inherit a constructor which
8681 // would become a default, copy, or move constructor of Derived either.
8682 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8683 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8684 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8685 }
8686
8687 /// Declare a single inheriting constructor, inheriting the specified
8688 /// constructor, with the given type.
8689 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8690 QualType DerivedType) {
8691 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8692
8693 // C++11 [class.inhctor]p3:
8694 // ... a constructor is implicitly declared with the same constructor
8695 // characteristics unless there is a user-declared constructor with
8696 // the same signature in the class where the using-declaration appears
8697 if (Entry.DeclaredInDerived)
8698 return;
8699
8700 // C++11 [class.inhctor]p7:
8701 // If two using-declarations declare inheriting constructors with the
8702 // same signature, the program is ill-formed
8703 if (Entry.DerivedCtor) {
8704 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8705 // Only diagnose this once per constructor.
8706 if (Entry.DerivedCtor->isInvalidDecl())
8707 return;
8708 Entry.DerivedCtor->setInvalidDecl();
8709
8710 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8711 SemaRef.Diag(BaseCtor->getLocation(),
8712 diag::note_using_decl_constructor_conflict_current_ctor);
8713 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8714 diag::note_using_decl_constructor_conflict_previous_ctor);
8715 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8716 diag::note_using_decl_constructor_conflict_previous_using);
8717 } else {
8718 // Core issue (no number): if the same inheriting constructor is
8719 // produced by multiple base class constructors from the same base
8720 // class, the inheriting constructor is defined as deleted.
8721 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8722 }
8723
8724 return;
8725 }
8726
8727 ASTContext &Context = SemaRef.Context;
8728 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8729 Context.getCanonicalType(Context.getRecordType(Derived)));
8730 DeclarationNameInfo NameInfo(Name, UsingLoc);
8731
Craig Topperc3ec1492014-05-26 06:22:03 +00008732 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008733 if (const FunctionTemplateDecl *FTD =
8734 BaseCtor->getDescribedFunctionTemplate()) {
8735 TemplateParams = FTD->getTemplateParameters();
8736 // We're reusing template parameters from a different DeclContext. This
8737 // is questionable at best, but works out because the template depth in
8738 // both places is guaranteed to be 0.
8739 // FIXME: Rebuild the template parameters in the new context, and
8740 // transform the function type to refer to them.
8741 }
8742
8743 // Build type source info pointing at the using-declaration. This is
8744 // required by template instantiation.
8745 TypeSourceInfo *TInfo =
8746 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8747 FunctionProtoTypeLoc ProtoLoc =
8748 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8749
8750 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8751 Context, Derived, UsingLoc, NameInfo, DerivedType,
8752 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8753 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8754
8755 // Build an unevaluated exception specification for this constructor.
8756 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8757 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00008758 EPI.ExceptionSpec.Type = EST_Unevaluated;
8759 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008760 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008761 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008762
8763 // Build the parameter declarations.
8764 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008765 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008766 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008767 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008768 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008769 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8770 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008771 PD->setScopeInfo(0, I);
8772 PD->setImplicit();
8773 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008774 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008775 }
8776
8777 // Set up the new constructor.
8778 DerivedCtor->setAccess(BaseCtor->getAccess());
8779 DerivedCtor->setParams(ParamDecls);
8780 DerivedCtor->setInheritedConstructor(BaseCtor);
8781 if (BaseCtor->isDeleted())
8782 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8783
8784 // If this is a constructor template, build the template declaration.
8785 if (TemplateParams) {
8786 FunctionTemplateDecl *DerivedTemplate =
8787 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8788 TemplateParams, DerivedCtor);
8789 DerivedTemplate->setAccess(BaseCtor->getAccess());
8790 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8791 Derived->addDecl(DerivedTemplate);
8792 } else {
8793 Derived->addDecl(DerivedCtor);
8794 }
8795
8796 Entry.BaseCtor = BaseCtor;
8797 Entry.DerivedCtor = DerivedCtor;
8798 }
8799
8800 Sema &SemaRef;
8801 CXXRecordDecl *Derived;
8802 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8803 MapType Map;
8804};
8805}
8806
8807void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8808 // Defer declaring the inheriting constructors until the class is
8809 // instantiated.
8810 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008811 return;
8812
Richard Smith185be182013-04-10 05:48:59 +00008813 // Find base classes from which we might inherit constructors.
8814 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008815 for (const auto &BaseIt : ClassDecl->bases())
8816 if (BaseIt.getInheritConstructors())
8817 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008818
Richard Smith185be182013-04-10 05:48:59 +00008819 // Go no further if we're not inheriting any constructors.
8820 if (InheritedBases.empty())
8821 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008822
Richard Smith185be182013-04-10 05:48:59 +00008823 // Declare the inherited constructors.
8824 InheritingConstructorInfo ICI(*this, ClassDecl);
8825 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8826 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008827}
8828
Richard Smithc2bc61b2013-03-18 21:12:30 +00008829void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8830 CXXConstructorDecl *Constructor) {
8831 CXXRecordDecl *ClassDecl = Constructor->getParent();
8832 assert(Constructor->getInheritedConstructor() &&
8833 !Constructor->doesThisDeclarationHaveABody() &&
8834 !Constructor->isDeleted());
8835
8836 SynthesizedFunctionScope Scope(*this, Constructor);
8837 DiagnosticErrorTrap Trap(Diags);
8838 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8839 Trap.hasErrorOccurred()) {
8840 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8841 << Context.getTagDeclType(ClassDecl);
8842 Constructor->setInvalidDecl();
8843 return;
8844 }
8845
8846 SourceLocation Loc = Constructor->getLocation();
8847 Constructor->setBody(new (Context) CompoundStmt(Loc));
8848
Eli Friedman276dd182013-09-05 00:02:25 +00008849 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008850 MarkVTableUsed(CurrentLocation, ClassDecl);
8851
8852 if (ASTMutationListener *L = getASTMutationListener()) {
8853 L->CompletedImplicitDefinition(Constructor);
8854 }
8855}
8856
8857
Alexis Huntf91729462011-05-12 22:46:25 +00008858Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008859Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8860 CXXRecordDecl *ClassDecl = MD->getParent();
8861
Douglas Gregorf1203042010-07-01 19:09:28 +00008862 // C++ [except.spec]p14:
8863 // An implicitly declared special member function (Clause 12) shall have
8864 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008865 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008866 if (ClassDecl->isInvalidDecl())
8867 return ExceptSpec;
8868
Douglas Gregorf1203042010-07-01 19:09:28 +00008869 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008870 for (const auto &B : ClassDecl->bases()) {
8871 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008872 continue;
8873
Aaron Ballman574705e2014-03-13 15:41:46 +00008874 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8875 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008876 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008877 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008878
Douglas Gregorf1203042010-07-01 19:09:28 +00008879 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008880 for (const auto &B : ClassDecl->vbases()) {
8881 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8882 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008883 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008884 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008885
Douglas Gregorf1203042010-07-01 19:09:28 +00008886 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008887 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008888 if (const RecordType *RecordTy
8889 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008890 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008891 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008892 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008893
Alexis Huntf91729462011-05-12 22:46:25 +00008894 return ExceptSpec;
8895}
8896
8897CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8898 // C++ [class.dtor]p2:
8899 // If a class has no user-declared destructor, a destructor is
8900 // declared implicitly. An implicitly-declared destructor is an
8901 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008902 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008903
Richard Smith8bf22e52012-11-29 01:34:07 +00008904 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8905 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008906 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008907
Douglas Gregor7454c562010-07-02 20:37:36 +00008908 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008909 CanQualType ClassType
8910 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008911 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008912 DeclarationName Name
8913 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008914 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008915 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008916 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008917 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008918 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008919 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008920 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008921 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008922
8923 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008924 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008925 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008926
Richard Smith6b02d462012-12-08 08:32:28 +00008927 AddOverriddenMethods(ClassDecl, Destructor);
8928
8929 // We don't need to use SpecialMemberIsTrivial here; triviality for
8930 // destructors is easy to compute.
8931 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8932
8933 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008934 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008935
Douglas Gregor7454c562010-07-02 20:37:36 +00008936 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008937 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008938
Douglas Gregor7454c562010-07-02 20:37:36 +00008939 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008940 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008941 PushOnScopeChains(Destructor, S, false);
8942 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008943
Douglas Gregorf1203042010-07-01 19:09:28 +00008944 return Destructor;
8945}
8946
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008947void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008948 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008949 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008950 !Destructor->doesThisDeclarationHaveABody() &&
8951 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008952 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008953 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008954 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008955
Douglas Gregor54818f02010-05-12 16:39:35 +00008956 if (Destructor->isInvalidDecl())
8957 return;
8958
Eli Friedmaneaf34142012-10-18 20:14:08 +00008959 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008960
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008961 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008962 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8963 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008964
Douglas Gregor54818f02010-05-12 16:39:35 +00008965 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008966 Diag(CurrentLocation, diag::note_member_synthesized_at)
8967 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8968
8969 Destructor->setInvalidDecl();
8970 return;
8971 }
8972
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008973 SourceLocation Loc = Destructor->getLocEnd().isValid()
8974 ? Destructor->getLocEnd()
8975 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008976 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008977 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008978 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008979
8980 if (ASTMutationListener *L = getASTMutationListener()) {
8981 L->CompletedImplicitDefinition(Destructor);
8982 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008983}
8984
Richard Smith84973e52012-04-21 18:42:51 +00008985/// \brief Perform any semantic analysis which needs to be delayed until all
8986/// pending class member declarations have been parsed.
8987void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008988 // If the context is an invalid C++ class, just suppress these checks.
8989 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8990 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008991 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008992 DelayedDestructorExceptionSpecChecks.clear();
8993 return;
8994 }
8995 }
Richard Smith84973e52012-04-21 18:42:51 +00008996}
8997
Richard Smithd3b5c9082012-07-27 04:22:15 +00008998void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8999 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009000 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009001 "adjusting dtor exception specs was introduced in c++11");
9002
Sebastian Redl623ea822011-05-19 05:13:44 +00009003 // C++11 [class.dtor]p3:
9004 // A declaration of a destructor that does not have an exception-
9005 // specification is implicitly considered to have the same exception-
9006 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009007 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009008 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009009 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009010 return;
9011
Chandler Carruth9a797572011-09-20 04:55:26 +00009012 // Replace the destructor's type, building off the existing one. Fortunately,
9013 // the only thing of interest in the destructor type is its extended info.
9014 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009015 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009016 EPI.ExceptionSpec.Type = EST_Unevaluated;
9017 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009018 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009019
Sebastian Redl623ea822011-05-19 05:13:44 +00009020 // FIXME: If the destructor has a body that could throw, and the newly created
9021 // spec doesn't allow exceptions, we should emit a warning, because this
9022 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009023 // However, we don't have a body or an exception specification yet, so it
9024 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009025}
9026
Pavel Labath58934982013-08-30 08:52:28 +00009027namespace {
9028/// \brief An abstract base class for all helper classes used in building the
9029// copy/move operators. These classes serve as factory functions and help us
9030// avoid using the same Expr* in the AST twice.
9031class ExprBuilder {
9032 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9033 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9034
9035protected:
9036 static Expr *assertNotNull(Expr *E) {
9037 assert(E && "Expression construction must not fail.");
9038 return E;
9039 }
9040
9041public:
9042 ExprBuilder() {}
9043 virtual ~ExprBuilder() {}
9044
9045 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9046};
9047
9048class RefBuilder: public ExprBuilder {
9049 VarDecl *Var;
9050 QualType VarType;
9051
9052public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009053 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009054 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009055 }
9056
9057 RefBuilder(VarDecl *Var, QualType VarType)
9058 : Var(Var), VarType(VarType) {}
9059};
9060
9061class ThisBuilder: public ExprBuilder {
9062public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009063 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009064 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009065 }
9066};
9067
9068class CastBuilder: public ExprBuilder {
9069 const ExprBuilder &Builder;
9070 QualType Type;
9071 ExprValueKind Kind;
9072 const CXXCastPath &Path;
9073
9074public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009075 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009076 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9077 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009078 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009079 }
9080
9081 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9082 const CXXCastPath &Path)
9083 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9084};
9085
9086class DerefBuilder: public ExprBuilder {
9087 const ExprBuilder &Builder;
9088
9089public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009090 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009091 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009092 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009093 }
9094
9095 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9096};
9097
9098class MemberBuilder: public ExprBuilder {
9099 const ExprBuilder &Builder;
9100 QualType Type;
9101 CXXScopeSpec SS;
9102 bool IsArrow;
9103 LookupResult &MemberLookup;
9104
9105public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009106 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009107 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009108 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009109 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009110 }
9111
9112 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9113 LookupResult &MemberLookup)
9114 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9115 MemberLookup(MemberLookup) {}
9116};
9117
9118class MoveCastBuilder: public ExprBuilder {
9119 const ExprBuilder &Builder;
9120
9121public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009122 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009123 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9124 }
9125
9126 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9127};
9128
9129class LvalueConvBuilder: public ExprBuilder {
9130 const ExprBuilder &Builder;
9131
9132public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009133 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009134 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009135 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009136 }
9137
9138 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9139};
9140
9141class SubscriptBuilder: public ExprBuilder {
9142 const ExprBuilder &Base;
9143 const ExprBuilder &Index;
9144
9145public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009146 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009147 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009148 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009149 }
9150
9151 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9152 : Base(Base), Index(Index) {}
9153};
9154
9155} // end anonymous namespace
9156
Richard Smith41ae3282012-11-14 00:50:40 +00009157/// When generating a defaulted copy or move assignment operator, if a field
9158/// should be copied with __builtin_memcpy rather than via explicit assignments,
9159/// do so. This optimization only applies for arrays of scalars, and for arrays
9160/// of class type where the selected copy/move-assignment operator is trivial.
9161static StmtResult
9162buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009163 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009164 // Compute the size of the memory buffer to be copied.
9165 QualType SizeType = S.Context.getSizeType();
9166 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9167 S.Context.getTypeSizeInChars(T).getQuantity());
9168
9169 // Take the address of the field references for "from" and "to". We
9170 // directly construct UnaryOperators here because semantic analysis
9171 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009172 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009173 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9174 S.Context.getPointerType(From->getType()),
9175 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009176 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009177 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9178 S.Context.getPointerType(To->getType()),
9179 VK_RValue, OK_Ordinary, Loc);
9180
9181 const Type *E = T->getBaseElementTypeUnsafe();
9182 bool NeedsCollectableMemCpy =
9183 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9184
9185 // Create a reference to the __builtin_objc_memmove_collectable function
9186 StringRef MemCpyName = NeedsCollectableMemCpy ?
9187 "__builtin_objc_memmove_collectable" :
9188 "__builtin_memcpy";
9189 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9190 Sema::LookupOrdinaryName);
9191 S.LookupName(R, S.TUScope, true);
9192
9193 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9194 if (!MemCpy)
9195 // Something went horribly wrong earlier, and we will have complained
9196 // about it.
9197 return StmtError();
9198
9199 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009200 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009201 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9202
9203 Expr *CallArgs[] = {
9204 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9205 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009206 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009207 Loc, CallArgs, Loc);
9208
9209 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009210 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009211}
9212
Sebastian Redl22653ba2011-08-30 19:58:05 +00009213/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009214/// \c To.
9215///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009216/// This routine is used to copy/move the members of a class with an
9217/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009218/// copied are arrays, this routine builds for loops to copy them.
9219///
9220/// \param S The Sema object used for type-checking.
9221///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009222/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009223///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009224/// \param T The type of the expressions being copied/moved. Both expressions
9225/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009226///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009227/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009228///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009229/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009230///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009231/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009232/// Otherwise, it's a non-static member subobject.
9233///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009234/// \param Copying Whether we're copying or moving.
9235///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009236/// \param Depth Internal parameter recording the depth of the recursion.
9237///
Richard Smith41ae3282012-11-14 00:50:40 +00009238/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9239/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009240static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009241buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009242 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009243 bool CopyingBaseSubobject, bool Copying,
9244 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009245 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009246 // Each subobject is assigned in the manner appropriate to its type:
9247 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009248 // - if the subobject is of class type, as if by a call to operator= with
9249 // the subobject as the object expression and the corresponding
9250 // subobject of x as a single function argument (as if by explicit
9251 // qualification; that is, ignoring any possible virtual overriding
9252 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009253 //
9254 // C++03 [class.copy]p13:
9255 // - if the subobject is of class type, the copy assignment operator for
9256 // the class is used (as if by explicit qualification; that is,
9257 // ignoring any possible virtual overriding functions in more derived
9258 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009259 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9260 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009261
Douglas Gregorb139cd52010-05-01 20:49:11 +00009262 // Look for operator=.
9263 DeclarationName Name
9264 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9265 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9266 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009267
Richard Smith52c0b582012-11-13 00:54:12 +00009268 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9269 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009270 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009271 LookupResult::Filter F = OpLookup.makeFilter();
9272 while (F.hasNext()) {
9273 NamedDecl *D = F.next();
9274 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9275 if (Method->isCopyAssignmentOperator() ||
9276 (!Copying && Method->isMoveAssignmentOperator()))
9277 continue;
9278
9279 F.erase();
9280 }
9281 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009282 }
Richard Smith52c0b582012-11-13 00:54:12 +00009283
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009284 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009285 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009286 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009287 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009288 // ambiguities), we need to cast "this" to that subobject type; to
9289 // ensure that we don't go through the virtual call mechanism, we need
9290 // to qualify the operator= name with the base class (see below). However,
9291 // this means that if the base class has a protected copy assignment
9292 // operator, the protected member access check will fail. So, we
9293 // rewrite "protected" access to "public" access in this case, since we
9294 // know by construction that we're calling from a derived class.
9295 if (CopyingBaseSubobject) {
9296 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9297 L != LEnd; ++L) {
9298 if (L.getAccess() == AS_protected)
9299 L.setAccess(AS_public);
9300 }
9301 }
Richard Smith52c0b582012-11-13 00:54:12 +00009302
Douglas Gregorb139cd52010-05-01 20:49:11 +00009303 // Create the nested-name-specifier that will be used to qualify the
9304 // reference to operator=; this is required to suppress the virtual
9305 // call mechanism.
9306 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009307 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009308 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009309 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009310 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009311 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009312
Douglas Gregorb139cd52010-05-01 20:49:11 +00009313 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009314 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009315 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9316 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009317 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009318 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009319 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009320 /*SuppressQualifierCheck=*/true);
9321 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009322 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009323
Douglas Gregorb139cd52010-05-01 20:49:11 +00009324 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009325
Pavel Labath58934982013-08-30 08:52:28 +00009326 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009327 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009328 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009329 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009330 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009331 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009332
Richard Smith41ae3282012-11-14 00:50:40 +00009333 // If we built a call to a trivial 'operator=' while copying an array,
9334 // bail out. We'll replace the whole shebang with a memcpy.
9335 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9336 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009337 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009338
Richard Smith52c0b582012-11-13 00:54:12 +00009339 // Convert to an expression-statement, and clean up any produced
9340 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009341 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009342 }
John McCallab8c2732010-03-16 06:11:48 +00009343
Richard Smith52c0b582012-11-13 00:54:12 +00009344 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009345 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009346 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009347 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009348 ExprResult Assignment = S.CreateBuiltinBinOp(
9349 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009350 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009351 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009352 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009353 }
Richard Smith52c0b582012-11-13 00:54:12 +00009354
9355 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009356 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009357
Douglas Gregorb139cd52010-05-01 20:49:11 +00009358 // Construct a loop over the array bounds, e.g.,
9359 //
9360 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9361 //
9362 // that will copy each of the array elements.
9363 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009364
Douglas Gregorb139cd52010-05-01 20:49:11 +00009365 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009366 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009367 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009368 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009369 llvm::raw_svector_ostream OS(Str);
9370 OS << "__i" << Depth;
9371 IterationVarName = &S.Context.Idents.get(OS.str());
9372 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009373 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009374 IterationVarName, SizeType,
9375 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009376 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009377
Douglas Gregorb139cd52010-05-01 20:49:11 +00009378 // Initialize the iteration variable to zero.
9379 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009380 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009381
Pavel Labath58934982013-08-30 08:52:28 +00009382 // Creates a reference to the iteration variable.
9383 RefBuilder IterationVarRef(IterationVar, SizeType);
9384 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009385
Douglas Gregorb139cd52010-05-01 20:49:11 +00009386 // Create the DeclStmt that holds the iteration variable.
9387 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009388
Douglas Gregorb139cd52010-05-01 20:49:11 +00009389 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009390 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9391 MoveCastBuilder FromIndexMove(FromIndexCopy);
9392 const ExprBuilder *FromIndex;
9393 if (Copying)
9394 FromIndex = &FromIndexCopy;
9395 else
9396 FromIndex = &FromIndexMove;
9397
9398 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009399
9400 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009401 StmtResult Copy =
9402 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009403 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009404 Copying, Depth + 1);
9405 // Bail out if copying fails or if we determined that we should use memcpy.
9406 if (Copy.isInvalid() || !Copy.get())
9407 return Copy;
9408
9409 // Create the comparison against the array bound.
9410 llvm::APInt Upper
9411 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9412 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009413 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009414 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9415 BO_NE, S.Context.BoolTy,
9416 VK_RValue, OK_Ordinary, Loc, false);
9417
9418 // Create the pre-increment of the iteration variable.
9419 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009420 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9421 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009422
Douglas Gregorb139cd52010-05-01 20:49:11 +00009423 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009424 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009425 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009426 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009427 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009428}
9429
Richard Smith41ae3282012-11-14 00:50:40 +00009430static StmtResult
9431buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009432 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009433 bool CopyingBaseSubobject, bool Copying) {
9434 // Maybe we should use a memcpy?
9435 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9436 T.isTriviallyCopyableType(S.Context))
9437 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9438
9439 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9440 CopyingBaseSubobject,
9441 Copying, 0));
9442
9443 // If we ended up picking a trivial assignment operator for an array of a
9444 // non-trivially-copyable class type, just emit a memcpy.
9445 if (!Result.isInvalid() && !Result.get())
9446 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9447
9448 return Result;
9449}
9450
Richard Smithd3b5c9082012-07-27 04:22:15 +00009451Sema::ImplicitExceptionSpecification
9452Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9453 CXXRecordDecl *ClassDecl = MD->getParent();
9454
9455 ImplicitExceptionSpecification ExceptSpec(*this);
9456 if (ClassDecl->isInvalidDecl())
9457 return ExceptSpec;
9458
9459 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009460 assert(T->getNumParams() == 1 && "not a copy assignment op");
9461 unsigned ArgQuals =
9462 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009463
Douglas Gregor68e11362010-07-01 17:48:08 +00009464 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009465 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009466 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009467
9468 // It is unspecified whether or not an implicit copy assignment operator
9469 // attempts to deduplicate calls to assignment operators of virtual bases are
9470 // made. As such, this exception specification is effectively unspecified.
9471 // Based on a similar decision made for constness in C++0x, we're erring on
9472 // the side of assuming such calls to be made regardless of whether they
9473 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009474 for (const auto &Base : ClassDecl->bases()) {
9475 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009476 continue;
9477
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009478 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009479 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009480 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9481 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009482 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009483 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009484
Aaron Ballman445a9392014-03-13 16:15:17 +00009485 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009486 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009487 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009488 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9489 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009490 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009491 }
9492
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009493 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009494 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009495 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9496 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009497 LookupCopyingAssignment(FieldClassDecl,
9498 ArgQuals | FieldType.getCVRQualifiers(),
9499 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009500 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009501 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009502 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009503
Richard Smithd3b5c9082012-07-27 04:22:15 +00009504 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009505}
9506
9507CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9508 // Note: The following rules are largely analoguous to the copy
9509 // constructor rules. Note that virtual bases are not taken into account
9510 // for determining the argument type of the operator. Note also that
9511 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009512 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009513
Richard Smith8bf22e52012-11-29 01:34:07 +00009514 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9515 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009516 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009517
Alexis Hunt119f3652011-05-14 05:23:20 +00009518 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9519 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009520 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9521 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009522 ArgType = ArgType.withConst();
9523 ArgType = Context.getLValueReferenceType(ArgType);
9524
Richard Smith99005e62013-05-07 03:19:20 +00009525 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9526 CXXCopyAssignment,
9527 Const);
9528
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009529 // An implicitly-declared copy assignment operator is an inline public
9530 // member of its class.
9531 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009532 SourceLocation ClassLoc = ClassDecl->getLocation();
9533 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009534 CXXMethodDecl *CopyAssignment =
9535 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009536 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9537 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009538 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009539 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009540 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009541
9542 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009543 FunctionProtoType::ExtProtoInfo EPI =
9544 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009545 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009546
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009547 // Add the parameter to the operator.
9548 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009549 ClassLoc, ClassLoc,
9550 /*Id=*/nullptr, ArgType,
9551 /*TInfo=*/nullptr, SC_None,
9552 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009553 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009554
Richard Smith6b02d462012-12-08 08:32:28 +00009555 AddOverriddenMethods(ClassDecl, CopyAssignment);
9556
9557 CopyAssignment->setTrivial(
9558 ClassDecl->needsOverloadResolutionForCopyAssignment()
9559 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9560 : ClassDecl->hasTrivialCopyAssignment());
9561
Richard Smith852265f2012-03-30 20:53:28 +00009562 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009563 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009564
Richard Smith6b02d462012-12-08 08:32:28 +00009565 // Note that we have added this copy-assignment operator.
9566 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9567
9568 if (Scope *S = getScopeForContext(ClassDecl))
9569 PushOnScopeChains(CopyAssignment, S, false);
9570 ClassDecl->addDecl(CopyAssignment);
9571
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009572 return CopyAssignment;
9573}
9574
Richard Smithd577fbb2013-06-13 03:23:42 +00009575/// Diagnose an implicit copy operation for a class which is odr-used, but
9576/// which is deprecated because the class has a user-declared copy constructor,
9577/// copy assignment operator, or destructor.
9578static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9579 SourceLocation UseLoc) {
9580 assert(CopyOp->isImplicit());
9581
9582 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009583 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009584
9585 // In Microsoft mode, assignment operations don't affect constructors and
9586 // vice versa.
9587 if (RD->hasUserDeclaredDestructor()) {
9588 UserDeclaredOperation = RD->getDestructor();
9589 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9590 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009591 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009592 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009593 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009594 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009595 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009596 break;
9597 }
9598 }
9599 assert(UserDeclaredOperation);
9600 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9601 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009602 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009603 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009604 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009605 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009606 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009607 break;
9608 }
9609 }
9610 assert(UserDeclaredOperation);
9611 }
9612
9613 if (UserDeclaredOperation) {
9614 S.Diag(UserDeclaredOperation->getLocation(),
9615 diag::warn_deprecated_copy_operation)
9616 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9617 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9618 S.Diag(UseLoc, diag::note_member_synthesized_at)
9619 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9620 : Sema::CXXCopyAssignment)
9621 << RD;
9622 }
9623}
9624
Douglas Gregorb139cd52010-05-01 20:49:11 +00009625void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9626 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009627 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009628 CopyAssignOperator->isOverloadedOperator() &&
9629 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009630 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9631 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009632 "DefineImplicitCopyAssignment called for wrong function");
9633
9634 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9635
9636 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9637 CopyAssignOperator->setInvalidDecl();
9638 return;
9639 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009640
9641 // C++11 [class.copy]p18:
9642 // The [definition of an implicitly declared copy assignment operator] is
9643 // deprecated if the class has a user-declared copy constructor or a
9644 // user-declared destructor.
9645 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9646 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9647
Eli Friedman276dd182013-09-05 00:02:25 +00009648 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009649
Eli Friedmaneaf34142012-10-18 20:14:08 +00009650 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009651 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009652
9653 // C++0x [class.copy]p30:
9654 // The implicitly-defined or explicitly-defaulted copy assignment operator
9655 // for a non-union class X performs memberwise copy assignment of its
9656 // subobjects. The direct base classes of X are assigned first, in the
9657 // order of their declaration in the base-specifier-list, and then the
9658 // immediate non-static data members of X are assigned, in the order in
9659 // which they were declared in the class definition.
9660
9661 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009662 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009663
9664 // The parameter for the "other" object, which we are copying from.
9665 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9666 Qualifiers OtherQuals = Other->getType().getQualifiers();
9667 QualType OtherRefType = Other->getType();
9668 if (const LValueReferenceType *OtherRef
9669 = OtherRefType->getAs<LValueReferenceType>()) {
9670 OtherRefType = OtherRef->getPointeeType();
9671 OtherQuals = OtherRefType.getQualifiers();
9672 }
9673
9674 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009675 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9676 ? CopyAssignOperator->getLocEnd()
9677 : CopyAssignOperator->getLocation();
9678
Pavel Labath58934982013-08-30 08:52:28 +00009679 // Builds a DeclRefExpr for the "other" object.
9680 RefBuilder OtherRef(Other, OtherRefType);
9681
9682 // Builds the "this" pointer.
9683 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009684
9685 // Assign base classes.
9686 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009687 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009688 // Form the assignment:
9689 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009690 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009691 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009692 Invalid = true;
9693 continue;
9694 }
9695
John McCallcf142162010-08-07 06:22:56 +00009696 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009697 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009698
Douglas Gregorb139cd52010-05-01 20:49:11 +00009699 // Construct the "from" expression, which is an implicit cast to the
9700 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009701 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9702 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009703
9704 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009705 DerefBuilder DerefThis(This);
9706 CastBuilder To(DerefThis,
9707 Context.getCVRQualifiedType(
9708 BaseType, CopyAssignOperator->getTypeQualifiers()),
9709 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009710
9711 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009712 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009713 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009714 /*CopyingBaseSubobject=*/true,
9715 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009716 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009717 Diag(CurrentLocation, diag::note_member_synthesized_at)
9718 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9719 CopyAssignOperator->setInvalidDecl();
9720 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009721 }
9722
9723 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009724 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009725 }
9726
Douglas Gregorb139cd52010-05-01 20:49:11 +00009727 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009728 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009729 if (Field->isUnnamedBitfield())
9730 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009731
9732 if (Field->isInvalidDecl()) {
9733 Invalid = true;
9734 continue;
9735 }
9736
Douglas Gregorb139cd52010-05-01 20:49:11 +00009737 // Check for members of reference type; we can't copy those.
9738 if (Field->getType()->isReferenceType()) {
9739 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9740 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9741 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009742 Diag(CurrentLocation, diag::note_member_synthesized_at)
9743 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009744 Invalid = true;
9745 continue;
9746 }
9747
9748 // Check for members of const-qualified, non-class type.
9749 QualType BaseType = Context.getBaseElementType(Field->getType());
9750 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9751 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9752 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9753 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009754 Diag(CurrentLocation, diag::note_member_synthesized_at)
9755 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009756 Invalid = true;
9757 continue;
9758 }
John McCall1b1a1db2011-06-17 00:18:42 +00009759
9760 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009761 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9762 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009763
9764 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009765 if (FieldType->isIncompleteArrayType()) {
9766 assert(ClassDecl->hasFlexibleArrayMember() &&
9767 "Incomplete array type is not valid");
9768 continue;
9769 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009770
9771 // Build references to the field in the object we're copying from and to.
9772 CXXScopeSpec SS; // Intentionally empty
9773 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9774 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009775 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009776 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009777
9778 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9779
9780 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009781
Douglas Gregorb139cd52010-05-01 20:49:11 +00009782 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009783 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009784 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009785 /*CopyingBaseSubobject=*/false,
9786 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009787 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009788 Diag(CurrentLocation, diag::note_member_synthesized_at)
9789 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9790 CopyAssignOperator->setInvalidDecl();
9791 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009792 }
9793
9794 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009795 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009796 }
9797
9798 if (!Invalid) {
9799 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009800 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009801
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009802 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009803 if (Return.isInvalid())
9804 Invalid = true;
9805 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009806 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009807
9808 if (Trap.hasErrorOccurred()) {
9809 Diag(CurrentLocation, diag::note_member_synthesized_at)
9810 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9811 Invalid = true;
9812 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009813 }
9814 }
9815
9816 if (Invalid) {
9817 CopyAssignOperator->setInvalidDecl();
9818 return;
9819 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009820
9821 StmtResult Body;
9822 {
9823 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009824 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009825 /*isStmtExpr=*/false);
9826 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9827 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009828 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009829
9830 if (ASTMutationListener *L = getASTMutationListener()) {
9831 L->CompletedImplicitDefinition(CopyAssignOperator);
9832 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009833}
9834
Sebastian Redl22653ba2011-08-30 19:58:05 +00009835Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009836Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9837 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009838
Richard Smithd3b5c9082012-07-27 04:22:15 +00009839 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009840 if (ClassDecl->isInvalidDecl())
9841 return ExceptSpec;
9842
9843 // C++0x [except.spec]p14:
9844 // An implicitly declared special member function (Clause 12) shall have an
9845 // exception-specification. [...]
9846
9847 // It is unspecified whether or not an implicit move assignment operator
9848 // attempts to deduplicate calls to assignment operators of virtual bases are
9849 // made. As such, this exception specification is effectively unspecified.
9850 // Based on a similar decision made for constness in C++0x, we're erring on
9851 // the side of assuming such calls to be made regardless of whether they
9852 // actually happen.
9853 // Note that a move constructor is not implicitly declared when there are
9854 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009855 for (const auto &Base : ClassDecl->bases()) {
9856 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009857 continue;
9858
9859 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009860 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009861 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009862 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009863 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009864 }
9865
Aaron Ballman445a9392014-03-13 16:15:17 +00009866 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009867 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009868 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009869 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009870 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009871 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872 }
9873
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009874 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009875 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009876 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009877 if (CXXMethodDecl *MoveAssign =
9878 LookupMovingAssignment(FieldClassDecl,
9879 FieldType.getCVRQualifiers(),
9880 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009881 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009882 }
9883 }
9884
9885 return ExceptSpec;
9886}
9887
9888CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009889 assert(ClassDecl->needsImplicitMoveAssignment());
9890
Richard Smith8bf22e52012-11-29 01:34:07 +00009891 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9892 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009893 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009894
Sebastian Redl22653ba2011-08-30 19:58:05 +00009895 // Note: The following rules are largely analoguous to the move
9896 // constructor rules.
9897
Sebastian Redl22653ba2011-08-30 19:58:05 +00009898 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9899 QualType RetType = Context.getLValueReferenceType(ArgType);
9900 ArgType = Context.getRValueReferenceType(ArgType);
9901
Richard Smith99005e62013-05-07 03:19:20 +00009902 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9903 CXXMoveAssignment,
9904 false);
9905
Sebastian Redl22653ba2011-08-30 19:58:05 +00009906 // An implicitly-declared move assignment operator is an inline public
9907 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009908 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9909 SourceLocation ClassLoc = ClassDecl->getLocation();
9910 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009911 CXXMethodDecl *MoveAssignment =
9912 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009913 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009914 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009915 MoveAssignment->setAccess(AS_public);
9916 MoveAssignment->setDefaulted();
9917 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009918
Richard Smithd3b5c9082012-07-27 04:22:15 +00009919 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009920 FunctionProtoType::ExtProtoInfo EPI =
9921 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009922 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009923
Sebastian Redl22653ba2011-08-30 19:58:05 +00009924 // Add the parameter to the operator.
9925 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009926 ClassLoc, ClassLoc,
9927 /*Id=*/nullptr, ArgType,
9928 /*TInfo=*/nullptr, SC_None,
9929 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009930 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009931
Richard Smith6b02d462012-12-08 08:32:28 +00009932 AddOverriddenMethods(ClassDecl, MoveAssignment);
9933
9934 MoveAssignment->setTrivial(
9935 ClassDecl->needsOverloadResolutionForMoveAssignment()
9936 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9937 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009938
Richard Smithd951a1d2012-02-18 02:02:13 +00009939 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009940 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9941 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009942 }
9943
Richard Smith6b02d462012-12-08 08:32:28 +00009944 // Note that we have added this copy-assignment operator.
9945 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9946
Sebastian Redl22653ba2011-08-30 19:58:05 +00009947 if (Scope *S = getScopeForContext(ClassDecl))
9948 PushOnScopeChains(MoveAssignment, S, false);
9949 ClassDecl->addDecl(MoveAssignment);
9950
Sebastian Redl22653ba2011-08-30 19:58:05 +00009951 return MoveAssignment;
9952}
9953
Richard Smithb2504bd2013-11-04 04:26:14 +00009954/// Check if we're implicitly defining a move assignment operator for a class
9955/// with virtual bases. Such a move assignment might move-assign the virtual
9956/// base multiple times.
9957static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9958 SourceLocation CurrentLocation) {
9959 assert(!Class->isDependentContext() && "should not define dependent move");
9960
9961 // Only a virtual base could get implicitly move-assigned multiple times.
9962 // Only a non-trivial move assignment can observe this. We only want to
9963 // diagnose if we implicitly define an assignment operator that assigns
9964 // two base classes, both of which move-assign the same virtual base.
9965 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9966 Class->getNumBases() < 2)
9967 return;
9968
9969 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9970 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9971 VBaseMap VBases;
9972
Aaron Ballman574705e2014-03-13 15:41:46 +00009973 for (auto &BI : Class->bases()) {
9974 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009975 while (!Worklist.empty()) {
9976 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9977 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9978
9979 // If the base has no non-trivial move assignment operators,
9980 // we don't care about moves from it.
9981 if (!Base->hasNonTrivialMoveAssignment())
9982 continue;
9983
9984 // If there's nothing virtual here, skip it.
9985 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9986 continue;
9987
9988 // If we're not actually going to call a move assignment for this base,
9989 // or the selected move assignment is trivial, skip it.
9990 Sema::SpecialMemberOverloadResult *SMOR =
9991 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9992 /*ConstArg*/false, /*VolatileArg*/false,
9993 /*RValueThis*/true, /*ConstThis*/false,
9994 /*VolatileThis*/false);
9995 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9996 !SMOR->getMethod()->isMoveAssignmentOperator())
9997 continue;
9998
9999 if (BaseSpec->isVirtual()) {
10000 // We're going to move-assign this virtual base, and its move
10001 // assignment operator is not trivial. If this can happen for
10002 // multiple distinct direct bases of Class, diagnose it. (If it
10003 // only happens in one base, we'll diagnose it when synthesizing
10004 // that base class's move assignment operator.)
10005 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010006 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010007 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010008 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010009 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10010 << Class << Base;
10011 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10012 << (Base->getCanonicalDecl() ==
10013 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10014 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010015 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010016 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010017 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10018 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010019
10020 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010021 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010022 }
10023 } else {
10024 // Only walk over bases that have defaulted move assignment operators.
10025 // We assume that any user-provided move assignment operator handles
10026 // the multiple-moves-of-vbase case itself somehow.
10027 if (!SMOR->getMethod()->isDefaulted())
10028 continue;
10029
10030 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010031 for (auto &BI : Base->bases())
10032 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010033 }
10034 }
10035 }
10036}
10037
Sebastian Redl22653ba2011-08-30 19:58:05 +000010038void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10039 CXXMethodDecl *MoveAssignOperator) {
10040 assert((MoveAssignOperator->isDefaulted() &&
10041 MoveAssignOperator->isOverloadedOperator() &&
10042 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010043 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10044 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010045 "DefineImplicitMoveAssignment called for wrong function");
10046
10047 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10048
10049 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10050 MoveAssignOperator->setInvalidDecl();
10051 return;
10052 }
10053
Eli Friedman276dd182013-09-05 00:02:25 +000010054 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010055
Eli Friedmaneaf34142012-10-18 20:14:08 +000010056 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010057 DiagnosticErrorTrap Trap(Diags);
10058
10059 // C++0x [class.copy]p28:
10060 // The implicitly-defined or move assignment operator for a non-union class
10061 // X performs memberwise move assignment of its subobjects. The direct base
10062 // classes of X are assigned first, in the order of their declaration in the
10063 // base-specifier-list, and then the immediate non-static data members of X
10064 // are assigned, in the order in which they were declared in the class
10065 // definition.
10066
Richard Smithb2504bd2013-11-04 04:26:14 +000010067 // Issue a warning if our implicit move assignment operator will move
10068 // from a virtual base more than once.
10069 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010070
Sebastian Redl22653ba2011-08-30 19:58:05 +000010071 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010072 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010073
10074 // The parameter for the "other" object, which we are move from.
10075 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10076 QualType OtherRefType = Other->getType()->
10077 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010078 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010079 "Bad argument type of defaulted move assignment");
10080
10081 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010082 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10083 ? MoveAssignOperator->getLocEnd()
10084 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010085
Pavel Labath58934982013-08-30 08:52:28 +000010086 // Builds a reference to the "other" object.
10087 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010088 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010089 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010090
Pavel Labath58934982013-08-30 08:52:28 +000010091 // Builds the "this" pointer.
10092 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010093
Sebastian Redl22653ba2011-08-30 19:58:05 +000010094 // Assign base classes.
10095 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010096 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010097 // C++11 [class.copy]p28:
10098 // It is unspecified whether subobjects representing virtual base classes
10099 // are assigned more than once by the implicitly-defined copy assignment
10100 // operator.
10101 // FIXME: Do not assign to a vbase that will be assigned by some other base
10102 // class. For a move-assignment, this can result in the vbase being moved
10103 // multiple times.
10104
Sebastian Redl22653ba2011-08-30 19:58:05 +000010105 // Form the assignment:
10106 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010107 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010108 if (!BaseType->isRecordType()) {
10109 Invalid = true;
10110 continue;
10111 }
10112
10113 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010114 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010115
10116 // Construct the "from" expression, which is an implicit cast to the
10117 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010118 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010119
10120 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010121 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010122
10123 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010124 CastBuilder To(DerefThis,
10125 Context.getCVRQualifiedType(
10126 BaseType, MoveAssignOperator->getTypeQualifiers()),
10127 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010128
10129 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010130 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010131 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010132 /*CopyingBaseSubobject=*/true,
10133 /*Copying=*/false);
10134 if (Move.isInvalid()) {
10135 Diag(CurrentLocation, diag::note_member_synthesized_at)
10136 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10137 MoveAssignOperator->setInvalidDecl();
10138 return;
10139 }
10140
10141 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010142 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010143 }
10144
Sebastian Redl22653ba2011-08-30 19:58:05 +000010145 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010146 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010147 if (Field->isUnnamedBitfield())
10148 continue;
10149
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010150 if (Field->isInvalidDecl()) {
10151 Invalid = true;
10152 continue;
10153 }
10154
Sebastian Redl22653ba2011-08-30 19:58:05 +000010155 // Check for members of reference type; we can't move those.
10156 if (Field->getType()->isReferenceType()) {
10157 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10158 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10159 Diag(Field->getLocation(), diag::note_declared_at);
10160 Diag(CurrentLocation, diag::note_member_synthesized_at)
10161 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10162 Invalid = true;
10163 continue;
10164 }
10165
10166 // Check for members of const-qualified, non-class type.
10167 QualType BaseType = Context.getBaseElementType(Field->getType());
10168 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10169 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10170 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10171 Diag(Field->getLocation(), diag::note_declared_at);
10172 Diag(CurrentLocation, diag::note_member_synthesized_at)
10173 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10174 Invalid = true;
10175 continue;
10176 }
10177
10178 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010179 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10180 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010181
10182 QualType FieldType = Field->getType().getNonReferenceType();
10183 if (FieldType->isIncompleteArrayType()) {
10184 assert(ClassDecl->hasFlexibleArrayMember() &&
10185 "Incomplete array type is not valid");
10186 continue;
10187 }
10188
10189 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010190 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10191 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010192 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010193 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010194 MemberBuilder From(MoveOther, OtherRefType,
10195 /*IsArrow=*/false, MemberLookup);
10196 MemberBuilder To(This, getCurrentThisType(),
10197 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010198
Pavel Labath58934982013-08-30 08:52:28 +000010199 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010200 "Member reference with rvalue base must be rvalue except for reference "
10201 "members, which aren't allowed for move assignment.");
10202
Sebastian Redl22653ba2011-08-30 19:58:05 +000010203 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010204 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010205 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010206 /*CopyingBaseSubobject=*/false,
10207 /*Copying=*/false);
10208 if (Move.isInvalid()) {
10209 Diag(CurrentLocation, diag::note_member_synthesized_at)
10210 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10211 MoveAssignOperator->setInvalidDecl();
10212 return;
10213 }
Richard Smith11d19592012-11-12 23:33:00 +000010214
Sebastian Redl22653ba2011-08-30 19:58:05 +000010215 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010216 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010217 }
10218
10219 if (!Invalid) {
10220 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010221 ExprResult ThisObj =
10222 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10223
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010224 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010225 if (Return.isInvalid())
10226 Invalid = true;
10227 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010228 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010229
10230 if (Trap.hasErrorOccurred()) {
10231 Diag(CurrentLocation, diag::note_member_synthesized_at)
10232 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10233 Invalid = true;
10234 }
10235 }
10236 }
10237
10238 if (Invalid) {
10239 MoveAssignOperator->setInvalidDecl();
10240 return;
10241 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010242
10243 StmtResult Body;
10244 {
10245 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010246 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010247 /*isStmtExpr=*/false);
10248 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10249 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010250 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010251
10252 if (ASTMutationListener *L = getASTMutationListener()) {
10253 L->CompletedImplicitDefinition(MoveAssignOperator);
10254 }
10255}
10256
Richard Smithd3b5c9082012-07-27 04:22:15 +000010257Sema::ImplicitExceptionSpecification
10258Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10259 CXXRecordDecl *ClassDecl = MD->getParent();
10260
10261 ImplicitExceptionSpecification ExceptSpec(*this);
10262 if (ClassDecl->isInvalidDecl())
10263 return ExceptSpec;
10264
10265 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010266 assert(T->getNumParams() >= 1 && "not a copy ctor");
10267 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010268
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010269 // C++ [except.spec]p14:
10270 // An implicitly declared special member function (Clause 12) shall have an
10271 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010272 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010273 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010274 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010275 continue;
10276
Douglas Gregora6d69502010-07-02 23:41:54 +000010277 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010278 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010279 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010280 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010281 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010282 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010283 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010284 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010285 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010286 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010287 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010288 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010289 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010290 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010291 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010292 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10293 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010294 LookupCopyingConstructor(FieldClassDecl,
10295 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010296 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010297 }
10298 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010299
Richard Smithd3b5c9082012-07-27 04:22:15 +000010300 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010301}
10302
10303CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10304 CXXRecordDecl *ClassDecl) {
10305 // C++ [class.copy]p4:
10306 // If the class definition does not explicitly declare a copy
10307 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010308 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010309
Richard Smith8bf22e52012-11-29 01:34:07 +000010310 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10311 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010312 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010313
Alexis Hunt913820d2011-05-13 06:10:58 +000010314 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10315 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010316 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010317 if (Const)
10318 ArgType = ArgType.withConst();
10319 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010320
Richard Smithb5800092012-06-10 05:43:50 +000010321 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10322 CXXCopyConstructor,
10323 Const);
10324
Douglas Gregor54be3392010-07-01 17:57:27 +000010325 DeclarationName Name
10326 = Context.DeclarationNames.getCXXConstructorName(
10327 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010328 SourceLocation ClassLoc = ClassDecl->getLocation();
10329 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010330
10331 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010332 // member of its class.
10333 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010334 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010335 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010336 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010337 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010338 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010339
Richard Smithd3b5c9082012-07-27 04:22:15 +000010340 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010341 FunctionProtoType::ExtProtoInfo EPI =
10342 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010343 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010344 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010345
Douglas Gregor54be3392010-07-01 17:57:27 +000010346 // Add the parameter to the constructor.
10347 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010348 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010349 /*IdentifierInfo=*/nullptr,
10350 ArgType, /*TInfo=*/nullptr,
10351 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010352 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010353
Richard Smith6b02d462012-12-08 08:32:28 +000010354 CopyConstructor->setTrivial(
10355 ClassDecl->needsOverloadResolutionForCopyConstructor()
10356 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10357 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010358
Richard Smith852265f2012-03-30 20:53:28 +000010359 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010360 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010361
Richard Smith6b02d462012-12-08 08:32:28 +000010362 // Note that we have declared this constructor.
10363 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10364
10365 if (Scope *S = getScopeForContext(ClassDecl))
10366 PushOnScopeChains(CopyConstructor, S, false);
10367 ClassDecl->addDecl(CopyConstructor);
10368
Douglas Gregor54be3392010-07-01 17:57:27 +000010369 return CopyConstructor;
10370}
10371
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010372void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010373 CXXConstructorDecl *CopyConstructor) {
10374 assert((CopyConstructor->isDefaulted() &&
10375 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010376 !CopyConstructor->doesThisDeclarationHaveABody() &&
10377 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010378 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010379
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010380 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010381 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010382
Richard Smithd577fbb2013-06-13 03:23:42 +000010383 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010384 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010385 // deprecated if the class has a user-declared copy assignment operator
10386 // or a user-declared destructor.
10387 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10388 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10389
Eli Friedmaneaf34142012-10-18 20:14:08 +000010390 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010391 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010392
David Blaikie3fc2f912013-01-17 05:26:25 +000010393 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010394 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010395 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010396 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010397 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010398 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010399 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10400 ? CopyConstructor->getLocEnd()
10401 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010402 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010403 CopyConstructor->setBody(
10404 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010405 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010406
Eli Friedman276dd182013-09-05 00:02:25 +000010407 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010408 MarkVTableUsed(CurrentLocation, ClassDecl);
10409
Sebastian Redlab238a72011-04-24 16:28:06 +000010410 if (ASTMutationListener *L = getASTMutationListener()) {
10411 L->CompletedImplicitDefinition(CopyConstructor);
10412 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010413}
10414
Sebastian Redl22653ba2011-08-30 19:58:05 +000010415Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010416Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10417 CXXRecordDecl *ClassDecl = MD->getParent();
10418
Sebastian Redl22653ba2011-08-30 19:58:05 +000010419 // C++ [except.spec]p14:
10420 // An implicitly declared special member function (Clause 12) shall have an
10421 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010422 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010423 if (ClassDecl->isInvalidDecl())
10424 return ExceptSpec;
10425
10426 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010427 for (const auto &B : ClassDecl->bases()) {
10428 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010429 continue;
10430
Aaron Ballman574705e2014-03-13 15:41:46 +000010431 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010432 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010433 CXXConstructorDecl *Constructor =
10434 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010435 // If this is a deleted function, add it anyway. This might be conformant
10436 // with the standard. This might not. I'm not sure. It might not matter.
10437 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010438 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010439 }
10440 }
10441
10442 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010443 for (const auto &B : ClassDecl->vbases()) {
10444 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010445 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010446 CXXConstructorDecl *Constructor =
10447 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010448 // If this is a deleted function, add it anyway. This might be conformant
10449 // with the standard. This might not. I'm not sure. It might not matter.
10450 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010451 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010452 }
10453 }
10454
10455 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010456 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010457 QualType FieldType = Context.getBaseElementType(F->getType());
10458 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10459 CXXConstructorDecl *Constructor =
10460 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010461 // If this is a deleted function, add it anyway. This might be conformant
10462 // with the standard. This might not. I'm not sure. It might not matter.
10463 // In particular, the problem is that this function never gets called. It
10464 // might just be ill-formed because this function attempts to refer to
10465 // a deleted function here.
10466 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010467 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010468 }
10469 }
10470
10471 return ExceptSpec;
10472}
10473
10474CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10475 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010476 assert(ClassDecl->needsImplicitMoveConstructor());
10477
Richard Smith8bf22e52012-11-29 01:34:07 +000010478 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10479 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010480 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010481
Sebastian Redl22653ba2011-08-30 19:58:05 +000010482 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10483 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010484
Richard Smithb5800092012-06-10 05:43:50 +000010485 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10486 CXXMoveConstructor,
10487 false);
10488
Sebastian Redl22653ba2011-08-30 19:58:05 +000010489 DeclarationName Name
10490 = Context.DeclarationNames.getCXXConstructorName(
10491 Context.getCanonicalType(ClassType));
10492 SourceLocation ClassLoc = ClassDecl->getLocation();
10493 DeclarationNameInfo NameInfo(Name, ClassLoc);
10494
Richard Smith99005e62013-05-07 03:19:20 +000010495 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010496 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010497 // member of its class.
10498 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010499 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010500 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010501 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010502 MoveConstructor->setAccess(AS_public);
10503 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010504
Richard Smithd3b5c9082012-07-27 04:22:15 +000010505 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010506 FunctionProtoType::ExtProtoInfo EPI =
10507 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010508 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010509 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010510
Sebastian Redl22653ba2011-08-30 19:58:05 +000010511 // Add the parameter to the constructor.
10512 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10513 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010514 /*IdentifierInfo=*/nullptr,
10515 ArgType, /*TInfo=*/nullptr,
10516 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010517 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010518
Richard Smith6b02d462012-12-08 08:32:28 +000010519 MoveConstructor->setTrivial(
10520 ClassDecl->needsOverloadResolutionForMoveConstructor()
10521 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10522 : ClassDecl->hasTrivialMoveConstructor());
10523
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010524 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010525 ClassDecl->setImplicitMoveConstructorIsDeleted();
10526 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010527 }
10528
10529 // Note that we have declared this constructor.
10530 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10531
10532 if (Scope *S = getScopeForContext(ClassDecl))
10533 PushOnScopeChains(MoveConstructor, S, false);
10534 ClassDecl->addDecl(MoveConstructor);
10535
10536 return MoveConstructor;
10537}
10538
10539void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10540 CXXConstructorDecl *MoveConstructor) {
10541 assert((MoveConstructor->isDefaulted() &&
10542 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010543 !MoveConstructor->doesThisDeclarationHaveABody() &&
10544 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010545 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10546
10547 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10548 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10549
Eli Friedmaneaf34142012-10-18 20:14:08 +000010550 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010551 DiagnosticErrorTrap Trap(Diags);
10552
David Blaikie3fc2f912013-01-17 05:26:25 +000010553 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010554 Trap.hasErrorOccurred()) {
10555 Diag(CurrentLocation, diag::note_member_synthesized_at)
10556 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10557 MoveConstructor->setInvalidDecl();
10558 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010559 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10560 ? MoveConstructor->getLocEnd()
10561 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010562 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010563 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010564 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010565 }
10566
Eli Friedman276dd182013-09-05 00:02:25 +000010567 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010568 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010569
10570 if (ASTMutationListener *L = getASTMutationListener()) {
10571 L->CompletedImplicitDefinition(MoveConstructor);
10572 }
10573}
10574
Douglas Gregor74f7d502012-02-15 19:33:52 +000010575bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010576 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010577}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010578
10579void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010580 SourceLocation CurrentLocation,
10581 CXXConversionDecl *Conv) {
10582 CXXRecordDecl *Lambda = Conv->getParent();
10583 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10584 // If we are defining a specialization of a conversion to function-ptr
10585 // cache the deduced template arguments for this specialization
10586 // so that we can use them to retrieve the corresponding call-operator
10587 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010588 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10589
Faisal Vali571df122013-09-29 08:45:24 +000010590 // Retrieve the corresponding call-operator specialization.
10591 if (Lambda->isGenericLambda()) {
10592 assert(Conv->isFunctionTemplateSpecialization());
10593 FunctionTemplateDecl *CallOpTemplate =
10594 CallOp->getDescribedFunctionTemplate();
10595 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010596 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010597 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010598 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010599 InsertPos);
10600 assert(CallOpSpec &&
10601 "Conversion operator must have a corresponding call operator");
10602 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10603 }
10604 // Mark the call operator referenced (and add to pending instantiations
10605 // if necessary).
10606 // For both the conversion and static-invoker template specializations
10607 // we construct their body's in this function, so no need to add them
10608 // to the PendingInstantiations.
10609 MarkFunctionReferenced(CurrentLocation, CallOp);
10610
Eli Friedmaneaf34142012-10-18 20:14:08 +000010611 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010612 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010613
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010614 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010615 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10616 // ... and get the corresponding specialization for a generic lambda.
10617 if (Lambda->isGenericLambda()) {
10618 assert(DeducedTemplateArgs &&
10619 "Must have deduced template arguments from Conversion Operator");
10620 FunctionTemplateDecl *InvokeTemplate =
10621 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010622 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010623 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010624 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010625 InsertPos);
10626 assert(InvokeSpec &&
10627 "Must have a corresponding static invoker specialization");
10628 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10629 }
10630 // Construct the body of the conversion function { return __invoke; }.
10631 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010632 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010633 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010634 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010635 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10636 Conv->getLocation(),
10637 Conv->getLocation()));
10638
10639 Conv->markUsed(Context);
10640 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010641
Faisal Vali571df122013-09-29 08:45:24 +000010642 // Fill in the __invoke function with a dummy implementation. IR generation
10643 // will fill in the actual details.
10644 Invoker->markUsed(Context);
10645 Invoker->setReferenced();
10646 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10647
Douglas Gregord3b672c2012-02-16 01:06:16 +000010648 if (ASTMutationListener *L = getASTMutationListener()) {
10649 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010650 L->CompletedImplicitDefinition(Invoker);
10651 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010652}
10653
Faisal Vali571df122013-09-29 08:45:24 +000010654
10655
Douglas Gregord3b672c2012-02-16 01:06:16 +000010656void Sema::DefineImplicitLambdaToBlockPointerConversion(
10657 SourceLocation CurrentLocation,
10658 CXXConversionDecl *Conv)
10659{
Faisal Vali850da1a2013-09-29 17:08:32 +000010660 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010661
Eli Friedman276dd182013-09-05 00:02:25 +000010662 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010663
Eli Friedmaneaf34142012-10-18 20:14:08 +000010664 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010665 DiagnosticErrorTrap Trap(Diags);
10666
Douglas Gregored90df32012-02-22 05:02:47 +000010667 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010668 Expr *This = ActOnCXXThis(CurrentLocation).get();
10669 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010670
Eli Friedman98b01ed2012-03-01 04:01:32 +000010671 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10672 Conv->getLocation(),
10673 Conv, DerefThis);
10674
10675 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10676 // behavior. Note that only the general conversion function does this
10677 // (since it's unusable otherwise); in the case where we inline the
10678 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010679 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010680 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10681 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010682 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010683
10684 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010685 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010686 Conv->setInvalidDecl();
10687 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010688 }
Douglas Gregored90df32012-02-22 05:02:47 +000010689
Douglas Gregored90df32012-02-22 05:02:47 +000010690 // Create the return statement that returns the block from the conversion
10691 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010692 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010693 if (Return.isInvalid()) {
10694 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10695 Conv->setInvalidDecl();
10696 return;
10697 }
10698
10699 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010700 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010701 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010702 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010703 Conv->getLocation()));
10704
Douglas Gregored90df32012-02-22 05:02:47 +000010705 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010706 if (ASTMutationListener *L = getASTMutationListener()) {
10707 L->CompletedImplicitDefinition(Conv);
10708 }
10709}
10710
Douglas Gregord2f70072012-03-10 06:53:13 +000010711/// \brief Determine whether the given list arguments contains exactly one
10712/// "real" (non-default) argument.
10713static bool hasOneRealArgument(MultiExprArg Args) {
10714 switch (Args.size()) {
10715 case 0:
10716 return false;
10717
10718 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010719 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010720 return false;
10721
10722 // fall through
10723 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010724 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010725 }
10726
10727 return false;
10728}
10729
John McCalldadc5752010-08-24 06:29:42 +000010730ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010731Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010732 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010733 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010734 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010735 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010736 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010737 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010738 unsigned ConstructKind,
10739 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010740 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010741
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010742 // C++0x [class.copy]p34:
10743 // When certain criteria are met, an implementation is allowed to
10744 // omit the copy/move construction of a class object, even if the
10745 // copy/move constructor and/or destructor for the object have
10746 // side effects. [...]
10747 // - when a temporary class object that has not been bound to a
10748 // reference (12.2) would be copied/moved to a class object
10749 // with the same cv-unqualified type, the copy/move operation
10750 // can be omitted by constructing the temporary object
10751 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010752 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010753 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010754 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010755 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010756 }
Mike Stump11289f42009-09-09 15:08:12 +000010757
10758 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010759 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010760 IsListInitialization,
10761 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000010762 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010763}
10764
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010765/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10766/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010767ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010768Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10769 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010770 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010771 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010772 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010773 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010774 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010775 unsigned ConstructKind,
10776 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010777 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010778 return CXXConstructExpr::Create(
10779 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010780 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10781 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010782 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10783 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010784}
10785
John McCall03c48482010-02-02 09:10:11 +000010786void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010787 if (VD->isInvalidDecl()) return;
10788
John McCall03c48482010-02-02 09:10:11 +000010789 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010790 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010791 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010792 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010793
Chandler Carruth86d17d32011-03-27 21:26:48 +000010794 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010795 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010796 CheckDestructorAccess(VD->getLocation(), Destructor,
10797 PDiag(diag::err_access_dtor_var)
10798 << VD->getDeclName()
10799 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010800 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010801
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010802 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010803 if (!VD->hasGlobalStorage()) return;
10804
10805 // Emit warning for non-trivial dtor in global scope (a real global,
10806 // class-static, function-static).
10807 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10808
10809 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010810 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010811 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010812}
10813
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010814/// \brief Given a constructor and the set of arguments provided for the
10815/// constructor, convert the arguments and add any required default arguments
10816/// to form a proper call to this constructor.
10817///
10818/// \returns true if an error occurred, false otherwise.
10819bool
10820Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10821 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010822 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010823 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010824 bool AllowExplicit,
10825 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010826 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10827 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010828 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010829
10830 const FunctionProtoType *Proto
10831 = Constructor->getType()->getAs<FunctionProtoType>();
10832 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010833 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010834
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010835 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010836 if (NumArgs < NumParams)
10837 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010838 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010839 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010840
10841 VariadicCallType CallType =
10842 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010843 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010844 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010845 Proto, 0,
10846 llvm::makeArrayRef(Args, NumArgs),
10847 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010848 CallType, AllowExplicit,
10849 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010850 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010851
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010852 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010853
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010854 CheckConstructorCall(Constructor,
10855 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10856 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010857 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010858
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010859 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010860}
10861
Anders Carlssone363c8e2009-12-12 00:32:00 +000010862static inline bool
10863CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10864 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010865 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010866 if (isa<NamespaceDecl>(DC)) {
10867 return SemaRef.Diag(FnDecl->getLocation(),
10868 diag::err_operator_new_delete_declared_in_namespace)
10869 << FnDecl->getDeclName();
10870 }
10871
10872 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010873 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010874 return SemaRef.Diag(FnDecl->getLocation(),
10875 diag::err_operator_new_delete_declared_static)
10876 << FnDecl->getDeclName();
10877 }
10878
Anders Carlsson60659a82009-12-12 02:43:16 +000010879 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010880}
10881
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010882static inline bool
10883CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10884 CanQualType ExpectedResultType,
10885 CanQualType ExpectedFirstParamType,
10886 unsigned DependentParamTypeDiag,
10887 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010888 QualType ResultType =
10889 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010890
10891 // Check that the result type is not dependent.
10892 if (ResultType->isDependentType())
10893 return SemaRef.Diag(FnDecl->getLocation(),
10894 diag::err_operator_new_delete_dependent_result_type)
10895 << FnDecl->getDeclName() << ExpectedResultType;
10896
10897 // Check that the result type is what we expect.
10898 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10899 return SemaRef.Diag(FnDecl->getLocation(),
10900 diag::err_operator_new_delete_invalid_result_type)
10901 << FnDecl->getDeclName() << ExpectedResultType;
10902
10903 // A function template must have at least 2 parameters.
10904 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10905 return SemaRef.Diag(FnDecl->getLocation(),
10906 diag::err_operator_new_delete_template_too_few_parameters)
10907 << FnDecl->getDeclName();
10908
10909 // The function decl must have at least 1 parameter.
10910 if (FnDecl->getNumParams() == 0)
10911 return SemaRef.Diag(FnDecl->getLocation(),
10912 diag::err_operator_new_delete_too_few_parameters)
10913 << FnDecl->getDeclName();
10914
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010915 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010916 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10917 if (FirstParamType->isDependentType())
10918 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10919 << FnDecl->getDeclName() << ExpectedFirstParamType;
10920
10921 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010922 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010923 ExpectedFirstParamType)
10924 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10925 << FnDecl->getDeclName() << ExpectedFirstParamType;
10926
10927 return false;
10928}
10929
Anders Carlsson12308f42009-12-11 23:23:22 +000010930static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010931CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010932 // C++ [basic.stc.dynamic.allocation]p1:
10933 // A program is ill-formed if an allocation function is declared in a
10934 // namespace scope other than global scope or declared static in global
10935 // scope.
10936 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10937 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010938
10939 CanQualType SizeTy =
10940 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10941
10942 // C++ [basic.stc.dynamic.allocation]p1:
10943 // The return type shall be void*. The first parameter shall have type
10944 // std::size_t.
10945 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10946 SizeTy,
10947 diag::err_operator_new_dependent_param_type,
10948 diag::err_operator_new_param_type))
10949 return true;
10950
10951 // C++ [basic.stc.dynamic.allocation]p1:
10952 // The first parameter shall not have an associated default argument.
10953 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010954 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010955 diag::err_operator_new_default_arg)
10956 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10957
10958 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010959}
10960
10961static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010962CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010963 // C++ [basic.stc.dynamic.deallocation]p1:
10964 // A program is ill-formed if deallocation functions are declared in a
10965 // namespace scope other than global scope or declared static in global
10966 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010967 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10968 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010969
10970 // C++ [basic.stc.dynamic.deallocation]p2:
10971 // Each deallocation function shall return void and its first parameter
10972 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010973 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10974 SemaRef.Context.VoidPtrTy,
10975 diag::err_operator_delete_dependent_param_type,
10976 diag::err_operator_delete_param_type))
10977 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010978
Anders Carlsson12308f42009-12-11 23:23:22 +000010979 return false;
10980}
10981
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010982/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10983/// of this overloaded operator is well-formed. If so, returns false;
10984/// otherwise, emits appropriate diagnostics and returns true.
10985bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010986 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010987 "Expected an overloaded operator declaration");
10988
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010989 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10990
Mike Stump11289f42009-09-09 15:08:12 +000010991 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010992 // The allocation and deallocation functions, operator new,
10993 // operator new[], operator delete and operator delete[], are
10994 // described completely in 3.7.3. The attributes and restrictions
10995 // found in the rest of this subclause do not apply to them unless
10996 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010997 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010998 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010999
Anders Carlsson22f443f2009-12-12 00:26:23 +000011000 if (Op == OO_New || Op == OO_Array_New)
11001 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011002
11003 // C++ [over.oper]p6:
11004 // An operator function shall either be a non-static member
11005 // function or be a non-member function and have at least one
11006 // parameter whose type is a class, a reference to a class, an
11007 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011008 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11009 if (MethodDecl->isStatic())
11010 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011011 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011012 } else {
11013 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011014 for (auto Param : FnDecl->params()) {
11015 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011016 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11017 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011018 ClassOrEnumParam = true;
11019 break;
11020 }
11021 }
11022
Douglas Gregord69246b2008-11-17 16:14:12 +000011023 if (!ClassOrEnumParam)
11024 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011025 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011026 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011027 }
11028
11029 // C++ [over.oper]p8:
11030 // An operator function cannot have default arguments (8.3.6),
11031 // except where explicitly stated below.
11032 //
Mike Stump11289f42009-09-09 15:08:12 +000011033 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011034 // (C++ [over.call]p1).
11035 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011036 for (auto Param : FnDecl->params()) {
11037 if (Param->hasDefaultArg())
11038 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011039 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011040 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011041 }
11042 }
11043
Douglas Gregor6cf08062008-11-10 13:38:07 +000011044 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11045 { false, false, false }
11046#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11047 , { Unary, Binary, MemberOnly }
11048#include "clang/Basic/OperatorKinds.def"
11049 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011050
Douglas Gregor6cf08062008-11-10 13:38:07 +000011051 bool CanBeUnaryOperator = OperatorUses[Op][0];
11052 bool CanBeBinaryOperator = OperatorUses[Op][1];
11053 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011054
11055 // C++ [over.oper]p8:
11056 // [...] Operator functions cannot have more or fewer parameters
11057 // than the number required for the corresponding operator, as
11058 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011059 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011060 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011061 if (Op != OO_Call &&
11062 ((NumParams == 1 && !CanBeUnaryOperator) ||
11063 (NumParams == 2 && !CanBeBinaryOperator) ||
11064 (NumParams < 1) || (NumParams > 2))) {
11065 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011066 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011067 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011068 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011069 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011070 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011071 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011072 assert(CanBeBinaryOperator &&
11073 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011074 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011075 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011076
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011077 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011078 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011079 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011080
Douglas Gregord69246b2008-11-17 16:14:12 +000011081 // Overloaded operators other than operator() cannot be variadic.
11082 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011083 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011084 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011085 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011086 }
11087
11088 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011089 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11090 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011091 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011092 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011093 }
11094
11095 // C++ [over.inc]p1:
11096 // The user-defined function called operator++ implements the
11097 // prefix and postfix ++ operator. If this function is a member
11098 // function with no parameters, or a non-member function with one
11099 // parameter of class or enumeration type, it defines the prefix
11100 // increment operator ++ for objects of that type. If the function
11101 // is a member function with one parameter (which shall be of type
11102 // int) or a non-member function with two parameters (the second
11103 // of which shall be of type int), it defines the postfix
11104 // increment operator ++ for objects of that type.
11105 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11106 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011107 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011108
Richard Smith538b52a2014-01-30 22:24:05 +000011109 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11110 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011111 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011112 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011113 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011114 }
11115
Douglas Gregord69246b2008-11-17 16:14:12 +000011116 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011117}
Chris Lattner3b024a32008-12-17 07:09:26 +000011118
Alexis Huntc88db062010-01-13 09:01:02 +000011119/// CheckLiteralOperatorDeclaration - Check whether the declaration
11120/// of this literal operator function is well-formed. If so, returns
11121/// false; otherwise, emits appropriate diagnostics and returns true.
11122bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011123 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011124 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11125 << FnDecl->getDeclName();
11126 return true;
11127 }
11128
Richard Smith72eebee2012-03-04 09:41:16 +000011129 if (FnDecl->isExternC()) {
11130 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11131 return true;
11132 }
11133
Alexis Huntc88db062010-01-13 09:01:02 +000011134 bool Valid = false;
11135
Richard Smithbcc22fc2012-03-09 08:00:36 +000011136 // This might be the definition of a literal operator template.
11137 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11138 // This might be a specialization of a literal operator template.
11139 if (!TpDecl)
11140 TpDecl = FnDecl->getPrimaryTemplate();
11141
Richard Smithb8b41d32013-10-07 19:57:58 +000011142 // template <char...> type operator "" name() and
11143 // template <class T, T...> type operator "" name() are the only valid
11144 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011145 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011146 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011147 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011148 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11149 if (Params->size() == 1) {
11150 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011151 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011152
Alexis Hunt7dd26172010-04-07 23:11:06 +000011153 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011154 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11155 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11156 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011157 } else if (Params->size() == 2) {
11158 TemplateTypeParmDecl *PmType =
11159 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11160 NonTypeTemplateParmDecl *PmArgs =
11161 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11162
11163 // The second template parameter must be a parameter pack with the
11164 // first template parameter as its type.
11165 if (PmType && PmArgs &&
11166 !PmType->isTemplateParameterPack() &&
11167 PmArgs->isTemplateParameterPack()) {
11168 const TemplateTypeParmType *TArgs =
11169 PmArgs->getType()->getAs<TemplateTypeParmType>();
11170 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11171 TArgs->getIndex() == PmType->getIndex()) {
11172 Valid = true;
11173 if (ActiveTemplateInstantiations.empty())
11174 Diag(FnDecl->getLocation(),
11175 diag::ext_string_literal_operator_template);
11176 }
11177 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011178 }
11179 }
Richard Smith72eebee2012-03-04 09:41:16 +000011180 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011181 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011182 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11183
Richard Smith72eebee2012-03-04 09:41:16 +000011184 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011185
Alexis Hunt079a6f72010-04-07 22:57:35 +000011186 // unsigned long long int, long double, and any character type are allowed
11187 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011188 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11189 Context.hasSameType(T, Context.LongDoubleTy) ||
11190 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011191 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011192 Context.hasSameType(T, Context.Char16Ty) ||
11193 Context.hasSameType(T, Context.Char32Ty)) {
11194 if (++Param == FnDecl->param_end())
11195 Valid = true;
11196 goto FinishedParams;
11197 }
11198
Alexis Hunt079a6f72010-04-07 22:57:35 +000011199 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011200 const PointerType *PT = T->getAs<PointerType>();
11201 if (!PT)
11202 goto FinishedParams;
11203 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011204 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011205 goto FinishedParams;
11206 T = T.getUnqualifiedType();
11207
11208 // Move on to the second parameter;
11209 ++Param;
11210
11211 // If there is no second parameter, the first must be a const char *
11212 if (Param == FnDecl->param_end()) {
11213 if (Context.hasSameType(T, Context.CharTy))
11214 Valid = true;
11215 goto FinishedParams;
11216 }
11217
11218 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11219 // are allowed as the first parameter to a two-parameter function
11220 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011221 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011222 Context.hasSameType(T, Context.Char16Ty) ||
11223 Context.hasSameType(T, Context.Char32Ty)))
11224 goto FinishedParams;
11225
11226 // The second and final parameter must be an std::size_t
11227 T = (*Param)->getType().getUnqualifiedType();
11228 if (Context.hasSameType(T, Context.getSizeType()) &&
11229 ++Param == FnDecl->param_end())
11230 Valid = true;
11231 }
11232
11233 // FIXME: This diagnostic is absolutely terrible.
11234FinishedParams:
11235 if (!Valid) {
11236 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11237 << FnDecl->getDeclName();
11238 return true;
11239 }
11240
Richard Smith768cecc2012-03-09 08:16:22 +000011241 // A parameter-declaration-clause containing a default argument is not
11242 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011243 for (auto Param : FnDecl->params()) {
11244 if (Param->hasDefaultArg()) {
11245 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011246 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011247 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011248 break;
11249 }
11250 }
11251
Richard Smith0df56f42012-03-08 02:39:21 +000011252 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011253 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11254 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011255 // C++11 [usrlit.suffix]p1:
11256 // Literal suffix identifiers that do not start with an underscore
11257 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011258 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11259 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011260 }
Richard Smith0df56f42012-03-08 02:39:21 +000011261
Alexis Huntc88db062010-01-13 09:01:02 +000011262 return false;
11263}
11264
Douglas Gregor07665a62009-01-05 19:45:36 +000011265/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11266/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011267/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11268/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011269/// the '{' brace. Otherwise, this linkage specification does not
11270/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011271Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011272 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011273 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011274 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11275 if (!Lit->isAscii()) {
11276 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11277 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011278 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011279 }
11280
11281 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011282 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011283 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011284 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011285 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011286 Language = LinkageSpecDecl::lang_cxx;
11287 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011288 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11289 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011290 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011291 }
Mike Stump11289f42009-09-09 15:08:12 +000011292
Chris Lattner438e5012008-12-17 07:13:27 +000011293 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011294
Richard Smith4ee696d2014-02-17 23:25:27 +000011295 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11296 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011297 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011298 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011299 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011300 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011301}
11302
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011303/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011304/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11305/// valid, it's the position of the closing '}' brace in a linkage
11306/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011307Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011308 Decl *LinkageSpec,
11309 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011310 if (RBraceLoc.isValid()) {
11311 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11312 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011313 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011314 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011315 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011316}
11317
Michael Han84324352013-02-22 17:15:32 +000011318Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11319 AttributeList *AttrList,
11320 SourceLocation SemiLoc) {
11321 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11322 // Attribute declarations appertain to empty declaration so we handle
11323 // them here.
11324 if (AttrList)
11325 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011326
Michael Han84324352013-02-22 17:15:32 +000011327 CurContext->addDecl(ED);
11328 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011329}
11330
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011331/// \brief Perform semantic analysis for the variable declaration that
11332/// occurs within a C++ catch clause, returning the newly-created
11333/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011334VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011335 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011336 SourceLocation StartLoc,
11337 SourceLocation Loc,
11338 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011339 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011340 QualType ExDeclType = TInfo->getType();
11341
Sebastian Redl54c04d42008-12-22 19:15:10 +000011342 // Arrays and functions decay.
11343 if (ExDeclType->isArrayType())
11344 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11345 else if (ExDeclType->isFunctionType())
11346 ExDeclType = Context.getPointerType(ExDeclType);
11347
11348 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11349 // The exception-declaration shall not denote a pointer or reference to an
11350 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011351 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011352 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011353 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011354 Invalid = true;
11355 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011356
Sebastian Redl54c04d42008-12-22 19:15:10 +000011357 QualType BaseType = ExDeclType;
11358 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011359 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011360 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011361 BaseType = Ptr->getPointeeType();
11362 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011363 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011364 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011365 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011366 BaseType = Ref->getPointeeType();
11367 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011368 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011369 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011370 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011371 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011372 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011373
Mike Stump11289f42009-09-09 15:08:12 +000011374 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011375 RequireNonAbstractType(Loc, ExDeclType,
11376 diag::err_abstract_type_in_decl,
11377 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011378 Invalid = true;
11379
John McCall2ca705e2010-07-24 00:37:23 +000011380 // Only the non-fragile NeXT runtime currently supports C++ catches
11381 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011382 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011383 QualType T = ExDeclType;
11384 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11385 T = RT->getPointeeType();
11386
11387 if (T->isObjCObjectType()) {
11388 Diag(Loc, diag::err_objc_object_catch);
11389 Invalid = true;
11390 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011391 // FIXME: should this be a test for macosx-fragile specifically?
11392 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011393 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011394 }
11395 }
11396
Abramo Bagnaradff19302011-03-08 08:55:46 +000011397 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011398 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011399 ExDecl->setExceptionVariable(true);
11400
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011401 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011402 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011403 Invalid = true;
11404
Douglas Gregor750734c2011-07-06 18:14:43 +000011405 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011406 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011407 // Insulate this from anything else we might currently be parsing.
11408 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11409
Douglas Gregor6de584c2010-03-05 23:38:39 +000011410 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011411 // The object declared in an exception-declaration or, if the
11412 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011413 // copy-initialized (8.5) from the exception object. [...]
11414 // The object is destroyed when the handler exits, after the destruction
11415 // of any automatic objects initialized within the handler.
11416 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011417 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011418 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011419 QualType initType = ExDeclType;
11420
11421 InitializedEntity entity =
11422 InitializedEntity::InitializeVariable(ExDecl);
11423 InitializationKind initKind =
11424 InitializationKind::CreateCopy(Loc, SourceLocation());
11425
11426 Expr *opaqueValue =
11427 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011428 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11429 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011430 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011431 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011432 else {
11433 // If the constructor used was non-trivial, set this as the
11434 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011435 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011436 if (!construct->getConstructor()->isTrivial()) {
11437 Expr *init = MaybeCreateExprWithCleanups(construct);
11438 ExDecl->setInit(init);
11439 }
11440
11441 // And make sure it's destructable.
11442 FinalizeVarWithDestructor(ExDecl, recordType);
11443 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011444 }
11445 }
11446
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011447 if (Invalid)
11448 ExDecl->setInvalidDecl();
11449
11450 return ExDecl;
11451}
11452
11453/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11454/// handler.
John McCall48871652010-08-21 09:40:31 +000011455Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011456 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011457 bool Invalid = D.isInvalidType();
11458
11459 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011460 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11461 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011462 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11463 D.getIdentifierLoc());
11464 Invalid = true;
11465 }
11466
Sebastian Redl54c04d42008-12-22 19:15:10 +000011467 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011468 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011469 LookupOrdinaryName,
11470 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011471 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011472 // it contains any previous declaration, except for function parameters in
11473 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011474 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011475 if (isDeclInScope(PrevDecl, CurContext, S)) {
11476 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11477 << D.getIdentifier();
11478 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11479 Invalid = true;
11480 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011481 // Maybe we will complain about the shadowed template parameter.
11482 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011483 }
11484
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011485 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011486 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11487 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011488 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011489 }
11490
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011491 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011492 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011493 D.getIdentifierLoc(),
11494 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011495 if (Invalid)
11496 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011497
Sebastian Redl54c04d42008-12-22 19:15:10 +000011498 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011499 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011500 PushOnScopeChains(ExDecl, S);
11501 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011502 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011503
Douglas Gregor758a8692009-06-17 21:51:59 +000011504 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011505 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011506}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011507
Abramo Bagnaraea947882011-03-08 16:41:52 +000011508Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011509 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011510 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011511 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011512 StringLiteral *AssertMessage =
11513 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011514
Richard Smithded9c2e2012-07-11 22:37:56 +000011515 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011516 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011517
11518 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11519 AssertMessage, RParenLoc, false);
11520}
11521
11522Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11523 Expr *AssertExpr,
11524 StringLiteral *AssertMessage,
11525 SourceLocation RParenLoc,
11526 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011527 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011528 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11529 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011530 // In a static_assert-declaration, the constant-expression shall be a
11531 // constant expression that can be contextually converted to bool.
11532 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11533 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011534 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011535
Richard Smith902ca212011-12-14 23:32:26 +000011536 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011537 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011538 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011539 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011540 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011541
Richard Smithded9c2e2012-07-11 22:37:56 +000011542 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011543 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011544 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011545 if (AssertMessage)
11546 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011547 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011548 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011549 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011550 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011551 }
Mike Stump11289f42009-09-09 15:08:12 +000011552
Abramo Bagnaraea947882011-03-08 16:41:52 +000011553 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011554 AssertExpr, AssertMessage, RParenLoc,
11555 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011556
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011557 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011558 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011559}
Sebastian Redlf769df52009-03-24 22:27:57 +000011560
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011561/// \brief Perform semantic analysis of the given friend type declaration.
11562///
11563/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011564FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011565 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011566 TypeSourceInfo *TSInfo) {
11567 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11568
11569 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011570 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011571
Richard Smithc8239732011-10-18 21:39:00 +000011572 // C++03 [class.friend]p2:
11573 // An elaborated-type-specifier shall be used in a friend declaration
11574 // for a class.*
11575 //
11576 // * The class-key of the elaborated-type-specifier is required.
11577 if (!ActiveTemplateInstantiations.empty()) {
11578 // Do not complain about the form of friend template types during
11579 // template instantiation; we will already have complained when the
11580 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011581 } else {
11582 if (!T->isElaboratedTypeSpecifier()) {
11583 // If we evaluated the type to a record type, suggest putting
11584 // a tag in front.
11585 if (const RecordType *RT = T->getAs<RecordType>()) {
11586 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011587
11588 SmallString<16> InsertionText(" ");
11589 InsertionText += RD->getKindName();
11590
Nick Lewycky36722d22013-02-06 05:59:33 +000011591 Diag(TypeRange.getBegin(),
11592 getLangOpts().CPlusPlus11 ?
11593 diag::warn_cxx98_compat_unelaborated_friend_type :
11594 diag::ext_unelaborated_friend_type)
11595 << (unsigned) RD->getTagKind()
11596 << T
11597 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11598 InsertionText);
11599 } else {
11600 Diag(FriendLoc,
11601 getLangOpts().CPlusPlus11 ?
11602 diag::warn_cxx98_compat_nonclass_type_friend :
11603 diag::ext_nonclass_type_friend)
11604 << T
11605 << TypeRange;
11606 }
11607 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011608 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011609 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011610 diag::warn_cxx98_compat_enum_friend :
11611 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011612 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011613 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011614 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011615
Nick Lewycky36722d22013-02-06 05:59:33 +000011616 // C++11 [class.friend]p3:
11617 // A friend declaration that does not declare a function shall have one
11618 // of the following forms:
11619 // friend elaborated-type-specifier ;
11620 // friend simple-type-specifier ;
11621 // friend typename-specifier ;
11622 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11623 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11624 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011625
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011626 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011627 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011628 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011629 return FriendDecl::Create(Context, CurContext,
11630 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11631 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011632}
11633
John McCallace48cd2010-10-19 01:40:49 +000011634/// Handle a friend tag declaration where the scope specifier was
11635/// templated.
11636Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11637 unsigned TagSpec, SourceLocation TagLoc,
11638 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011639 IdentifierInfo *Name,
11640 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011641 AttributeList *Attr,
11642 MultiTemplateParamsArg TempParamLists) {
11643 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11644
11645 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011646 bool Invalid = false;
11647
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011648 if (TemplateParameterList *TemplateParams =
11649 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011650 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011651 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011652 if (TemplateParams->size() > 0) {
11653 // This is a declaration of a class template.
11654 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011655 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011656
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011657 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11658 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011659 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011660 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011661 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011662 } else {
11663 // The "template<>" header is extraneous.
11664 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11665 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11666 isExplicitSpecialization = true;
11667 }
11668 }
11669
Craig Topperc3ec1492014-05-26 06:22:03 +000011670 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011671
John McCallace48cd2010-10-19 01:40:49 +000011672 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011673 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011674 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011675 isAllExplicitSpecializations = false;
11676 break;
11677 }
11678 }
11679
11680 // FIXME: don't ignore attributes.
11681
11682 // If it's explicit specializations all the way down, just forget
11683 // about the template header and build an appropriate non-templated
11684 // friend. TODO: for source fidelity, remember the headers.
11685 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011686 if (SS.isEmpty()) {
11687 bool Owned = false;
11688 bool IsDependent = false;
11689 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011690 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011691 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011692 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011693 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011694 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011695 /*UnderlyingType=*/TypeResult(),
11696 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011697 }
Richard Smith649c7b062014-01-08 00:56:48 +000011698
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011699 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011700 ElaboratedTypeKeyword Keyword
11701 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011702 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011703 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011704 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011705 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011706
11707 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11708 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011709 DependentNameTypeLoc TL =
11710 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011711 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011712 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011713 TL.setNameLoc(NameLoc);
11714 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011715 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011716 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011717 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011718 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011719 }
11720
11721 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011722 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011723 Friend->setAccess(AS_public);
11724 CurContext->addDecl(Friend);
11725 return Friend;
11726 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011727
11728 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11729
11730
John McCallace48cd2010-10-19 01:40:49 +000011731
11732 // Handle the case of a templated-scope friend class. e.g.
11733 // template <class T> class A<T>::B;
11734 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011735 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11736 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011737 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11738 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11739 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011740 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011741 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011742 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011743 TL.setNameLoc(NameLoc);
11744
11745 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011746 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011747 Friend->setAccess(AS_public);
11748 Friend->setUnsupportedFriend(true);
11749 CurContext->addDecl(Friend);
11750 return Friend;
11751}
11752
11753
John McCall11083da2009-09-16 22:47:08 +000011754/// Handle a friend type declaration. This works in tandem with
11755/// ActOnTag.
11756///
11757/// Notes on friend class templates:
11758///
11759/// We generally treat friend class declarations as if they were
11760/// declaring a class. So, for example, the elaborated type specifier
11761/// in a friend declaration is required to obey the restrictions of a
11762/// class-head (i.e. no typedefs in the scope chain), template
11763/// parameters are required to match up with simple template-ids, &c.
11764/// However, unlike when declaring a template specialization, it's
11765/// okay to refer to a template specialization without an empty
11766/// template parameter declaration, e.g.
11767/// friend class A<T>::B<unsigned>;
11768/// We permit this as a special case; if there are any template
11769/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011770/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011771Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011772 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011773 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011774
11775 assert(DS.isFriendSpecified());
11776 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11777
John McCall11083da2009-09-16 22:47:08 +000011778 // Try to convert the decl specifier to a type. This works for
11779 // friend templates because ActOnTag never produces a ClassTemplateDecl
11780 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011781 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011782 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11783 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011784 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011785 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011786
Douglas Gregor6c110f32010-12-16 01:14:37 +000011787 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011788 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011789
John McCall11083da2009-09-16 22:47:08 +000011790 // This is definitely an error in C++98. It's probably meant to
11791 // be forbidden in C++0x, too, but the specification is just
11792 // poorly written.
11793 //
11794 // The problem is with declarations like the following:
11795 // template <T> friend A<T>::foo;
11796 // where deciding whether a class C is a friend or not now hinges
11797 // on whether there exists an instantiation of A that causes
11798 // 'foo' to equal C. There are restrictions on class-heads
11799 // (which we declare (by fiat) elaborated friend declarations to
11800 // be) that makes this tractable.
11801 //
11802 // FIXME: handle "template <> friend class A<T>;", which
11803 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011804 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011805 Diag(Loc, diag::err_tagless_friend_type_template)
11806 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011807 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011808 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011809
John McCallaa74a0c2009-08-28 07:59:38 +000011810 // C++98 [class.friend]p1: A friend of a class is a function
11811 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011812 // This is fixed in DR77, which just barely didn't make the C++03
11813 // deadline. It's also a very silly restriction that seriously
11814 // affects inner classes and which nobody else seems to implement;
11815 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011816 //
11817 // But note that we could warn about it: it's always useless to
11818 // friend one of your own members (it's not, however, worthless to
11819 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011820
John McCall11083da2009-09-16 22:47:08 +000011821 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011822 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011823 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011824 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011825 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011826 TSI,
John McCall11083da2009-09-16 22:47:08 +000011827 DS.getFriendSpecLoc());
11828 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011829 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011830
11831 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011832 return nullptr;
11833
John McCall11083da2009-09-16 22:47:08 +000011834 D->setAccess(AS_public);
11835 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011836
John McCall48871652010-08-21 09:40:31 +000011837 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011838}
11839
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011840NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11841 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011842 const DeclSpec &DS = D.getDeclSpec();
11843
11844 assert(DS.isFriendSpecified());
11845 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11846
11847 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011848 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011849
11850 // C++ [class.friend]p1
11851 // A friend of a class is a function or class....
11852 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011853 // It *doesn't* see through dependent types, which is correct
11854 // according to [temp.arg.type]p3:
11855 // If a declaration acquires a function type through a
11856 // type dependent on a template-parameter and this causes
11857 // a declaration that does not use the syntactic form of a
11858 // function declarator to have a function type, the program
11859 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011860 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011861 Diag(Loc, diag::err_unexpected_friend);
11862
11863 // It might be worthwhile to try to recover by creating an
11864 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011865 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011866 }
11867
11868 // C++ [namespace.memdef]p3
11869 // - If a friend declaration in a non-local class first declares a
11870 // class or function, the friend class or function is a member
11871 // of the innermost enclosing namespace.
11872 // - The name of the friend is not found by simple name lookup
11873 // until a matching declaration is provided in that namespace
11874 // scope (either before or after the class declaration granting
11875 // friendship).
11876 // - If a friend function is called, its name may be found by the
11877 // name lookup that considers functions from namespaces and
11878 // classes associated with the types of the function arguments.
11879 // - When looking for a prior declaration of a class or a function
11880 // declared as a friend, scopes outside the innermost enclosing
11881 // namespace scope are not considered.
11882
John McCallde3fd222010-10-12 23:13:28 +000011883 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011884 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11885 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011886 assert(Name);
11887
Douglas Gregor6c110f32010-12-16 01:14:37 +000011888 // Check for unexpanded parameter packs.
11889 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11890 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11891 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011892 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011893
John McCall07e91c02009-08-06 02:15:43 +000011894 // The context we found the declaration in, or in which we should
11895 // create the declaration.
11896 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011897 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011898 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011899 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011900
Richard Smith114394f2013-08-09 04:35:01 +000011901 // There are five cases here.
11902 // - There's no scope specifier and we're in a local class. Only look
11903 // for functions declared in the immediately-enclosing block scope.
11904 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011905 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011906 if ((SS.isInvalid() || !SS.isSet()) &&
11907 (FunctionContainingLocalClass =
11908 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11909 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011910 // If a friend declaration appears in a local class and the name
11911 // specified is an unqualified name, a prior declaration is
11912 // looked up without considering scopes that are outside the
11913 // innermost enclosing non-class scope. For a friend function
11914 // declaration, if there is no prior declaration, the program is
11915 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011916
11917 // Find the innermost enclosing non-class scope. This is the block
11918 // scope containing the local class definition (or for a nested class,
11919 // the outer local class).
11920 DCScope = S->getFnParent();
11921
11922 // Look up the function name in the scope.
11923 Previous.clear(LookupLocalFriendName);
11924 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11925
11926 if (!Previous.empty()) {
11927 // All possible previous declarations must have the same context:
11928 // either they were declared at block scope or they are members of
11929 // one of the enclosing local classes.
11930 DC = Previous.getRepresentativeDecl()->getDeclContext();
11931 } else {
11932 // This is ill-formed, but provide the context that we would have
11933 // declared the function in, if we were permitted to, for error recovery.
11934 DC = FunctionContainingLocalClass;
11935 }
Richard Smith541b38b2013-09-20 01:15:31 +000011936 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011937
11938 // C++ [class.friend]p6:
11939 // A function can be defined in a friend declaration of a class if and
11940 // only if the class is a non-local class (9.8), the function name is
11941 // unqualified, and the function has namespace scope.
11942 if (D.isFunctionDefinition()) {
11943 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11944 }
11945
11946 // - There's no scope specifier, in which case we just go to the
11947 // appropriate scope and look for a function or function template
11948 // there as appropriate.
11949 } else if (SS.isInvalid() || !SS.isSet()) {
11950 // C++11 [namespace.memdef]p3:
11951 // If the name in a friend declaration is neither qualified nor
11952 // a template-id and the declaration is a function or an
11953 // elaborated-type-specifier, the lookup to determine whether
11954 // the entity has been previously declared shall not consider
11955 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011956 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011957
John McCallf7cfb222010-10-13 05:45:15 +000011958 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011959 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011960
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011961 // Skip class contexts. If someone can cite chapter and verse
11962 // for this behavior, that would be nice --- it's what GCC and
11963 // EDG do, and it seems like a reasonable intent, but the spec
11964 // really only says that checks for unqualified existing
11965 // declarations should stop at the nearest enclosing namespace,
11966 // not that they should only consider the nearest enclosing
11967 // namespace.
11968 while (DC->isRecord())
11969 DC = DC->getParent();
11970
11971 DeclContext *LookupDC = DC;
11972 while (LookupDC->isTransparentContext())
11973 LookupDC = LookupDC->getParent();
11974
11975 while (true) {
11976 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011977
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011978 if (!Previous.empty()) {
11979 DC = LookupDC;
11980 break;
John McCallf4776592010-10-14 22:22:28 +000011981 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011982
11983 if (isTemplateId) {
11984 if (isa<TranslationUnitDecl>(LookupDC)) break;
11985 } else {
11986 if (LookupDC->isFileContext()) break;
11987 }
11988 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011989 }
11990
John McCallccbc0322010-10-13 06:22:15 +000011991 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011992
John McCallde3fd222010-10-12 23:13:28 +000011993 // - There's a non-dependent scope specifier, in which case we
11994 // compute it and do a previous lookup there for a function
11995 // or function template.
11996 } else if (!SS.getScopeRep()->isDependent()) {
11997 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000011998 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000011999
Craig Topperc3ec1492014-05-26 06:22:03 +000012000 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012001
12002 LookupQualifiedName(Previous, DC);
12003
12004 // Ignore things found implicitly in the wrong scope.
12005 // TODO: better diagnostics for this case. Suggesting the right
12006 // qualified scope would be nice...
12007 LookupResult::Filter F = Previous.makeFilter();
12008 while (F.hasNext()) {
12009 NamedDecl *D = F.next();
12010 if (!DC->InEnclosingNamespaceSetOf(
12011 D->getDeclContext()->getRedeclContext()))
12012 F.erase();
12013 }
12014 F.done();
12015
12016 if (Previous.empty()) {
12017 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012018 Diag(Loc, diag::err_qualified_friend_not_found)
12019 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012020 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012021 }
12022
12023 // C++ [class.friend]p1: A friend of a class is a function or
12024 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012025 if (DC->Equals(CurContext))
12026 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012027 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012028 diag::warn_cxx98_compat_friend_is_member :
12029 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012030
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012031 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012032 // C++ [class.friend]p6:
12033 // A function can be defined in a friend declaration of a class if and
12034 // only if the class is a non-local class (9.8), the function name is
12035 // unqualified, and the function has namespace scope.
12036 SemaDiagnosticBuilder DB
12037 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12038
12039 DB << SS.getScopeRep();
12040 if (DC->isFileContext())
12041 DB << FixItHint::CreateRemoval(SS.getRange());
12042 SS.clear();
12043 }
John McCallde3fd222010-10-12 23:13:28 +000012044
12045 // - There's a scope specifier that does not match any template
12046 // parameter lists, in which case we use some arbitrary context,
12047 // create a method or method template, and wait for instantiation.
12048 // - There's a scope specifier that does match some template
12049 // parameter lists, which we don't handle right now.
12050 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012051 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012052 // C++ [class.friend]p6:
12053 // A function can be defined in a friend declaration of a class if and
12054 // only if the class is a non-local class (9.8), the function name is
12055 // unqualified, and the function has namespace scope.
12056 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12057 << SS.getScopeRep();
12058 }
12059
John McCallde3fd222010-10-12 23:13:28 +000012060 DC = CurContext;
12061 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012062 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012063
John McCallf7cfb222010-10-13 05:45:15 +000012064 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012065 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012066 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12067 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12068 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012069 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012070 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12071 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012072 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012073 }
John McCall07e91c02009-08-06 02:15:43 +000012074 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012075
Douglas Gregordd847ba2011-11-03 16:37:14 +000012076 // FIXME: This is an egregious hack to cope with cases where the scope stack
12077 // does not contain the declaration context, i.e., in an out-of-line
12078 // definition of a class.
12079 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12080 if (!DCScope) {
12081 FakeDCScope.setEntity(DC);
12082 DCScope = &FakeDCScope;
12083 }
Richard Smith114394f2013-08-09 04:35:01 +000012084
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012085 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012086 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012087 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012088 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012089
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012090 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012091
Richard Smith114394f2013-08-09 04:35:01 +000012092 // If we performed typo correction, we might have added a scope specifier
12093 // and changed the decl context.
12094 DC = ND->getDeclContext();
12095
John McCall759e32b2009-08-31 22:39:49 +000012096 // Add the function declaration to the appropriate lookup tables,
12097 // adjusting the redeclarations list as necessary. We don't
12098 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012099 //
John McCall759e32b2009-08-31 22:39:49 +000012100 // Also update the scope-based lookup if the target context's
12101 // lookup context is in lexical scope.
12102 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012103 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012104 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012105 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012106 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012107 }
John McCallaa74a0c2009-08-28 07:59:38 +000012108
12109 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012110 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012111 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012112 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012113 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012114
John McCalla0a96892012-08-10 03:15:35 +000012115 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012116 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012117 } else {
12118 if (DC->isRecord()) CheckFriendAccess(ND);
12119
John McCall2c2eb122010-10-16 06:59:13 +000012120 FunctionDecl *FD;
12121 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12122 FD = FTD->getTemplatedDecl();
12123 else
12124 FD = cast<FunctionDecl>(ND);
12125
David Majnemer502b0ed2013-06-25 23:09:30 +000012126 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12127 // default argument expression, that declaration shall be a definition
12128 // and shall be the only declaration of the function or function
12129 // template in the translation unit.
12130 if (functionDeclHasDefaultArgument(FD)) {
12131 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12132 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12133 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12134 } else if (!D.isFunctionDefinition())
12135 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12136 }
12137
John McCall2c2eb122010-10-16 06:59:13 +000012138 // Mark templated-scope function declarations as unsupported.
12139 if (FD->getNumTemplateParameterLists())
12140 FrD->setUnsupportedFriend(true);
12141 }
John McCallde3fd222010-10-12 23:13:28 +000012142
John McCall48871652010-08-21 09:40:31 +000012143 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012144}
12145
John McCall48871652010-08-21 09:40:31 +000012146void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12147 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012148
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012149 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012150 if (!Fn) {
12151 Diag(DelLoc, diag::err_deleted_non_function);
12152 return;
12153 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012154
Douglas Gregorec9fd132012-01-14 16:38:05 +000012155 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012156 // Don't consider the implicit declaration we generate for explicit
12157 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012158 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12159 Prev->getPreviousDecl()) &&
12160 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012161 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012162 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12163 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12164 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012165 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012166 // If the declaration wasn't the first, we delete the function anyway for
12167 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012168 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012169 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012170
Nico Rieck9de0a572014-05-29 16:51:19 +000012171 // dllimport/dllexport cannot be deleted.
12172 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12173 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12174 Fn->setInvalidDecl();
12175 }
12176
Richard Smithb4d2a152013-04-02 19:38:47 +000012177 if (Fn->isDeleted())
12178 return;
12179
12180 // See if we're deleting a function which is already known to override a
12181 // non-deleted virtual function.
12182 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12183 bool IssuedDiagnostic = false;
12184 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12185 E = MD->end_overridden_methods();
12186 I != E; ++I) {
12187 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12188 if (!IssuedDiagnostic) {
12189 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12190 IssuedDiagnostic = true;
12191 }
12192 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12193 }
12194 }
12195 }
12196
Richard Smithb63b6ee2014-01-22 01:43:19 +000012197 // C++11 [basic.start.main]p3:
12198 // A program that defines main as deleted [...] is ill-formed.
12199 if (Fn->isMain())
12200 Diag(DelLoc, diag::err_deleted_main);
12201
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012202 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012203}
Sebastian Redl4c018662009-04-27 21:33:24 +000012204
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012205void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012206 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012207
12208 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012209 if (MD->getParent()->isDependentType()) {
12210 MD->setDefaulted();
12211 MD->setExplicitlyDefaulted();
12212 return;
12213 }
12214
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012215 CXXSpecialMember Member = getSpecialMember(MD);
12216 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012217 if (!MD->isInvalidDecl())
12218 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012219 return;
12220 }
12221
12222 MD->setDefaulted();
12223 MD->setExplicitlyDefaulted();
12224
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012225 // If this definition appears within the record, do the checking when
12226 // the record is complete.
12227 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012228 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012229 // Find the uninstantiated declaration that actually had the '= default'
12230 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012231 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012232
Richard Smith3901dfe2013-03-27 00:22:47 +000012233 // If the method was defaulted on its first declaration, we will have
12234 // already performed the checking in CheckCompletedCXXClass. Such a
12235 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012236 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012237 return;
12238
Richard Smithd3b5c9082012-07-27 04:22:15 +000012239 CheckExplicitlyDefaultedSpecialMember(MD);
12240
Richard Smithbd305122012-12-11 01:14:52 +000012241 // The exception specification is needed because we are defining the
12242 // function.
12243 ResolveExceptionSpec(DefaultLoc,
12244 MD->getType()->castAs<FunctionProtoType>());
12245
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012246 if (MD->isInvalidDecl())
12247 return;
12248
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012249 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012250 case CXXDefaultConstructor:
12251 DefineImplicitDefaultConstructor(DefaultLoc,
12252 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012253 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012254 case CXXCopyConstructor:
12255 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012256 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012257 case CXXCopyAssignment:
12258 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012259 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012260 case CXXDestructor:
12261 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012262 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012263 case CXXMoveConstructor:
12264 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012265 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012266 case CXXMoveAssignment:
12267 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012268 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012269 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012270 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012271 }
12272 } else {
12273 Diag(DefaultLoc, diag::err_default_special_members);
12274 }
12275}
12276
Sebastian Redl4c018662009-04-27 21:33:24 +000012277static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012278 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012279 Stmt *SubStmt = *CI;
12280 if (!SubStmt)
12281 continue;
12282 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012283 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012284 diag::err_return_in_constructor_handler);
12285 if (!isa<Expr>(SubStmt))
12286 SearchForReturnInStmt(Self, SubStmt);
12287 }
12288}
12289
12290void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12291 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12292 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12293 SearchForReturnInStmt(*this, Handler);
12294 }
12295}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012296
David Blaikie68f71a32013-01-18 23:03:15 +000012297bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012298 const CXXMethodDecl *Old) {
12299 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12300 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12301
12302 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12303
12304 // If the calling conventions match, everything is fine
12305 if (NewCC == OldCC)
12306 return false;
12307
Hans Wennborg2545efe2013-12-11 17:42:11 +000012308 // If the calling conventions mismatch because the new function is static,
12309 // suppress the calling convention mismatch error; the error about static
12310 // function override (err_static_overrides_virtual from
12311 // Sema::CheckFunctionDeclaration) is more clear.
12312 if (New->getStorageClass() == SC_Static)
12313 return false;
12314
Reid Kleckner78af0702013-08-27 23:08:25 +000012315 Diag(New->getLocation(),
12316 diag::err_conflicting_overriding_cc_attributes)
12317 << New->getDeclName() << New->getType() << Old->getType();
12318 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12319 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012320}
12321
Mike Stump11289f42009-09-09 15:08:12 +000012322bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012323 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012324 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12325 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012326
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012327 if (Context.hasSameType(NewTy, OldTy) ||
12328 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012329 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012330
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012331 // Check if the return types are covariant
12332 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012333
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012334 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012335 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12336 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012337 NewClassTy = NewPT->getPointeeType();
12338 OldClassTy = OldPT->getPointeeType();
12339 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012340 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12341 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12342 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12343 NewClassTy = NewRT->getPointeeType();
12344 OldClassTy = OldRT->getPointeeType();
12345 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012346 }
12347 }
Mike Stump11289f42009-09-09 15:08:12 +000012348
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012349 // The return types aren't either both pointers or references to a class type.
12350 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012351 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012352 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012353 << New->getDeclName() << NewTy << OldTy
12354 << New->getReturnTypeSourceRange();
12355 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12356 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012357
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012358 return true;
12359 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012360
Anders Carlssone60365b2009-12-31 18:34:24 +000012361 // C++ [class.virtual]p6:
12362 // If the return type of D::f differs from the return type of B::f, the
12363 // class type in the return type of D::f shall be complete at the point of
12364 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012365 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12366 if (!RT->isBeingDefined() &&
12367 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012368 diag::err_covariant_return_incomplete,
12369 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012370 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012371 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012372
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012373 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012374 // Check if the new class derives from the old class.
12375 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012376 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12377 << New->getDeclName() << NewTy << OldTy
12378 << New->getReturnTypeSourceRange();
12379 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12380 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012381 return true;
12382 }
Mike Stump11289f42009-09-09 15:08:12 +000012383
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012384 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012385 if (CheckDerivedToBaseConversion(
12386 NewClassTy, OldClassTy,
12387 diag::err_covariant_return_inaccessible_base,
12388 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12389 New->getLocation(), New->getReturnTypeSourceRange(),
12390 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012391 // FIXME: this note won't trigger for delayed access control
12392 // diagnostics, and it's impossible to get an undelayed error
12393 // here from access control during the original parse because
12394 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012395 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12396 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012397 return true;
12398 }
12399 }
Mike Stump11289f42009-09-09 15:08:12 +000012400
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012401 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012402 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012403 Diag(New->getLocation(),
12404 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012405 << New->getDeclName() << NewTy << OldTy
12406 << New->getReturnTypeSourceRange();
12407 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12408 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012409 return true;
12410 };
Mike Stump11289f42009-09-09 15:08:12 +000012411
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012412
12413 // The new class type must have the same or less qualifiers as the old type.
12414 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12415 Diag(New->getLocation(),
12416 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012417 << New->getDeclName() << NewTy << OldTy
12418 << New->getReturnTypeSourceRange();
12419 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12420 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012421 return true;
12422 };
Mike Stump11289f42009-09-09 15:08:12 +000012423
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012424 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012425}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012426
Douglas Gregor21920e372009-12-01 17:24:26 +000012427/// \brief Mark the given method pure.
12428///
12429/// \param Method the method to be marked pure.
12430///
12431/// \param InitRange the source range that covers the "0" initializer.
12432bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012433 SourceLocation EndLoc = InitRange.getEnd();
12434 if (EndLoc.isValid())
12435 Method->setRangeEnd(EndLoc);
12436
Douglas Gregor21920e372009-12-01 17:24:26 +000012437 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12438 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012439 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012440 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012441
12442 if (!Method->isInvalidDecl())
12443 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12444 << Method->getDeclName() << InitRange;
12445 return true;
12446}
12447
Douglas Gregor926410d2012-02-21 02:22:07 +000012448/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012449static bool isStaticDataMember(const Decl *D) {
12450 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12451 return Var->isStaticDataMember();
12452
12453 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012454}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012455
John McCall1f4ee7b2009-12-19 09:28:58 +000012456/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12457/// an initializer for the out-of-line declaration 'Dcl'. The scope
12458/// is a fresh scope pushed for just this purpose.
12459///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012460/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12461/// static data member of class X, names should be looked up in the scope of
12462/// class X.
John McCall48871652010-08-21 09:40:31 +000012463void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012464 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012465 if (!D || D->isInvalidDecl())
12466 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012467
Richard Smitha2302242013-12-05 07:51:02 +000012468 // We will always have a nested name specifier here, but this declaration
12469 // might not be out of line if the specifier names the current namespace:
12470 // extern int n;
12471 // int ::n = 0;
12472 if (D->isOutOfLine())
12473 EnterDeclaratorContext(S, D->getDeclContext());
12474
Douglas Gregor926410d2012-02-21 02:22:07 +000012475 // If we are parsing the initializer for a static data member, push a
12476 // new expression evaluation context that is associated with this static
12477 // data member.
12478 if (isStaticDataMember(D))
12479 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012480}
12481
12482/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012483/// initializer for the out-of-line declaration 'D'.
12484void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012485 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012486 if (!D || D->isInvalidDecl())
12487 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012488
Douglas Gregor926410d2012-02-21 02:22:07 +000012489 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012490 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012491
Richard Smitha2302242013-12-05 07:51:02 +000012492 if (D->isOutOfLine())
12493 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012494}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012495
12496/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12497/// C++ if/switch/while/for statement.
12498/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012499DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012500 // C++ 6.4p2:
12501 // The declarator shall not specify a function or an array.
12502 // The type-specifier-seq shall not contain typedef and shall not declare a
12503 // new class or enumeration.
12504 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12505 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012506
12507 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012508 if (!Dcl)
12509 return true;
12510
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012511 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12512 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012513 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012514 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012515 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012516
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012517 return Dcl;
12518}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012519
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012520void Sema::LoadExternalVTableUses() {
12521 if (!ExternalSource)
12522 return;
12523
12524 SmallVector<ExternalVTableUse, 4> VTables;
12525 ExternalSource->ReadUsedVTables(VTables);
12526 SmallVector<VTableUse, 4> NewUses;
12527 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12528 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12529 = VTablesUsed.find(VTables[I].Record);
12530 // Even if a definition wasn't required before, it may be required now.
12531 if (Pos != VTablesUsed.end()) {
12532 if (!Pos->second && VTables[I].DefinitionRequired)
12533 Pos->second = true;
12534 continue;
12535 }
12536
12537 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12538 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12539 }
12540
12541 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12542}
12543
Douglas Gregor88d292c2010-05-13 16:44:06 +000012544void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12545 bool DefinitionRequired) {
12546 // Ignore any vtable uses in unevaluated operands or for classes that do
12547 // not have a vtable.
12548 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012549 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012550 return;
12551
Douglas Gregor88d292c2010-05-13 16:44:06 +000012552 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012553 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012554 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12555 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12556 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12557 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012558 // If we already had an entry, check to see if we are promoting this vtable
12559 // to required a definition. If so, we need to reappend to the VTableUses
12560 // list, since we may have already processed the first entry.
12561 if (DefinitionRequired && !Pos.first->second) {
12562 Pos.first->second = true;
12563 } else {
12564 // Otherwise, we can early exit.
12565 return;
12566 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012567 } else {
12568 // The Microsoft ABI requires that we perform the destructor body
12569 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12570 // the deleting destructor is emitted with the vtable, not with the
12571 // destructor definition as in the Itanium ABI.
12572 // If it has a definition, we do the check at that point instead.
12573 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12574 Class->hasUserDeclaredDestructor() &&
12575 !Class->getDestructor()->isDefined() &&
12576 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012577 CXXDestructorDecl *DD = Class->getDestructor();
12578 ContextRAII SavedContext(*this, DD);
12579 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012580 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012581 }
12582
12583 // Local classes need to have their virtual members marked
12584 // immediately. For all other classes, we mark their virtual members
12585 // at the end of the translation unit.
12586 if (Class->isLocalClass())
12587 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012588 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012589 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012590}
12591
Douglas Gregor88d292c2010-05-13 16:44:06 +000012592bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012593 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012594 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012595 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012596
Douglas Gregor88d292c2010-05-13 16:44:06 +000012597 // Note: The VTableUses vector could grow as a result of marking
12598 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012599 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012600 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012601 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012602 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012603 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012604 if (!Class)
12605 continue;
12606
12607 SourceLocation Loc = VTableUses[I].second;
12608
Richard Smithd3b5c9082012-07-27 04:22:15 +000012609 bool DefineVTable = true;
12610
Douglas Gregor88d292c2010-05-13 16:44:06 +000012611 // If this class has a key function, but that key function is
12612 // defined in another translation unit, we don't need to emit the
12613 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012614 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012615 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012616 // The key function is in another translation unit.
12617 DefineVTable = false;
12618 TemplateSpecializationKind TSK =
12619 KeyFunction->getTemplateSpecializationKind();
12620 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12621 TSK != TSK_ImplicitInstantiation &&
12622 "Instantiations don't have key functions");
12623 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012624 } else if (!KeyFunction) {
12625 // If we have a class with no key function that is the subject
12626 // of an explicit instantiation declaration, suppress the
12627 // vtable; it will live with the explicit instantiation
12628 // definition.
12629 bool IsExplicitInstantiationDeclaration
12630 = Class->getTemplateSpecializationKind()
12631 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012632 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012633 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012634 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012635 if (TSK == TSK_ExplicitInstantiationDeclaration)
12636 IsExplicitInstantiationDeclaration = true;
12637 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12638 IsExplicitInstantiationDeclaration = false;
12639 break;
12640 }
12641 }
12642
12643 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012644 DefineVTable = false;
12645 }
12646
12647 // The exception specifications for all virtual members may be needed even
12648 // if we are not providing an authoritative form of the vtable in this TU.
12649 // We may choose to emit it available_externally anyway.
12650 if (!DefineVTable) {
12651 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12652 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012653 }
12654
12655 // Mark all of the virtual members of this class as referenced, so
12656 // that we can build a vtable. Then, tell the AST consumer that a
12657 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012658 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012659 MarkVirtualMembersReferenced(Loc, Class);
12660 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12661 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12662
12663 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012664 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012665 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012666 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012667 if (!KeyFunction ||
12668 (KeyFunction->hasBody(KeyFunctionDef) &&
12669 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012670 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12671 TSK_ExplicitInstantiationDefinition
12672 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12673 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012674 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012675 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012676 VTableUses.clear();
12677
Douglas Gregor97509692011-04-22 22:25:37 +000012678 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012679}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012680
Richard Smithd3b5c9082012-07-27 04:22:15 +000012681void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12682 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012683 for (const auto *I : RD->methods())
12684 if (I->isVirtual() && !I->isPure())
12685 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012686}
12687
Rafael Espindola5b334082010-03-26 00:36:59 +000012688void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12689 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012690 // Mark all functions which will appear in RD's vtable as used.
12691 CXXFinalOverriderMap FinalOverriders;
12692 RD->getFinalOverriders(FinalOverriders);
12693 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12694 E = FinalOverriders.end();
12695 I != E; ++I) {
12696 for (OverridingMethods::const_iterator OI = I->second.begin(),
12697 OE = I->second.end();
12698 OI != OE; ++OI) {
12699 assert(OI->second.size() > 0 && "no final overrider");
12700 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012701
Richard Smith4ff9ff92012-07-07 06:59:51 +000012702 // C++ [basic.def.odr]p2:
12703 // [...] A virtual member function is used if it is not pure. [...]
12704 if (!Overrider->isPure())
12705 MarkFunctionReferenced(Loc, Overrider);
12706 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012707 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012708
12709 // Only classes that have virtual bases need a VTT.
12710 if (RD->getNumVBases() == 0)
12711 return;
12712
Aaron Ballman574705e2014-03-13 15:41:46 +000012713 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012714 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012715 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012716 if (Base->getNumVBases() == 0)
12717 continue;
12718 MarkVirtualMembersReferenced(Loc, Base);
12719 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012720}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012721
12722/// SetIvarInitializers - This routine builds initialization ASTs for the
12723/// Objective-C implementation whose ivars need be initialized.
12724void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012725 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012726 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012727 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012728 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012729 CollectIvarsToConstructOrDestruct(OID, ivars);
12730 if (ivars.empty())
12731 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012732 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012733 for (unsigned i = 0; i < ivars.size(); i++) {
12734 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012735 if (Field->isInvalidDecl())
12736 continue;
12737
Alexis Hunt1d792652011-01-08 20:30:50 +000012738 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012739 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12740 InitializationKind InitKind =
12741 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012742
12743 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12744 ExprResult MemberInit =
12745 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012746 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012747 // Note, MemberInit could actually come back empty if no initialization
12748 // is required (e.g., because it would call a trivial default constructor)
12749 if (!MemberInit.get() || MemberInit.isInvalid())
12750 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012751
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012752 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012753 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12754 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012755 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012756 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012757 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012758
12759 // Be sure that the destructor is accessible and is marked as referenced.
12760 if (const RecordType *RecordTy
12761 = Context.getBaseElementType(Field->getType())
12762 ->getAs<RecordType>()) {
12763 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012764 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012765 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012766 CheckDestructorAccess(Field->getLocation(), Destructor,
12767 PDiag(diag::err_access_dtor_ivar)
12768 << Context.getBaseElementType(Field->getType()));
12769 }
12770 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012771 }
12772 ObjCImplementation->setIvarInitializers(Context,
12773 AllToInit.data(), AllToInit.size());
12774 }
12775}
Alexis Hunt6118d662011-05-04 05:57:24 +000012776
Alexis Hunt27a761d2011-05-04 23:29:54 +000012777static
12778void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12779 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12780 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12781 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12782 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012783 if (Ctor->isInvalidDecl())
12784 return;
12785
Richard Smith802c4b72012-08-23 06:16:52 +000012786 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12787
12788 // Target may not be determinable yet, for instance if this is a dependent
12789 // call in an uninstantiated template.
12790 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012791 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012792 (void)Target->hasBody(FNTarget);
12793 Target = const_cast<CXXConstructorDecl*>(
12794 cast_or_null<CXXConstructorDecl>(FNTarget));
12795 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012796
12797 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12798 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012799 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012800
12801 if (!Current.insert(Canonical))
12802 return;
12803
12804 // We know that beyond here, we aren't chaining into a cycle.
12805 if (!Target || !Target->isDelegatingConstructor() ||
12806 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012807 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012808 Current.clear();
12809 // We've hit a cycle.
12810 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12811 Current.count(TCanonical)) {
12812 // If we haven't diagnosed this cycle yet, do so now.
12813 if (!Invalid.count(TCanonical)) {
12814 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012815 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012816 << Ctor;
12817
Richard Smith802c4b72012-08-23 06:16:52 +000012818 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012819 if (TCanonical != Canonical)
12820 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12821
12822 CXXConstructorDecl *C = Target;
12823 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012824 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012825 (void)C->getTargetConstructor()->hasBody(FNTarget);
12826 assert(FNTarget && "Ctor cycle through bodiless function");
12827
Richard Smith802c4b72012-08-23 06:16:52 +000012828 C = const_cast<CXXConstructorDecl*>(
12829 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012830 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12831 }
12832 }
12833
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012834 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012835 Current.clear();
12836 } else {
12837 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12838 }
12839}
12840
12841
Alexis Hunt6118d662011-05-04 05:57:24 +000012842void Sema::CheckDelegatingCtorCycles() {
12843 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12844
Douglas Gregorbae31202011-07-27 21:57:17 +000012845 for (DelegatingCtorDeclsType::iterator
12846 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012847 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012848 I != E; ++I)
12849 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012850
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012851 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12852 CE = Invalid.end();
12853 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012854 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012855}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012856
Douglas Gregor3024f072012-04-16 07:05:22 +000012857namespace {
12858 /// \brief AST visitor that finds references to the 'this' expression.
12859 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12860 Sema &S;
12861
12862 public:
12863 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12864
12865 bool VisitCXXThisExpr(CXXThisExpr *E) {
12866 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12867 << E->isImplicit();
12868 return false;
12869 }
12870 };
12871}
12872
12873bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12874 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12875 if (!TSInfo)
12876 return false;
12877
12878 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012879 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012880 if (!ProtoTL)
12881 return false;
12882
12883 // C++11 [expr.prim.general]p3:
12884 // [The expression this] shall not appear before the optional
12885 // cv-qualifier-seq and it shall not appear within the declaration of a
12886 // static member function (although its type and value category are defined
12887 // within a static member function as they are within a non-static member
12888 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012889 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012890 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012891 FindCXXThisExpr Finder(*this);
12892
12893 // If the return type came after the cv-qualifier-seq, check it now.
12894 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012895 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012896 return true;
12897
12898 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012899 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12900 return true;
12901
12902 return checkThisInStaticMemberFunctionAttributes(Method);
12903}
12904
12905bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12906 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12907 if (!TSInfo)
12908 return false;
12909
12910 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012911 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012912 if (!ProtoTL)
12913 return false;
12914
David Blaikie6adc78e2013-02-18 22:06:02 +000012915 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012916 FindCXXThisExpr Finder(*this);
12917
Douglas Gregor3024f072012-04-16 07:05:22 +000012918 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012919 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012920 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012921 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012922 case EST_DynamicNone:
12923 case EST_MSAny:
12924 case EST_None:
12925 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012926
Douglas Gregor3024f072012-04-16 07:05:22 +000012927 case EST_ComputedNoexcept:
12928 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12929 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012930
Douglas Gregor3024f072012-04-16 07:05:22 +000012931 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012932 for (const auto &E : Proto->exceptions()) {
12933 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012934 return true;
12935 }
12936 break;
12937 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012938
12939 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012940}
12941
12942bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12943 FindCXXThisExpr Finder(*this);
12944
12945 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012946 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012947 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000012948 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000012949 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012950 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012951 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012952 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012953 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012954 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012955 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012956 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012957 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012958 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012959 Arg = ETLF->getSuccessValue();
12960 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012961 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012962 Arg = STLF->getSuccessValue();
12963 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012964 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012965 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012966 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012967 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012968 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012969 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012970 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012971 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012972 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12973 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12974 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012975 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012976
12977 if (Arg && !Finder.TraverseStmt(Arg))
12978 return true;
12979
12980 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12981 if (!Finder.TraverseStmt(Args[I]))
12982 return true;
12983 }
12984 }
12985
12986 return false;
12987}
12988
Douglas Gregor433e0532012-04-16 18:27:27 +000012989void
12990Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12991 ArrayRef<ParsedType> DynamicExceptions,
12992 ArrayRef<SourceRange> DynamicExceptionRanges,
12993 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012994 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +000012995 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000012996 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000012997 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000012998 if (EST == EST_Dynamic) {
12999 Exceptions.reserve(DynamicExceptions.size());
13000 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13001 // FIXME: Preserve type source info.
13002 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13003
13004 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13005 collectUnexpandedParameterPacks(ET, Unexpanded);
13006 if (!Unexpanded.empty()) {
13007 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13008 UPPC_ExceptionType,
13009 Unexpanded);
13010 continue;
13011 }
13012
13013 // Check that the type is valid for an exception spec, and
13014 // drop it if not.
13015 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13016 Exceptions.push_back(ET);
13017 }
Richard Smith8acb4282014-07-31 21:57:55 +000013018 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013019 return;
13020 }
Richard Smith8acb4282014-07-31 21:57:55 +000013021
Douglas Gregor433e0532012-04-16 18:27:27 +000013022 if (EST == EST_ComputedNoexcept) {
13023 // If an error occurred, there's no expression here.
13024 if (NoexceptExpr) {
13025 assert((NoexceptExpr->isTypeDependent() ||
13026 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13027 Context.BoolTy) &&
13028 "Parser should have made sure that the expression is boolean");
13029 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013030 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013031 return;
13032 }
Richard Smith8acb4282014-07-31 21:57:55 +000013033
Douglas Gregor433e0532012-04-16 18:27:27 +000013034 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013035 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013036 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013037 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013038 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013039 }
13040 return;
13041 }
13042}
13043
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013044/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13045Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13046 // Implicitly declared functions (e.g. copy constructors) are
13047 // __host__ __device__
13048 if (D->isImplicit())
13049 return CFT_HostDevice;
13050
13051 if (D->hasAttr<CUDAGlobalAttr>())
13052 return CFT_Global;
13053
13054 if (D->hasAttr<CUDADeviceAttr>()) {
13055 if (D->hasAttr<CUDAHostAttr>())
13056 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013057 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013058 }
13059
13060 return CFT_Host;
13061}
13062
13063bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13064 CUDAFunctionTarget CalleeTarget) {
13065 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13066 // Callable from the device only."
13067 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13068 return true;
13069
13070 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13071 // Callable from the host only."
13072 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13073 // Callable from the host only."
13074 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13075 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13076 return true;
13077
13078 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13079 return true;
13080
13081 return false;
13082}
John McCall5e77d762013-04-16 07:28:30 +000013083
13084/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13085///
13086MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13087 SourceLocation DeclStart,
13088 Declarator &D, Expr *BitWidth,
13089 InClassInitStyle InitStyle,
13090 AccessSpecifier AS,
13091 AttributeList *MSPropertyAttr) {
13092 IdentifierInfo *II = D.getIdentifier();
13093 if (!II) {
13094 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013095 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013096 }
13097 SourceLocation Loc = D.getIdentifierLoc();
13098
13099 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13100 QualType T = TInfo->getType();
13101 if (getLangOpts().CPlusPlus) {
13102 CheckExtraCXXDefaultArguments(D);
13103
13104 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13105 UPPC_DataMemberType)) {
13106 D.setInvalidType();
13107 T = Context.IntTy;
13108 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13109 }
13110 }
13111
13112 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13113
13114 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13115 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13116 diag::err_invalid_thread)
13117 << DeclSpec::getSpecifierName(TSCS);
13118
13119 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013120 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013121 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13122 LookupName(Previous, S);
13123 switch (Previous.getResultKind()) {
13124 case LookupResult::Found:
13125 case LookupResult::FoundUnresolvedValue:
13126 PrevDecl = Previous.getAsSingle<NamedDecl>();
13127 break;
13128
13129 case LookupResult::FoundOverloaded:
13130 PrevDecl = Previous.getRepresentativeDecl();
13131 break;
13132
13133 case LookupResult::NotFound:
13134 case LookupResult::NotFoundInCurrentInstantiation:
13135 case LookupResult::Ambiguous:
13136 break;
13137 }
13138
13139 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13140 // Maybe we will complain about the shadowed template parameter.
13141 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13142 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013143 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013144 }
13145
13146 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013147 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013148
13149 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013150 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013151 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13152 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013153 ProcessDeclAttributes(TUScope, NewPD, D);
13154 NewPD->setAccess(AS);
13155
13156 if (NewPD->isInvalidDecl())
13157 Record->setInvalidDecl();
13158
13159 if (D.getDeclSpec().isModulePrivateSpecified())
13160 NewPD->setModulePrivate();
13161
13162 if (NewPD->isInvalidDecl() && PrevDecl) {
13163 // Don't introduce NewFD into scope; there's already something
13164 // with the same name in the same scope.
13165 } else if (II) {
13166 PushOnScopeChains(NewPD, S);
13167 } else
13168 Record->addDecl(NewPD);
13169
13170 return NewPD;
13171}