blob: ef4f8dd4e6a715564b01181734645db5c16ad69a [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"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 for (const auto &E : Proto->exceptions())
216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
217 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000218}
219
Richard Smith938f40b2011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithf623c962012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssonc80a1272009-08-25 02:29:20 +0000249bool
John McCallb268a282010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssonc80a1272009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000271 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000273
Richard Smithc406cb72013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Anders Carlssonc80a1272009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Douglas Gregor758cb672010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000292 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000293}
294
Chris Lattner58258242008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000298void
John McCall48871652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner199abbc2008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlssonf1c26952009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump11289f42009-09-09 15:08:12 +0000327
John McCallb268a282010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000329}
330
Douglas Gregor58354032008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCall48871652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000344}
345
Douglas Gregor4d87df52008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000348void Sema::ActOnParamDefaultArgumentError(Decl *param) {
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);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000355}
356
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000357/// CheckExtraCXXDefaultArguments - Check for any extra default
358/// arguments in the declarator, which is not a function declaration
359/// or definition and therefore is not permitted to have default
360/// arguments. This routine should be invoked for every declarator
361/// that is not a function declaration or definition.
362void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
363 // C++ [dcl.fct.default]p3
364 // A default argument expression shall be specified only in the
365 // parameter-declaration-clause of a function declaration or in a
366 // template-parameter (14.1). It shall not be specified for a
367 // parameter pack. If it is specified in a
368 // parameter-declaration-clause, it shall not occur within a
369 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000370 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000372 DeclaratorChunk &chunk = D.getTypeObject(i);
373 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 if (MightBeFunction) {
375 // This is a function declaration. It can have default arguments, but
376 // keep looking in case its return type is a function type with default
377 // arguments.
378 MightBeFunction = false;
379 continue;
380 }
Alp Tokerc5350722014-02-26 22:27:52 +0000381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
382 ++argIdx) {
383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000384 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 << SourceRange((*Toks)[1].getLocation(),
388 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000389 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000391 } else if (Param->getDefaultArg()) {
392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
393 << Param->getDefaultArg()->getSourceRange();
394 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000395 }
396 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000397 } else if (chunk.Kind != DeclaratorChunk::Paren) {
398 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
401}
402
David Majnemer502b0ed2013-06-25 23:09:30 +0000403static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
406 if (!PVD->hasDefaultArg())
407 return false;
408 if (!PVD->hasInheritedDefaultArg())
409 return true;
410 }
411 return false;
412}
413
Craig Toppere4794282012-09-21 04:33:26 +0000414/// MergeCXXFunctionDecl - Merge two declarations of the same C++
415/// function, once we already know that they have the same
416/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
417/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000418bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
419 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000420 bool Invalid = false;
421
Chris Lattner199abbc2008-04-08 05:04:30 +0000422 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000423 // For non-template functions, default arguments can be added in
424 // later declarations of a function in the same
425 // scope. Declarations in different scopes have completely
426 // distinct sets of default arguments. That is, declarations in
427 // inner scopes do not acquire default arguments from
428 // declarations in outer scopes, and vice versa. In a given
429 // function declaration, all parameters subsequent to a
430 // parameter with a default argument shall have default
431 // arguments supplied in this or previous declarations. A
432 // default argument shall not be redefined by a later
433 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000434 //
435 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000436 // Except for member functions of class templates, the default arguments
437 // in a member function definition that appears outside of the class
438 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000439 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
441 ParmVarDecl *OldParam = Old->getParamDecl(p);
442 ParmVarDecl *NewParam = New->getParamDecl(p);
443
James Molloye9430032012-03-13 08:55:35 +0000444 bool OldParamHasDfl = OldParam->hasDefaultArg();
445 bool NewParamHasDfl = NewParam->hasDefaultArg();
446
447 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000448
449 // The declaration context corresponding to the scope is the semantic
450 // parent, unless this is a local function declaration, in which case
451 // it is that surrounding function.
452 DeclContext *ScopeDC = New->getLexicalDeclContext();
453 if (!ScopeDC->isFunctionOrMethod())
454 ScopeDC = New->getDeclContext();
455 if (S && !isDeclInScope(ND, ScopeDC, S) &&
456 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000457 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000458 // the same scope and this is not an out-of-line definition of
459 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000460 OldParamHasDfl = false;
461
462 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000463
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000464 unsigned DiagDefaultParamID =
465 diag::err_param_default_argument_redefinition;
466
467 // MSVC accepts that default parameters be redefined for member functions
468 // of template class. The new default parameter's value is ignored.
469 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000470 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
472 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000473 // Merge the old default argument into the new parameter.
474 NewParam->setHasInheritedDefaultArg();
475 if (OldParam->hasUninstantiatedDefaultArg())
476 NewParam->setUninstantiatedDefaultArg(
477 OldParam->getUninstantiatedDefaultArg());
478 else
479 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000481 Invalid = false;
482 }
483 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000484
Francois Pichet8cb243a2011-04-10 04:58:30 +0000485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
486 // hint here. Alternatively, we could walk the type-source information
487 // for NewParam to find the last source location in the type... but it
488 // isn't worth the effort right now. This is the kind of test case that
489 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000490 // int f(int);
491 // void g(int (*fp)(int) = f);
492 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000493 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000494 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495
496 // Look for the function declaration where the default argument was
497 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000498 for (FunctionDecl *Older = Old->getPreviousDecl();
499 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000500 if (!Older->getParamDecl(p)->hasDefaultArg())
501 break;
502
503 OldParam = Older->getParamDecl(p);
504 }
505
506 Diag(OldParam->getLocation(), diag::note_previous_definition)
507 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000508 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000509 // Merge the old default argument into the new parameter.
510 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000511 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000512 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000513 if (OldParam->hasUninstantiatedDefaultArg())
514 NewParam->setUninstantiatedDefaultArg(
515 OldParam->getUninstantiatedDefaultArg());
516 else
John McCalle61b02b2010-05-04 01:53:42 +0000517 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000518 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000519 if (New->getDescribedFunctionTemplate()) {
520 // Paragraph 4, quoted above, only applies to non-template functions.
521 Diag(NewParam->getLocation(),
522 diag::err_param_default_argument_template_redecl)
523 << NewParam->getDefaultArgRange();
524 Diag(Old->getLocation(), diag::note_template_prev_declaration)
525 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000526 } else if (New->getTemplateSpecializationKind()
527 != TSK_ImplicitInstantiation &&
528 New->getTemplateSpecializationKind() != TSK_Undeclared) {
529 // C++ [temp.expr.spec]p21:
530 // Default function arguments shall not be specified in a declaration
531 // or a definition for one of the following explicit specializations:
532 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000533 // - the explicit specialization of a member function template;
534 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000535 // template where the class template specialization to which the
536 // member function specialization belongs is implicitly
537 // instantiated.
538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
540 << New->getDeclName()
541 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000542 } else if (New->getDeclContext()->isDependentContext()) {
543 // C++ [dcl.fct.default]p6 (DR217):
544 // Default arguments for a member function of a class template shall
545 // be specified on the initial declaration of the member function
546 // within the class template.
547 //
548 // Reading the tea leaves a bit in DR217 and its reference to DR205
549 // leads me to the conclusion that one cannot add default function
550 // arguments for an out-of-line definition of a member function of a
551 // dependent type.
552 int WhichKind = 2;
553 if (CXXRecordDecl *Record
554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
555 if (Record->getDescribedClassTemplate())
556 WhichKind = 0;
557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
558 WhichKind = 1;
559 else
560 WhichKind = 2;
561 }
562
563 Diag(NewParam->getLocation(),
564 diag::err_param_default_argument_member_template_redecl)
565 << WhichKind
566 << NewParam->getDefaultArgRange();
567 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000568 }
569 }
570
Richard Smith58c3cc12012-11-28 03:45:24 +0000571 // DR1344: If a default argument is added outside a class definition and that
572 // default argument makes the function a special member function, the program
573 // is ill-formed. This can only happen for constructors.
574 if (isa<CXXConstructorDecl>(New) &&
575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
578 if (NewSM != OldSM) {
579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
580 assert(NewParam->hasDefaultArg());
581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
582 << NewParam->getDefaultArgRange() << NewSM;
583 Diag(Old->getLocation(), diag::note_previous_declaration);
584 }
585 }
586
David Majnemeree4f4022014-03-30 06:44:54 +0000587 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000589 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 if (New->isConstexpr() != Old->isConstexpr()) {
592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
593 << New << New->isConstexpr();
594 Diag(Old->getLocation(), diag::note_previous_declaration);
595 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000596 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
597 // C++11 [dcl.fcn.spec]p4:
598 // If the definition of a function appears in a translation unit before its
599 // first declaration as inline, the program is ill-formed.
600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
601 Diag(Def->getLocation(), diag::note_previous_definition);
602 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000603 }
604
David Majnemer502b0ed2013-06-25 23:09:30 +0000605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000606 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // the only declaration of the function or function template in the
608 // translation unit.
609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
610 functionDeclHasDefaultArgument(Old)) {
611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
612 Diag(Old->getLocation(), diag::note_previous_declaration);
613 Invalid = true;
614 }
615
Douglas Gregorf40863c2010-02-12 07:32:17 +0000616 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000617 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000618
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000619 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000620}
621
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000622/// \brief Merge the exception specifications of two variable declarations.
623///
624/// This is called when there's a redeclaration of a VarDecl. The function
625/// checks if the redeclaration might have an exception specification and
626/// validates compatibility and merges the specs if necessary.
627void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
628 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000629 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000630 return;
631
632 assert(Context.hasSameType(New->getType(), Old->getType()) &&
633 "Should only be called if types are otherwise the same.");
634
635 QualType NewType = New->getType();
636 QualType OldType = Old->getType();
637
638 // We're only interested in pointers and references to functions, as well
639 // as pointers to member functions.
640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
641 NewType = R->getPointeeType();
642 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
643 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
644 NewType = P->getPointeeType();
645 OldType = OldType->getAs<PointerType>()->getPointeeType();
646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
647 NewType = M->getPointeeType();
648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
649 }
650
651 if (!NewType->isFunctionProtoType())
652 return;
653
654 // There's lots of special cases for functions. For function pointers, system
655 // libraries are hopefully not as broken so that we don't need these
656 // workarounds.
657 if (CheckEquivalentExceptionSpec(
658 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
659 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
660 New->setInvalidDecl();
661 }
662}
663
Chris Lattner199abbc2008-04-08 05:04:30 +0000664/// CheckCXXDefaultArguments - Verify that the default arguments for a
665/// function declaration are well-formed according to C++
666/// [dcl.fct.default].
667void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
668 unsigned NumParams = FD->getNumParams();
669 unsigned p;
670
671 // Find first parameter with a default argument
672 for (p = 0; p < NumParams; ++p) {
673 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000674 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000675 break;
676 }
677
678 // C++ [dcl.fct.default]p4:
679 // In a given function declaration, all parameters
680 // subsequent to a parameter with a default argument shall
681 // have default arguments supplied in this or previous
682 // declarations. A default argument shall not be redefined
683 // by a later declaration (not even to the same value).
684 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000685 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000686 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000687 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000688 if (Param->isInvalidDecl())
689 /* We already complained about this parameter. */;
690 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000691 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000692 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000693 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000694 else
Mike Stump11289f42009-09-09 15:08:12 +0000695 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000697
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 LastMissingDefaultArg = p;
699 }
700 }
701
702 if (LastMissingDefaultArg > 0) {
703 // Some default arguments were missing. Clear out all of the
704 // default arguments up to (and including) the last missing
705 // default argument, so that we leave the function parameters
706 // in a semantically valid state.
707 for (p = 0; p <= LastMissingDefaultArg; ++p) {
708 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000709 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000710 Param->setDefaultArg(0);
711 }
712 }
713 }
714}
Douglas Gregor556877c2008-04-13 21:30:24 +0000715
Richard Smitheb3c10c2011-10-01 02:31:28 +0000716// CheckConstexprParameterTypes - Check whether a function's parameter types
717// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000718// diagnostic and return false.
719static bool CheckConstexprParameterTypes(Sema &SemaRef,
720 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000721 unsigned ArgIndex = 0;
722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
724 e = FT->param_type_end();
725 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
727 SourceLocation ParamLoc = PD->getLocation();
728 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000729 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000730 diag::err_constexpr_non_literal_param,
731 ArgIndex+1, PD->getSourceRange(),
732 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000733 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000734 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000735 return true;
736}
737
738/// \brief Get diagnostic %select index for tag kind for
739/// record diagnostic message.
740/// WARNING: Indexes apply to particular diagnostics only!
741///
742/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000743static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000744 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000745 case TTK_Struct: return 0;
746 case TTK_Interface: return 1;
747 case TTK_Class: return 2;
748 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000749 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000750}
751
752// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
753// the requirements of a constexpr function definition or a constexpr
754// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000755// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000756//
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
758bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
760 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000761 // C++11 [dcl.constexpr]p4:
762 // The definition of a constexpr constructor shall satisfy the following
763 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000764 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000765 const CXXRecordDecl *RD = MD->getParent();
766 if (RD->getNumVBases()) {
767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
768 << isa<CXXConstructorDecl>(NewFD)
769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000770 for (const auto &I : RD->vbases())
771 Diag(I.getLocStart(),
772 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000773 return false;
774 }
Richard Smith7971b692012-01-13 04:54:00 +0000775 }
776
777 if (!isa<CXXConstructorDecl>(NewFD)) {
778 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 // The definition of a constexpr function shall satisfy the following
780 // constraints:
781 // - it shall not be virtual;
782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
783 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000785
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 // If it's not obvious why this function is virtual, find an overridden
787 // function which uses the 'virtual' keyword.
788 const CXXMethodDecl *WrittenVirtual = Method;
789 while (!WrittenVirtual->isVirtualAsWritten())
790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
791 if (WrittenVirtual != Method)
792 Diag(WrittenVirtual->getLocation(),
793 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 return false;
795 }
796
797 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000798 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000799 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000800 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000801 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000803 }
804
Richard Smith7971b692012-01-13 04:54:00 +0000805 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000807 return false;
808
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 return true;
810}
811
812/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000813/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000814///
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// \return true if the body is OK (maybe only as an extension), false if we
816/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000818 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
819 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
821 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000822 for (const auto *DclIt : DS->decls()) {
823 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 case Decl::StaticAssert:
825 case Decl::Using:
826 case Decl::UsingShadow:
827 case Decl::UsingDirective:
828 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000829 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000830 // - static_assert-declarations
831 // - using-declarations,
832 // - using-directives,
833 continue;
834
835 case Decl::Typedef:
836 case Decl::TypeAlias: {
837 // - typedef declarations and alias-declarations that do not define
838 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000839 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000840 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
841 // Don't allow variably-modified types in constexpr functions.
842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
844 << TL.getSourceRange() << TL.getType()
845 << isa<CXXConstructorDecl>(Dcl);
846 return false;
847 }
848 continue;
849 }
850
851 case Decl::Enum:
852 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000853 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 SemaRef.Diag(DS->getLocStart(),
856 SemaRef.getLangOpts().CPlusPlus1y
857 ? diag::warn_cxx11_compat_constexpr_type_definition
858 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000859 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000860 continue;
861
Richard Smithd9f663b2013-04-22 15:31:51 +0000862 case Decl::EnumConstant:
863 case Decl::IndirectField:
864 case Decl::ParmVar:
865 // These can only appear with other declarations which are banned in
866 // C++11 and permitted in C++1y, so ignore them.
867 continue;
868
869 case Decl::Var: {
870 // C++1y [dcl.constexpr]p3 allows anything except:
871 // a definition of a variable of non-literal type or of static or
872 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000873 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000874 if (VD->isThisDeclarationADefinition()) {
875 if (VD->isStaticLocal()) {
876 SemaRef.Diag(VD->getLocation(),
877 diag::err_constexpr_local_var_static)
878 << isa<CXXConstructorDecl>(Dcl)
879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
880 return false;
881 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000882 if (!VD->getType()->isDependentType() &&
883 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000884 VD->getLocation(), VD->getType(),
885 diag::err_constexpr_local_var_non_literal_type,
886 isa<CXXConstructorDecl>(Dcl)))
887 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000888 if (!VD->getType()->isDependentType() &&
889 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000890 SemaRef.Diag(VD->getLocation(),
891 diag::err_constexpr_local_var_no_init)
892 << isa<CXXConstructorDecl>(Dcl);
893 return false;
894 }
895 }
896 SemaRef.Diag(VD->getLocation(),
897 SemaRef.getLangOpts().CPlusPlus1y
898 ? diag::warn_cxx11_compat_constexpr_local_var
899 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000900 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 continue;
902 }
903
904 case Decl::NamespaceAlias:
905 case Decl::Function:
906 // These are disallowed in C++11 and permitted in C++1y. Allow them
907 // everywhere as an extension.
908 if (!Cxx1yLoc.isValid())
909 Cxx1yLoc = DS->getLocStart();
910 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000911
912 default:
913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
914 << isa<CXXConstructorDecl>(Dcl);
915 return false;
916 }
917 }
918
919 return true;
920}
921
922/// Check that the given field is initialized within a constexpr constructor.
923///
924/// \param Dcl The constexpr constructor being checked.
925/// \param Field The field being checked. This may be a member of an anonymous
926/// struct or union nested within the class being checked.
927/// \param Inits All declarations, including anonymous struct/union members and
928/// indirect members, for which any initialization was provided.
929/// \param Diagnosed Set to true if an error is produced.
930static void CheckConstexprCtorInitializer(Sema &SemaRef,
931 const FunctionDecl *Dcl,
932 FieldDecl *Field,
933 llvm::SmallSet<Decl*, 16> &Inits,
934 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000935 if (Field->isInvalidDecl())
936 return;
937
Douglas Gregor556e5862011-10-10 17:22:13 +0000938 if (Field->isUnnamedBitfield())
939 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940
Richard Smithab44d5b2013-12-10 08:25:00 +0000941 // Anonymous unions with no variant members and empty anonymous structs do not
942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
943 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000944 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000945 (Field->getType()->isUnionType()
946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
947 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000948 return;
949
Richard Smitheb3c10c2011-10-01 02:31:28 +0000950 if (!Inits.count(Field)) {
951 if (!Diagnosed) {
952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
953 Diagnosed = true;
954 }
955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
956 } else if (Field->isAnonymousStructOrUnion()) {
957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000958 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000959 // If an anonymous union contains an anonymous struct of which any member
960 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000961 if (!RD->isUnion() || Inits.count(I))
962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000963 }
964}
965
Richard Smithd9f663b2013-04-22 15:31:51 +0000966/// Check the provided statement is allowed in a constexpr function
967/// definition.
968static bool
969CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000970 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000971 SourceLocation &Cxx1yLoc) {
972 // - its function-body shall be [...] a compound-statement that contains only
973 switch (S->getStmtClass()) {
974 case Stmt::NullStmtClass:
975 // - null statements,
976 return true;
977
978 case Stmt::DeclStmtClass:
979 // - static_assert-declarations
980 // - using-declarations,
981 // - using-directives,
982 // - typedef declarations and alias-declarations that do not define
983 // classes or enumerations,
984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
985 return false;
986 return true;
987
988 case Stmt::ReturnStmtClass:
989 // - and exactly one return statement;
990 if (isa<CXXConstructorDecl>(Dcl)) {
991 // C++1y allows return statements in constexpr constructors.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994 return true;
995 }
996
997 ReturnStmts.push_back(S->getLocStart());
998 return true;
999
1000 case Stmt::CompoundStmtClass: {
1001 // C++1y allows compound-statements.
1002 if (!Cxx1yLoc.isValid())
1003 Cxx1yLoc = S->getLocStart();
1004
1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001006 for (auto *BodyIt : CompStmt->body()) {
1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001008 Cxx1yLoc))
1009 return false;
1010 }
1011 return true;
1012 }
1013
1014 case Stmt::AttributedStmtClass:
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017 return true;
1018
1019 case Stmt::IfStmtClass: {
1020 // C++1y allows if-statements.
1021 if (!Cxx1yLoc.isValid())
1022 Cxx1yLoc = S->getLocStart();
1023
1024 IfStmt *If = cast<IfStmt>(S);
1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1026 Cxx1yLoc))
1027 return false;
1028 if (If->getElse() &&
1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1030 Cxx1yLoc))
1031 return false;
1032 return true;
1033 }
1034
1035 case Stmt::WhileStmtClass:
1036 case Stmt::DoStmtClass:
1037 case Stmt::ForStmtClass:
1038 case Stmt::CXXForRangeStmtClass:
1039 case Stmt::ContinueStmtClass:
1040 // C++1y allows all of these. We don't allow them as extensions in C++11,
1041 // because they don't make sense without variable mutation.
1042 if (!SemaRef.getLangOpts().CPlusPlus1y)
1043 break;
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 case Stmt::SwitchStmtClass:
1054 case Stmt::CaseStmtClass:
1055 case Stmt::DefaultStmtClass:
1056 case Stmt::BreakStmtClass:
1057 // C++1y allows switch-statements, and since they don't need variable
1058 // mutation, we can reasonably allow them in C++11 as an extension.
1059 if (!Cxx1yLoc.isValid())
1060 Cxx1yLoc = S->getLocStart();
1061 for (Stmt::child_range Children = S->children(); Children; ++Children)
1062 if (*Children &&
1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1064 Cxx1yLoc))
1065 return false;
1066 return true;
1067
1068 default:
1069 if (!isa<Expr>(S))
1070 break;
1071
1072 // C++1y allows expression-statements.
1073 if (!Cxx1yLoc.isValid())
1074 Cxx1yLoc = S->getLocStart();
1075 return true;
1076 }
1077
1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1079 << isa<CXXConstructorDecl>(Dcl);
1080 return false;
1081}
1082
Richard Smitheb3c10c2011-10-01 02:31:28 +00001083/// Check the body for the given constexpr function declaration only contains
1084/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1085///
1086/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001087bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 // The definition of a constexpr function shall satisfy the following
1091 // constraints: [...]
1092 // - its function-body shall be = delete, = default, or a
1093 // compound-statement
1094 //
Richard Smith74388b42012-02-04 00:33:54 +00001095 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 // In the definition of a constexpr constructor, [...]
1097 // - its function-body shall not be a function-try-block;
1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1099 << isa<CXXConstructorDecl>(Dcl);
1100 return false;
1101 }
1102
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001103 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001104
1105 // - its function-body shall be [...] a compound-statement that contains only
1106 // [... list of cases ...]
1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1108 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001109 for (auto *BodyIt : CompBody->body()) {
1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001111 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001112 }
1113
Richard Smithd9f663b2013-04-22 15:31:51 +00001114 if (Cxx1yLoc.isValid())
1115 Diag(Cxx1yLoc,
1116 getLangOpts().CPlusPlus1y
1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1118 : diag::ext_constexpr_body_invalid_stmt)
1119 << isa<CXXConstructorDecl>(Dcl);
1120
Richard Smitheb3c10c2011-10-01 02:31:28 +00001121 if (const CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1123 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001124 // DR1359:
1125 // - every non-variant non-static data member and base class sub-object
1126 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001127 // DR1460:
1128 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001129 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001130 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001131 if (Constructor->getNumCtorInitializers() == 0 &&
1132 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1134 return false;
1135 }
Richard Smithf368fb42011-10-10 16:38:04 +00001136 } else if (!Constructor->isDependentContext() &&
1137 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1139
1140 // Skip detailed checking if we have enough initializers, and we would
1141 // allow at most one initializer per member.
1142 bool AnyAnonStructUnionMembers = false;
1143 unsigned Fields = 0;
1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1145 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001146 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001147 AnyAnonStructUnionMembers = true;
1148 break;
1149 }
1150 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001151 // DR1460:
1152 // - if the class is a union-like class, but is not a union, for each of
1153 // its anonymous union members having variant members, exactly one of
1154 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 if (AnyAnonStructUnionMembers ||
1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1157 // Check initialization of non-static data members. Base classes are
1158 // always initialized so do not need to be checked. Dependent bases
1159 // might not have initializers in the member initializer list.
1160 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001161 for (const auto *I: Constructor->inits()) {
1162 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001164 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(ID->chain_begin(), ID->chain_end());
1166 }
1167
1168 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001169 for (auto *I : RD->fields())
1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 if (Diagnosed)
1172 return false;
1173 }
1174 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001175 } else {
1176 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001177 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001178 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 // otherwise if there's no return statement, the function cannot
1180 // be used in a core constant expression.
Richard Smith06ffb452014-04-22 23:14:23 +00001181 bool OK = getLangOpts().CPlusPlus1y &&
1182 (Dcl->getReturnType()->isVoidType() ||
1183 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001184 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001185 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1186 : diag::err_constexpr_body_no_return);
1187 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001188 }
1189 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001190 Diag(ReturnStmts.back(),
1191 getLangOpts().CPlusPlus1y
1192 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1193 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1195 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 }
1197 }
1198
Richard Smith74388b42012-02-04 00:33:54 +00001199 // C++11 [dcl.constexpr]p5:
1200 // if no function argument values exist such that the function invocation
1201 // substitution would produce a constant expression, the program is
1202 // ill-formed; no diagnostic required.
1203 // C++11 [dcl.constexpr]p3:
1204 // - every constructor call and implicit conversion used in initializing the
1205 // return value shall be one of those allowed in a constant expression.
1206 // C++11 [dcl.constexpr]p4:
1207 // - every constructor involved in initializing non-static data members and
1208 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001209 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001210 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001211 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001212 << isa<CXXConstructorDecl>(Dcl);
1213 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1214 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001215 // Don't return false here: we allow this for compatibility in
1216 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001217 }
1218
Richard Smitheb3c10c2011-10-01 02:31:28 +00001219 return true;
1220}
1221
Douglas Gregor61956c42008-10-31 09:07:45 +00001222/// isCurrentClassName - Determine whether the identifier II is the
1223/// name of the class type currently being defined. In the case of
1224/// nested classes, this will only return true if II is the name of
1225/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001226bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1227 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001229
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001230 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001231 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001232 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1234 } else
1235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1236
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001237 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001238 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001239 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001240}
1241
Richard Smithfb8b7b92013-10-15 00:00:26 +00001242/// \brief Determine whether the identifier II is a typo for the name of
1243/// the class type currently being defined. If so, update it to the identifier
1244/// that should have been used.
1245bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1246 assert(getLangOpts().CPlusPlus && "No class names in C!");
1247
1248 if (!getLangOpts().SpellChecking)
1249 return false;
1250
1251 CXXRecordDecl *CurDecl;
1252 if (SS && SS->isSet() && !SS->isInvalid()) {
1253 DeclContext *DC = computeDeclContext(*SS, true);
1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1255 } else
1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1257
1258 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1259 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1260 < II->getLength()) {
1261 II = CurDecl->getIdentifier();
1262 return true;
1263 }
1264
1265 return false;
1266}
1267
Douglas Gregordc974572012-11-10 07:24:09 +00001268/// \brief Determine whether the given class is a base class of the given
1269/// class, including looking at dependent bases.
1270static bool findCircularInheritance(const CXXRecordDecl *Class,
1271 const CXXRecordDecl *Current) {
1272 SmallVector<const CXXRecordDecl*, 8> Queue;
1273
1274 Class = Class->getCanonicalDecl();
1275 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001276 for (const auto &I : Current->bases()) {
1277 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001278 if (!Base)
1279 continue;
1280
1281 Base = Base->getDefinition();
1282 if (!Base)
1283 continue;
1284
1285 if (Base->getCanonicalDecl() == Class)
1286 return true;
1287
1288 Queue.push_back(Base);
1289 }
1290
1291 if (Queue.empty())
1292 return false;
1293
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001294 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001295 }
1296
1297 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001298}
1299
Mike Stump11289f42009-09-09 15:08:12 +00001300/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001301///
1302/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1303/// and returns NULL otherwise.
1304CXXBaseSpecifier *
1305Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1306 SourceRange SpecifierRange,
1307 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001308 TypeSourceInfo *TInfo,
1309 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001310 QualType BaseType = TInfo->getType();
1311
Douglas Gregor463421d2009-03-03 04:44:36 +00001312 // C++ [class.union]p1:
1313 // A union shall not have base classes.
1314 if (Class->isUnion()) {
1315 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1316 << SpecifierRange;
1317 return 0;
1318 }
1319
Douglas Gregor752a5952011-01-03 22:36:02 +00001320 if (EllipsisLoc.isValid() &&
1321 !TInfo->getType()->containsUnexpandedParameterPack()) {
1322 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1323 << TInfo->getTypeLoc().getSourceRange();
1324 EllipsisLoc = SourceLocation();
1325 }
Douglas Gregor62004702012-11-10 01:18:17 +00001326
1327 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1328
1329 if (BaseType->isDependentType()) {
1330 // Make sure that we don't have circular inheritance among our dependent
1331 // bases. For non-dependent bases, the check for completeness below handles
1332 // this.
1333 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1334 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1335 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001336 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001337 Diag(BaseLoc, diag::err_circular_inheritance)
1338 << BaseType << Context.getTypeDeclType(Class);
1339
1340 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1341 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1342 << BaseType;
1343
1344 return 0;
1345 }
1346 }
1347
Mike Stump11289f42009-09-09 15:08:12 +00001348 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001349 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001350 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001351 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001352
1353 // Base specifiers must be record types.
1354 if (!BaseType->isRecordType()) {
1355 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1356 return 0;
1357 }
1358
1359 // C++ [class.union]p1:
1360 // A union shall not be used as a base class.
1361 if (BaseType->isUnionType()) {
1362 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1363 return 0;
1364 }
1365
1366 // C++ [class.derived]p2:
1367 // The class-name in a base-specifier shall not be an incompletely
1368 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001369 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001370 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001371 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001372 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001373 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001374
Eli Friedmanc96d4962009-08-15 21:55:26 +00001375 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001376 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001378 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001379 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001380 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001381 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001382
David Majnemer9b1754d2013-11-02 12:00:36 +00001383 // A class which contains a flexible array member is not suitable for use as a
1384 // base class:
1385 // - If the layout determines that a base comes before another base,
1386 // the flexible array member would index into the subsequent base.
1387 // - If the layout determines that base comes before the derived class,
1388 // the flexible array member would index into the derived class.
1389 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1390 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1391 << CXXBaseDecl->getDeclName();
1392 return 0;
1393 }
1394
Anders Carlsson65c76d32011-03-25 14:55:14 +00001395 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001396 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001397 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001398 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001399 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001400 << CXXBaseDecl->getDeclName()
1401 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001402 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1403 << CXXBaseDecl->getDeclName();
1404 return 0;
1405 }
1406
John McCall3696dcb2010-08-17 07:23:57 +00001407 if (BaseDecl->isInvalidDecl())
1408 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001409
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001410 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001411 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001412 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001413 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001414}
1415
Douglas Gregor556877c2008-04-13 21:30:24 +00001416/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1417/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001418/// example:
1419/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001420/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001421BaseResult
John McCall48871652010-08-21 09:40:31 +00001422Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001423 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001424 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001425 ParsedType basetype, SourceLocation BaseLoc,
1426 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001427 if (!classdecl)
1428 return true;
1429
Douglas Gregorc40290e2009-03-09 23:48:35 +00001430 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001431 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001432 if (!Class)
1433 return true;
1434
Richard Smith4c96e992013-02-19 23:47:15 +00001435 // We do not support any C++11 attributes on base-specifiers yet.
1436 // Diagnose any attributes we see.
1437 if (!Attributes.empty()) {
1438 for (AttributeList *Attr = Attributes.getList(); Attr;
1439 Attr = Attr->getNext()) {
1440 if (Attr->isInvalid() ||
1441 Attr->getKind() == AttributeList::IgnoredAttribute)
1442 continue;
1443 Diag(Attr->getLoc(),
1444 Attr->getKind() == AttributeList::UnknownAttribute
1445 ? diag::warn_unknown_attribute_ignored
1446 : diag::err_base_specifier_attribute)
1447 << Attr->getName();
1448 }
1449 }
1450
Nick Lewycky19b9f952010-07-26 16:56:01 +00001451 TypeSourceInfo *TInfo = 0;
1452 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001453
Douglas Gregor752a5952011-01-03 22:36:02 +00001454 if (EllipsisLoc.isInvalid() &&
1455 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001456 UPPC_BaseType))
1457 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001458
Douglas Gregor463421d2009-03-03 04:44:36 +00001459 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001460 Virtual, Access, TInfo,
1461 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001462 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001463 else
1464 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregor463421d2009-03-03 04:44:36 +00001466 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001467}
Douglas Gregor556877c2008-04-13 21:30:24 +00001468
Douglas Gregor463421d2009-03-03 04:44:36 +00001469/// \brief Performs the actual work of attaching the given base class
1470/// specifiers to a C++ class.
1471bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1472 unsigned NumBases) {
1473 if (NumBases == 0)
1474 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001475
1476 // Used to keep track of which base types we have already seen, so
1477 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001478 // that the key is always the unqualified canonical type of the base
1479 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001480 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1481
1482 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001483 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001484 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001485 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001486 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001487 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001488 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001489
1490 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1491 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001492 // C++ [class.mi]p3:
1493 // A class shall not be specified as a direct base class of a
1494 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001495 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001496 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001497 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001498 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001499
1500 // Delete the duplicate base class specifier; we're going to
1501 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001502 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001503
1504 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001505 } else {
1506 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001507 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001508 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001509 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1510 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1511 if (Class->isInterface() &&
1512 (!RD->isInterface() ||
1513 KnownBase->getAccessSpecifier() != AS_public)) {
1514 // The Microsoft extension __interface does not permit bases that
1515 // are not themselves public interfaces.
1516 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1517 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1518 << RD->getSourceRange();
1519 Invalid = true;
1520 }
1521 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001522 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001523 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001524 }
1525 }
1526
1527 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001528 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001529
1530 // Delete the remaining (good) base class specifiers, since their
1531 // data has been copied into the CXXRecordDecl.
1532 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001533 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001534
1535 return Invalid;
1536}
1537
1538/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1539/// class, after checking whether there are any duplicate base
1540/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001541void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001542 unsigned NumBases) {
1543 if (!ClassDecl || !Bases || !NumBases)
1544 return;
1545
1546 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001547 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001548}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001549
Douglas Gregor36d1b142009-10-06 17:59:45 +00001550/// \brief Determine whether the type \p Derived is a C++ class that is
1551/// derived from the type \p Base.
1552bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001553 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001554 return false;
John McCalle78aac42010-03-10 03:28:59 +00001555
Douglas Gregor45bb4832013-03-26 23:36:30 +00001556 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001557 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001558 return false;
1559
Douglas Gregor45bb4832013-03-26 23:36:30 +00001560 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001561 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001562 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001563
1564 // If either the base or the derived type is invalid, don't try to
1565 // check whether one is derived from the other.
1566 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1567 return false;
1568
John McCall67da35c2010-02-04 22:26:26 +00001569 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1570 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001571}
1572
1573/// \brief Determine whether the type \p Derived is a C++ class that is
1574/// derived from the type \p Base.
1575bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001576 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001577 return false;
1578
Douglas Gregor45bb4832013-03-26 23:36:30 +00001579 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001580 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001581 return false;
1582
Douglas Gregor45bb4832013-03-26 23:36:30 +00001583 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001584 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001585 return false;
1586
Douglas Gregor36d1b142009-10-06 17:59:45 +00001587 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1588}
1589
Anders Carlssona70cff62010-04-24 19:06:50 +00001590void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001591 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001592 assert(BasePathArray.empty() && "Base path array must be empty!");
1593 assert(Paths.isRecordingPaths() && "Must record paths!");
1594
1595 const CXXBasePath &Path = Paths.front();
1596
1597 // We first go backward and check if we have a virtual base.
1598 // FIXME: It would be better if CXXBasePath had the base specifier for
1599 // the nearest virtual base.
1600 unsigned Start = 0;
1601 for (unsigned I = Path.size(); I != 0; --I) {
1602 if (Path[I - 1].Base->isVirtual()) {
1603 Start = I - 1;
1604 break;
1605 }
1606 }
1607
1608 // Now add all bases.
1609 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001610 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001611}
1612
Douglas Gregor88d292c2010-05-13 16:44:06 +00001613/// \brief Determine whether the given base path includes a virtual
1614/// base class.
John McCallcf142162010-08-07 06:22:56 +00001615bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1616 for (CXXCastPath::const_iterator B = BasePath.begin(),
1617 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001618 B != BEnd; ++B)
1619 if ((*B)->isVirtual())
1620 return true;
1621
1622 return false;
1623}
1624
Douglas Gregor36d1b142009-10-06 17:59:45 +00001625/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1626/// conversion (where Derived and Base are class types) is
1627/// well-formed, meaning that the conversion is unambiguous (and
1628/// that all of the base classes are accessible). Returns true
1629/// and emits a diagnostic if the code is ill-formed, returns false
1630/// otherwise. Loc is the location where this routine should point to
1631/// if there is an error, and Range is the source range to highlight
1632/// if there is an error.
1633bool
1634Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001635 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001636 unsigned AmbigiousBaseConvID,
1637 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001638 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001639 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001640 // First, determine whether the path from Derived to Base is
1641 // ambiguous. This is slightly more expensive than checking whether
1642 // the Derived to Base conversion exists, because here we need to
1643 // explore multiple paths to determine if there is an ambiguity.
1644 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1645 /*DetectVirtual=*/false);
1646 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1647 assert(DerivationOkay &&
1648 "Can only be used with a derived-to-base conversion");
1649 (void)DerivationOkay;
1650
1651 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001652 if (InaccessibleBaseID) {
1653 // Check that the base class can be accessed.
1654 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1655 InaccessibleBaseID)) {
1656 case AR_inaccessible:
1657 return true;
1658 case AR_accessible:
1659 case AR_dependent:
1660 case AR_delayed:
1661 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001662 }
John McCall5b0829a2010-02-10 09:31:12 +00001663 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001664
1665 // Build a base path if necessary.
1666 if (BasePath)
1667 BuildBasePathArray(Paths, *BasePath);
1668 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001669 }
1670
David Majnemer626032f2013-06-22 06:43:58 +00001671 if (AmbigiousBaseConvID) {
1672 // We know that the derived-to-base conversion is ambiguous, and
1673 // we're going to produce a diagnostic. Perform the derived-to-base
1674 // search just one more time to compute all of the possible paths so
1675 // that we can print them out. This is more expensive than any of
1676 // the previous derived-to-base checks we've done, but at this point
1677 // performance isn't as much of an issue.
1678 Paths.clear();
1679 Paths.setRecordingPaths(true);
1680 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1681 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1682 (void)StillOkay;
1683
1684 // Build up a textual representation of the ambiguous paths, e.g.,
1685 // D -> B -> A, that will be used to illustrate the ambiguous
1686 // conversions in the diagnostic. We only print one of the paths
1687 // to each base class subobject.
1688 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1689
1690 Diag(Loc, AmbigiousBaseConvID)
1691 << Derived << Base << PathDisplayStr << Range << Name;
1692 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001693 return true;
1694}
1695
1696bool
1697Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001698 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001699 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001700 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001701 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001702 IgnoreAccess ? 0
1703 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001704 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001705 Loc, Range, DeclarationName(),
1706 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707}
1708
1709
1710/// @brief Builds a string representing ambiguous paths from a
1711/// specific derived class to different subobjects of the same base
1712/// class.
1713///
1714/// This function builds a string that can be used in error messages
1715/// to show the different paths that one can take through the
1716/// inheritance hierarchy to go from the derived class to different
1717/// subobjects of a base class. The result looks something like this:
1718/// @code
1719/// struct D -> struct B -> struct A
1720/// struct D -> struct C -> struct A
1721/// @endcode
1722std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1723 std::string PathDisplayStr;
1724 std::set<unsigned> DisplayedPaths;
1725 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1726 Path != Paths.end(); ++Path) {
1727 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1728 // We haven't displayed a path to this particular base
1729 // class subobject yet.
1730 PathDisplayStr += "\n ";
1731 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1732 for (CXXBasePath::const_iterator Element = Path->begin();
1733 Element != Path->end(); ++Element)
1734 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1735 }
1736 }
1737
1738 return PathDisplayStr;
1739}
1740
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001741//===----------------------------------------------------------------------===//
1742// C++ class member Handling
1743//===----------------------------------------------------------------------===//
1744
Abramo Bagnarad7340582010-06-05 05:09:32 +00001745/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001746bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1747 SourceLocation ASLoc,
1748 SourceLocation ColonLoc,
1749 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001750 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001751 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001752 ASLoc, ColonLoc);
1753 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001754 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001755}
1756
Richard Smith18f07db2012-08-06 03:25:17 +00001757/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001758void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001759 if (D->isInvalidDecl())
1760 return;
1761
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001762 // We only care about "override" and "final" declarations.
1763 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1764 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001765
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001766 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001767
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001768 // We can't check dependent instance methods.
1769 if (MD && MD->isInstance() &&
1770 (MD->getParent()->hasAnyDependentBases() ||
1771 MD->getType()->isDependentType()))
1772 return;
1773
1774 if (MD && !MD->isVirtual()) {
1775 // If we have a non-virtual method, check if if hides a virtual method.
1776 // (In that case, it's most likely the method has the wrong type.)
1777 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1778 FindHiddenVirtualMethods(MD, OverloadedMethods);
1779
1780 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001781 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1782 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001783 diag::override_keyword_hides_virtual_member_function)
1784 << "override" << (OverloadedMethods.size() > 1);
1785 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001786 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001787 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001788 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1789 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001790 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001791 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1792 MD->setInvalidDecl();
1793 return;
1794 }
1795 // Fall through into the general case diagnostic.
1796 // FIXME: We might want to attempt typo correction here.
1797 }
1798
1799 if (!MD || !MD->isVirtual()) {
1800 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1801 Diag(OA->getLocation(),
1802 diag::override_keyword_only_allowed_on_virtual_member_functions)
1803 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1804 D->dropAttr<OverrideAttr>();
1805 }
1806 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1807 Diag(FA->getLocation(),
1808 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001809 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1810 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001811 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001812 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001813 return;
1814 }
Richard Smith18f07db2012-08-06 03:25:17 +00001815
Richard Smith18f07db2012-08-06 03:25:17 +00001816 // C++11 [class.virtual]p5:
1817 // If a virtual function is marked with the virt-specifier override and
1818 // does not override a member function of a base class, the program is
1819 // ill-formed.
1820 bool HasOverriddenMethods =
1821 MD->begin_overridden_methods() != MD->end_overridden_methods();
1822 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1823 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1824 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001825}
1826
Richard Smith18f07db2012-08-06 03:25:17 +00001827/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001828/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001829/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001830bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1831 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001832 FinalAttr *FA = Old->getAttr<FinalAttr>();
1833 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001834 return false;
1835
1836 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001837 << New->getDeclName()
1838 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001839 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1840 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001841}
1842
Daniel Jasper0baec5492012-06-06 08:32:04 +00001843static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001844 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1845 // FIXME: Destruction of ObjC lifetime types has side-effects.
1846 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1847 return !RD->isCompleteDefinition() ||
1848 !RD->hasTrivialDefaultConstructor() ||
1849 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001850 return false;
1851}
1852
John McCall5e77d762013-04-16 07:28:30 +00001853static AttributeList *getMSPropertyAttr(AttributeList *list) {
1854 for (AttributeList* it = list; it != 0; it = it->getNext())
1855 if (it->isDeclspecPropertyAttribute())
1856 return it;
1857 return 0;
1858}
1859
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001860/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1861/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001862/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001863/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1864/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001865NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001866Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001867 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001868 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001869 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001870 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001871 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1872 DeclarationName Name = NameInfo.getName();
1873 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001874
1875 // For anonymous bitfields, the location should point to the type.
1876 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001877 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001878
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001879 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001880
John McCallb1cd7da2010-06-04 08:34:12 +00001881 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001882 assert(!DS.isFriendSpecified());
1883
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001884 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001885
John McCalldb632ac2012-09-25 07:32:39 +00001886 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1887 // The Microsoft extension __interface only permits public member functions
1888 // and prohibits constructors, destructors, operators, non-public member
1889 // functions, static methods and data members.
1890 unsigned InvalidDecl;
1891 bool ShowDeclName = true;
1892 if (!isFunc)
1893 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1894 else if (AS != AS_public)
1895 InvalidDecl = 2;
1896 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1897 InvalidDecl = 3;
1898 else switch (Name.getNameKind()) {
1899 case DeclarationName::CXXConstructorName:
1900 InvalidDecl = 4;
1901 ShowDeclName = false;
1902 break;
1903
1904 case DeclarationName::CXXDestructorName:
1905 InvalidDecl = 5;
1906 ShowDeclName = false;
1907 break;
1908
1909 case DeclarationName::CXXOperatorName:
1910 case DeclarationName::CXXConversionFunctionName:
1911 InvalidDecl = 6;
1912 break;
1913
1914 default:
1915 InvalidDecl = 0;
1916 break;
1917 }
1918
1919 if (InvalidDecl) {
1920 if (ShowDeclName)
1921 Diag(Loc, diag::err_invalid_member_in_interface)
1922 << (InvalidDecl-1) << Name;
1923 else
1924 Diag(Loc, diag::err_invalid_member_in_interface)
1925 << (InvalidDecl-1) << "";
1926 return 0;
1927 }
1928 }
1929
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001930 // C++ 9.2p6: A member shall not be declared to have automatic storage
1931 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001932 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1933 // data members and cannot be applied to names declared const or static,
1934 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001935 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001936 case DeclSpec::SCS_unspecified:
1937 case DeclSpec::SCS_typedef:
1938 case DeclSpec::SCS_static:
1939 break;
1940 case DeclSpec::SCS_mutable:
1941 if (isFunc) {
1942 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001943
Richard Smithb4a9e862013-04-12 22:46:28 +00001944 // FIXME: It would be nicer if the keyword was ignored only for this
1945 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001946 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001947 }
1948 break;
1949 default:
1950 Diag(DS.getStorageClassSpecLoc(),
1951 diag::err_storageclass_invalid_for_member);
1952 D.getMutableDeclSpec().ClearStorageClassSpecs();
1953 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001954 }
1955
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001956 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1957 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001958 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001959
David Blaikie35506f82013-01-30 01:22:18 +00001960 if (DS.isConstexprSpecified() && isInstField) {
1961 SemaDiagnosticBuilder B =
1962 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1963 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1964 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00001965 B << 0 << 0;
1966 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
1967 B << FixItHint::CreateRemoval(ConstexprLoc);
1968 else {
1969 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
1970 D.getMutableDeclSpec().ClearConstexprSpec();
1971 const char *PrevSpec;
1972 unsigned DiagID;
1973 bool Failed = D.getMutableDeclSpec().SetTypeQual(
1974 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
1975 (void)Failed;
1976 assert(!Failed && "Making a constexpr member const shouldn't fail");
1977 }
David Blaikie35506f82013-01-30 01:22:18 +00001978 } else {
1979 B << 1;
1980 const char *PrevSpec;
1981 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001982 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001983 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1984 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001985 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001986 "This is the only DeclSpec that should fail to be applied");
1987 B << 1;
1988 } else {
1989 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1990 isInstField = false;
1991 }
1992 }
1993 }
1994
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001995 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001996 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001997 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001998
1999 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002000 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002001 Diag(Loc, diag::err_bad_variable_name)
2002 << Name;
2003 return 0;
2004 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002005
Benjamin Kramer365082d2012-05-19 16:34:46 +00002006 IdentifierInfo *II = Name.getAsIdentifierInfo();
2007
Douglas Gregor7c26c042011-09-21 14:40:46 +00002008 // Member field could not be with "template" keyword.
2009 // So TemplateParameterLists should be empty in this case.
2010 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002011 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002012 if (TemplateParams->size()) {
2013 // There is no such thing as a member field template.
2014 Diag(D.getIdentifierLoc(), diag::err_template_member)
2015 << II
2016 << SourceRange(TemplateParams->getTemplateLoc(),
2017 TemplateParams->getRAngleLoc());
2018 } else {
2019 // There is an extraneous 'template<>' for this member.
2020 Diag(TemplateParams->getTemplateLoc(),
2021 diag::err_template_member_noparams)
2022 << II
2023 << SourceRange(TemplateParams->getTemplateLoc(),
2024 TemplateParams->getRAngleLoc());
2025 }
2026 return 0;
2027 }
2028
Douglas Gregora007d362010-10-13 22:19:53 +00002029 if (SS.isSet() && !SS.isInvalid()) {
2030 // The user provided a superfluous scope specifier inside a class
2031 // definition:
2032 //
2033 // class X {
2034 // int X::member;
2035 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002036 if (DeclContext *DC = computeDeclContext(SS, false))
2037 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002038 else
2039 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2040 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002041
Douglas Gregora007d362010-10-13 22:19:53 +00002042 SS.clear();
2043 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002044
John McCall5e77d762013-04-16 07:28:30 +00002045 AttributeList *MSPropertyAttr =
2046 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002047 if (MSPropertyAttr) {
2048 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2049 BitWidth, InitStyle, AS, MSPropertyAttr);
2050 if (!Member)
2051 return 0;
2052 isInstField = false;
2053 } else {
2054 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2055 BitWidth, InitStyle, AS);
2056 assert(Member && "HandleField never returns null");
2057 }
2058 } else {
2059 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2060
2061 Member = HandleDeclarator(S, D, TemplateParameterLists);
2062 if (!Member)
2063 return 0;
2064
2065 // Non-instance-fields can't have a bitfield.
2066 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002067 if (Member->isInvalidDecl()) {
2068 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002069 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002070 // C++ 9.6p3: A bit-field shall not be a static member.
2071 // "static member 'A' cannot be a bit-field"
2072 Diag(Loc, diag::err_static_not_bitfield)
2073 << Name << BitWidth->getSourceRange();
2074 } else if (isa<TypedefDecl>(Member)) {
2075 // "typedef member 'x' cannot be a bit-field"
2076 Diag(Loc, diag::err_typedef_not_bitfield)
2077 << Name << BitWidth->getSourceRange();
2078 } else {
2079 // A function typedef ("typedef int f(); f a;").
2080 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2081 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002082 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002083 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattnerd26760a2009-03-05 23:01:03 +00002086 BitWidth = 0;
2087 Member->setInvalidDecl();
2088 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002089
2090 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Larisse Voufo39a1e502013-08-06 01:03:05 +00002092 // If we have declared a member function template or static data member
2093 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002094 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2095 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002096 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2097 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002098 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002099
Richard Smith18f07db2012-08-06 03:25:17 +00002100 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002101 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002102 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002103 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2104 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002105
Douglas Gregorf2f08062011-03-08 17:10:18 +00002106 if (VS.getLastLocation().isValid()) {
2107 // Update the end location of a method that has a virt-specifiers.
2108 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2109 MD->setRangeEnd(VS.getLastLocation());
2110 }
Richard Smith18f07db2012-08-06 03:25:17 +00002111
Anders Carlssonc87f8612011-01-20 06:29:02 +00002112 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002113
Douglas Gregor92751d42008-11-17 22:58:34 +00002114 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002115
Daniel Jasper0baec5492012-06-06 08:32:04 +00002116 if (isInstField) {
2117 FieldDecl *FD = cast<FieldDecl>(Member);
2118 FieldCollector->Add(FD);
2119
2120 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2121 FD->getLocation())
2122 != DiagnosticsEngine::Ignored) {
2123 // Remember all explicit private FieldDecls that have a name, no side
2124 // effects and are not part of a dependent type declaration.
2125 if (!FD->isImplicit() && FD->getDeclName() &&
2126 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002127 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002128 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002129 !InitializationHasSideEffects(*FD))
2130 UnusedPrivateFields.insert(FD);
2131 }
2132 }
2133
John McCall48871652010-08-21 09:40:31 +00002134 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002135}
2136
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002137namespace {
2138 class UninitializedFieldVisitor
2139 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2140 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002141 // List of Decls to generate a warning on. Also remove Decls that become
2142 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002143 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002144 // If non-null, add a note to the warning pointing back to the constructor.
2145 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002146 public:
2147 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002148 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002149 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002150 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002151 : Inherited(S.Context), S(S), Decls(Decls),
2152 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002153
Richard Trieufd687772013-09-16 20:46:50 +00002154 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002155 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2156 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002157
Richard Trieu1bc22c12013-09-13 03:20:53 +00002158 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2159 // or union.
2160 MemberExpr *FieldME = ME;
2161
2162 Expr *Base = ME;
2163 while (isa<MemberExpr>(Base)) {
2164 ME = cast<MemberExpr>(Base);
2165
2166 if (isa<VarDecl>(ME->getMemberDecl()))
2167 return;
2168
2169 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2170 if (!FD->isAnonymousStructOrUnion())
2171 FieldME = ME;
2172
2173 Base = ME->getBase();
2174 }
2175
Richard Trieufd687772013-09-16 20:46:50 +00002176 if (!isa<CXXThisExpr>(Base))
2177 return;
2178
Richard Trieu406e65c2013-09-20 03:03:06 +00002179 ValueDecl* FoundVD = FieldME->getMemberDecl();
2180
Richard Trieuef64e942013-10-25 00:56:00 +00002181 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002182 return;
2183
Richard Trieuef64e942013-10-25 00:56:00 +00002184 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002185
Richard Trieuef64e942013-10-25 00:56:00 +00002186 // Prevent double warnings on use of unbounded references.
2187 if (IsReference != CheckReferenceOnly)
2188 return;
2189
2190 unsigned diag = IsReference
2191 ? diag::warn_reference_field_is_uninit
2192 : diag::warn_field_is_uninit;
2193 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2194 if (Constructor)
2195 S.Diag(Constructor->getLocation(),
2196 diag::note_uninit_in_this_constructor)
2197 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2198
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002199 }
2200
2201 void HandleValue(Expr *E) {
2202 E = E->IgnoreParens();
2203
2204 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002205 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002206 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002207 }
2208
2209 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2210 HandleValue(CO->getTrueExpr());
2211 HandleValue(CO->getFalseExpr());
2212 return;
2213 }
2214
2215 if (BinaryConditionalOperator *BCO =
2216 dyn_cast<BinaryConditionalOperator>(E)) {
2217 HandleValue(BCO->getCommon());
2218 HandleValue(BCO->getFalseExpr());
2219 return;
2220 }
2221
2222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2223 switch (BO->getOpcode()) {
2224 default:
2225 return;
2226 case(BO_PtrMemD):
2227 case(BO_PtrMemI):
2228 HandleValue(BO->getLHS());
2229 return;
2230 case(BO_Comma):
2231 HandleValue(BO->getRHS());
2232 return;
2233 }
2234 }
2235 }
2236
Richard Trieu1bc22c12013-09-13 03:20:53 +00002237 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002238 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002240
2241 Inherited::VisitMemberExpr(ME);
2242 }
2243
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002244 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2245 if (E->getCastKind() == CK_LValueToRValue)
2246 HandleValue(E->getSubExpr());
2247
2248 Inherited::VisitImplicitCastExpr(E);
2249 }
2250
Richard Trieu1bc22c12013-09-13 03:20:53 +00002251 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002252 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2254 if (ICE->getCastKind() == CK_NoOp)
2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002257
2258 Inherited::VisitCXXConstructExpr(E);
2259 }
2260
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2262 Expr *Callee = E->getCallee();
2263 if (isa<MemberExpr>(Callee))
2264 HandleValue(Callee);
2265
2266 Inherited::VisitCXXMemberCallExpr(E);
2267 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002268
2269 void VisitBinaryOperator(BinaryOperator *E) {
2270 // If a field assignment is detected, remove the field from the
2271 // uninitiailized field set.
2272 if (E->getOpcode() == BO_Assign)
2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002275 if (!FD->getType()->isReferenceType())
2276 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002277
2278 Inherited::VisitBinaryOperator(E);
2279 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002280 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002281 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002282 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2283 const CXXConstructorDecl *Constructor) {
2284 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002285 return;
2286
Richard Trieuef64e942013-10-25 00:56:00 +00002287 if (!E)
2288 return;
2289
2290 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2291 E = Default->getExpr();
2292 if (!E)
2293 return;
2294 // In class initializers will point to the constructor.
2295 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2296 } else {
2297 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2298 }
2299 }
2300
2301 // Diagnose value-uses of fields to initialize themselves, e.g.
2302 // foo(foo)
2303 // where foo is not also a parameter to the constructor.
2304 // Also diagnose across field uninitialized use such as
2305 // x(y), y(x)
2306 // TODO: implement -Wuninitialized and fold this into that framework.
2307 static void DiagnoseUninitializedFields(
2308 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2309
2310 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2311 Constructor->getLocation())
2312 == DiagnosticsEngine::Ignored) {
2313 return;
2314 }
2315
2316 if (Constructor->isInvalidDecl())
2317 return;
2318
2319 const CXXRecordDecl *RD = Constructor->getParent();
2320
2321 // Holds fields that are uninitialized.
2322 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2323
2324 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002325 for (auto *I : RD->decls()) {
2326 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002327 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002328 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002329 UninitializedFields.insert(IFD->getAnonField());
2330 }
2331 }
2332
Aaron Ballman0ad78302014-03-13 17:34:31 +00002333 for (const auto *FieldInit : Constructor->inits()) {
2334 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002335
2336 CheckInitExprContainsUninitializedFields(
2337 SemaRef, InitExpr, UninitializedFields, Constructor);
2338
Aaron Ballman0ad78302014-03-13 17:34:31 +00002339 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002340 UninitializedFields.erase(Field);
2341 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002342 }
2343} // namespace
2344
Richard Smith74108172014-01-17 03:11:34 +00002345/// \brief Enter a new C++ default initializer scope. After calling this, the
2346/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2347/// parsing or instantiating the initializer failed.
2348void Sema::ActOnStartCXXInClassMemberInitializer() {
2349 // Create a synthetic function scope to represent the call to the constructor
2350 // that notionally surrounds a use of this initializer.
2351 PushFunctionScope();
2352}
2353
2354/// \brief This is invoked after parsing an in-class initializer for a
2355/// non-static C++ class member, and after instantiating an in-class initializer
2356/// in a class template. Such actions are deferred until the class is complete.
2357void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2358 SourceLocation InitLoc,
2359 Expr *InitExpr) {
2360 // Pop the notional constructor scope we created earlier.
2361 PopFunctionScopeInfo(0, D);
2362
Richard Smith938f40b2011-06-11 17:19:42 +00002363 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002364 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2365 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002366
2367 if (!InitExpr) {
2368 FD->setInvalidDecl();
2369 FD->removeInClassInitializer();
2370 return;
2371 }
2372
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002373 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2374 FD->setInvalidDecl();
2375 FD->removeInClassInitializer();
2376 return;
2377 }
2378
Richard Smith938f40b2011-06-11 17:19:42 +00002379 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002380 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002381 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002382 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002383 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002384 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002385 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2386 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002387 if (Init.isInvalid()) {
2388 FD->setInvalidDecl();
2389 return;
2390 }
Richard Smith938f40b2011-06-11 17:19:42 +00002391 }
2392
Richard Smith945f8d32013-01-14 22:39:08 +00002393 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002394 // The initialization of each base and member constitutes a
2395 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002396 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002397 if (Init.isInvalid()) {
2398 FD->setInvalidDecl();
2399 return;
2400 }
2401
2402 InitExpr = Init.release();
2403
2404 FD->setInClassInitializer(InitExpr);
2405}
2406
Douglas Gregor15e77a22009-12-31 09:10:24 +00002407/// \brief Find the direct and/or virtual base specifiers that
2408/// correspond to the given base type, for use in base initialization
2409/// within a constructor.
2410static bool FindBaseInitializer(Sema &SemaRef,
2411 CXXRecordDecl *ClassDecl,
2412 QualType BaseType,
2413 const CXXBaseSpecifier *&DirectBaseSpec,
2414 const CXXBaseSpecifier *&VirtualBaseSpec) {
2415 // First, check for a direct base class.
2416 DirectBaseSpec = 0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002417 for (const auto &Base : ClassDecl->bases()) {
2418 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002419 // We found a direct base of this type. That's what we're
2420 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002421 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002422 break;
2423 }
2424 }
2425
2426 // Check for a virtual base class.
2427 // FIXME: We might be able to short-circuit this if we know in advance that
2428 // there are no virtual bases.
2429 VirtualBaseSpec = 0;
2430 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2431 // We haven't found a base yet; search the class hierarchy for a
2432 // virtual base class.
2433 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2434 /*DetectVirtual=*/false);
2435 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2436 BaseType, Paths)) {
2437 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2438 Path != Paths.end(); ++Path) {
2439 if (Path->back().Base->isVirtual()) {
2440 VirtualBaseSpec = Path->back().Base;
2441 break;
2442 }
2443 }
2444 }
2445 }
2446
2447 return DirectBaseSpec || VirtualBaseSpec;
2448}
2449
Sebastian Redla74948d2011-09-24 17:48:25 +00002450/// \brief Handle a C++ member initializer using braced-init-list syntax.
2451MemInitResult
2452Sema::ActOnMemInitializer(Decl *ConstructorD,
2453 Scope *S,
2454 CXXScopeSpec &SS,
2455 IdentifierInfo *MemberOrBase,
2456 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002457 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002458 SourceLocation IdLoc,
2459 Expr *InitList,
2460 SourceLocation EllipsisLoc) {
2461 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002462 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002463 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002464}
2465
2466/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002467MemInitResult
John McCall48871652010-08-21 09:40:31 +00002468Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002469 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002470 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002471 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002472 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002473 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002474 SourceLocation IdLoc,
2475 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002476 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002477 SourceLocation RParenLoc,
2478 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002479 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002480 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002481 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002482 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002483}
2484
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002485namespace {
2486
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002487// Callback to only accept typo corrections that can be a valid C++ member
2488// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002490public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002491 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2492 : ClassDecl(ClassDecl) {}
2493
Craig Toppera798a9d2014-03-02 09:32:10 +00002494 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002495 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2496 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2497 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002498 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002499 }
2500 return false;
2501 }
2502
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002503private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002504 CXXRecordDecl *ClassDecl;
2505};
2506
2507}
2508
Sebastian Redla74948d2011-09-24 17:48:25 +00002509/// \brief Handle a C++ member initializer.
2510MemInitResult
2511Sema::BuildMemInitializer(Decl *ConstructorD,
2512 Scope *S,
2513 CXXScopeSpec &SS,
2514 IdentifierInfo *MemberOrBase,
2515 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002516 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002517 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002518 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002519 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002520 if (!ConstructorD)
2521 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002522
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002523 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002524
2525 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002526 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002527 if (!Constructor) {
2528 // The user wrote a constructor initializer on a function that is
2529 // not a C++ constructor. Ignore the error for now, because we may
2530 // have more member initializers coming; we'll diagnose it just
2531 // once in ActOnMemInitializers.
2532 return true;
2533 }
2534
2535 CXXRecordDecl *ClassDecl = Constructor->getParent();
2536
2537 // C++ [class.base.init]p2:
2538 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002539 // constructor's class and, if not found in that scope, are looked
2540 // up in the scope containing the constructor's definition.
2541 // [Note: if the constructor's class contains a member with the
2542 // same name as a direct or virtual base class of the class, a
2543 // mem-initializer-id naming the member or base class and composed
2544 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002545 // mem-initializer-id for the hidden base class may be specified
2546 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002547 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002548 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002549 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002550 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002551 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002552 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002553 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2554 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002555 if (EllipsisLoc.isValid())
2556 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002557 << MemberOrBase
2558 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002559
Sebastian Redla9351792012-02-11 23:51:47 +00002560 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002561 }
Francois Pichetd583da02010-12-04 09:14:42 +00002562 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002563 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002564 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002565 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002566 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002567
2568 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002569 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002570 } else if (DS.getTypeSpecType() == TST_decltype) {
2571 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002572 } else {
2573 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2574 LookupParsedName(R, S, &SS);
2575
2576 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2577 if (!TyD) {
2578 if (R.isAmbiguous()) return true;
2579
John McCallda6841b2010-04-09 19:01:14 +00002580 // We don't want access-control diagnostics here.
2581 R.suppressDiagnostics();
2582
Douglas Gregora3b624a2010-01-19 06:46:48 +00002583 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2584 bool NotUnknownSpecialization = false;
2585 DeclContext *DC = computeDeclContext(SS, false);
2586 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2587 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2588
2589 if (!NotUnknownSpecialization) {
2590 // When the scope specifier can refer to a member of an unknown
2591 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002592 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2593 SS.getWithLocInContext(Context),
2594 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002595 if (BaseType.isNull())
2596 return true;
2597
Douglas Gregora3b624a2010-01-19 06:46:48 +00002598 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002599 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002600 }
2601 }
2602
Douglas Gregor15e77a22009-12-31 09:10:24 +00002603 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002604 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002605 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002606 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002607 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002608 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002609 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002610 // We have found a non-static data member with a similar
2611 // name to what was typed; complain and initialize that
2612 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002613 diagnoseTypo(Corr,
2614 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2615 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002616 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002617 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002618 const CXXBaseSpecifier *DirectBaseSpec;
2619 const CXXBaseSpecifier *VirtualBaseSpec;
2620 if (FindBaseInitializer(*this, ClassDecl,
2621 Context.getTypeDeclType(Type),
2622 DirectBaseSpec, VirtualBaseSpec)) {
2623 // We have found a direct or virtual base class with a
2624 // similar name to what was typed; complain and initialize
2625 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002626 diagnoseTypo(Corr,
2627 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2628 << MemberOrBase << false,
2629 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002630
Richard Smithf9b15102013-08-17 00:46:16 +00002631 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2632 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002633 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002634 diag::note_base_class_specified_here)
2635 << BaseSpec->getType()
2636 << BaseSpec->getSourceRange();
2637
Douglas Gregor15e77a22009-12-31 09:10:24 +00002638 TyD = Type;
2639 }
2640 }
2641 }
2642
Douglas Gregora3b624a2010-01-19 06:46:48 +00002643 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002644 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002645 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002646 return true;
2647 }
John McCallb5a0d312009-12-21 10:41:20 +00002648 }
2649
Douglas Gregora3b624a2010-01-19 06:46:48 +00002650 if (BaseType.isNull()) {
2651 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002652 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002653 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002654 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2655 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002656 }
2657 }
Mike Stump11289f42009-09-09 15:08:12 +00002658
John McCallbcd03502009-12-07 02:54:59 +00002659 if (!TInfo)
2660 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002661
Sebastian Redla9351792012-02-11 23:51:47 +00002662 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002663}
2664
Chandler Carruth599deef2011-09-03 01:14:15 +00002665/// Checks a member initializer expression for cases where reference (or
2666/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002667static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2668 Expr *Init,
2669 SourceLocation IdLoc) {
2670 QualType MemberTy = Member->getType();
2671
2672 // We only handle pointers and references currently.
2673 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2674 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2675 return;
2676
2677 const bool IsPointer = MemberTy->isPointerType();
2678 if (IsPointer) {
2679 if (const UnaryOperator *Op
2680 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2681 // The only case we're worried about with pointers requires taking the
2682 // address.
2683 if (Op->getOpcode() != UO_AddrOf)
2684 return;
2685
2686 Init = Op->getSubExpr();
2687 } else {
2688 // We only handle address-of expression initializers for pointers.
2689 return;
2690 }
2691 }
2692
Richard Smithe3b28bc2013-06-12 21:51:50 +00002693 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002694 // We only warn when referring to a non-reference parameter declaration.
2695 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2696 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002697 return;
2698
2699 S.Diag(Init->getExprLoc(),
2700 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2701 : diag::warn_bind_ref_member_to_parameter)
2702 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002703 } else {
2704 // Other initializers are fine.
2705 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002706 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002707
2708 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2709 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002710}
2711
John McCallfaf5fb42010-08-26 23:41:50 +00002712MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002713Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002714 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002715 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2716 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2717 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002718 "Member must be a FieldDecl or IndirectFieldDecl");
2719
Sebastian Redla9351792012-02-11 23:51:47 +00002720 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002721 return true;
2722
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002723 if (Member->isInvalidDecl())
2724 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002725
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002726 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002727 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002728 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002729 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002730 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002731 } else {
2732 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002733 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002734 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002735
Sebastian Redla9351792012-02-11 23:51:47 +00002736 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002737
Sebastian Redla9351792012-02-11 23:51:47 +00002738 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002739 // Can't check initialization for a member of dependent type or when
2740 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002741 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002742 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002743 bool InitList = false;
2744 if (isa<InitListExpr>(Init)) {
2745 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002746 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002747 }
2748
Chandler Carruthd44c3102010-12-06 09:23:57 +00002749 // Initialize the member.
2750 InitializedEntity MemberEntity =
2751 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2752 : InitializedEntity::InitializeMember(IndirectMember, 0);
2753 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002754 InitList ? InitializationKind::CreateDirectList(IdLoc)
2755 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2756 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002757
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002758 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2759 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002760 if (MemberInit.isInvalid())
2761 return true;
2762
Richard Smith736a9472013-06-12 20:42:33 +00002763 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2764
Richard Smith945f8d32013-01-14 22:39:08 +00002765 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002766 // The initialization of each base and member constitutes a
2767 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002768 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002769 if (MemberInit.isInvalid())
2770 return true;
2771
Richard Smithd59b8322012-12-19 01:39:02 +00002772 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002773 }
2774
Chandler Carruthd44c3102010-12-06 09:23:57 +00002775 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002776 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2777 InitRange.getBegin(), Init,
2778 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002779 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002780 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2781 InitRange.getBegin(), Init,
2782 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002783 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002784}
2785
John McCallfaf5fb42010-08-26 23:41:50 +00002786MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002787Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002788 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002789 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002790 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002791 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002792 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002793 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002794
Sebastian Redl0501c632012-02-12 16:37:36 +00002795 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002796 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2798 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002799 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002800 }
2801
Sebastian Redla9351792012-02-11 23:51:47 +00002802 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002803 // Initialize the object.
2804 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2805 QualType(ClassDecl->getTypeForDecl(), 0));
2806 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002807 InitList ? InitializationKind::CreateDirectList(NameLoc)
2808 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2809 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002810 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002811 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002812 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002813 if (DelegationInit.isInvalid())
2814 return true;
2815
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002816 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2817 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002818
Richard Smith945f8d32013-01-14 22:39:08 +00002819 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002820 // The initialization of each base and member constitutes a
2821 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002822 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2823 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002824 if (DelegationInit.isInvalid())
2825 return true;
2826
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002827 // If we are in a dependent context, template instantiation will
2828 // perform this type-checking again. Just save the arguments that we
2829 // received in a ParenListExpr.
2830 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2831 // of the information that we have about the base
2832 // initializer. However, deconstructing the ASTs is a dicey process,
2833 // and this approach is far more likely to get the corner cases right.
2834 if (CurContext->isDependentContext())
2835 DelegationInit = Owned(Init);
2836
Sebastian Redla9351792012-02-11 23:51:47 +00002837 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002838 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002839 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002840}
2841
2842MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002843Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002844 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002845 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002846 SourceLocation BaseLoc
2847 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002848
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002849 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2850 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2851 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2852
2853 // C++ [class.base.init]p2:
2854 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002855 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002856 // of that class, the mem-initializer is ill-formed. A
2857 // mem-initializer-list can initialize a base class using any
2858 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002859 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002860
Sebastian Redla9351792012-02-11 23:51:47 +00002861 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002862 if (EllipsisLoc.isValid()) {
2863 // This is a pack expansion.
2864 if (!BaseType->containsUnexpandedParameterPack()) {
2865 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002866 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002867
Douglas Gregor44e7df62011-01-04 00:32:56 +00002868 EllipsisLoc = SourceLocation();
2869 }
2870 } else {
2871 // Check for any unexpanded parameter packs.
2872 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2873 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002874
Sebastian Redla9351792012-02-11 23:51:47 +00002875 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002876 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002877 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002878
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002879 // Check for direct and virtual base classes.
2880 const CXXBaseSpecifier *DirectBaseSpec = 0;
2881 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2882 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002883 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2884 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002885 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002886
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002887 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2888 VirtualBaseSpec);
2889
2890 // C++ [base.class.init]p2:
2891 // Unless the mem-initializer-id names a nonstatic data member of the
2892 // constructor's class or a direct or virtual base of that class, the
2893 // mem-initializer is ill-formed.
2894 if (!DirectBaseSpec && !VirtualBaseSpec) {
2895 // If the class has any dependent bases, then it's possible that
2896 // one of those types will resolve to the same type as
2897 // BaseType. Therefore, just treat this as a dependent base
2898 // class initialization. FIXME: Should we try to check the
2899 // initialization anyway? It seems odd.
2900 if (ClassDecl->hasAnyDependentBases())
2901 Dependent = true;
2902 else
2903 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2904 << BaseType << Context.getTypeDeclType(ClassDecl)
2905 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2906 }
2907 }
2908
2909 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002910 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002911
Sebastian Redla74948d2011-09-24 17:48:25 +00002912 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2913 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002914 InitRange.getBegin(), Init,
2915 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002916 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002917
2918 // C++ [base.class.init]p2:
2919 // If a mem-initializer-id is ambiguous because it designates both
2920 // a direct non-virtual base class and an inherited virtual base
2921 // class, the mem-initializer is ill-formed.
2922 if (DirectBaseSpec && VirtualBaseSpec)
2923 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002924 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002925
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002926 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002927 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002928 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002929
2930 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002931 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002932 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002933 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002934 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002935 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002936 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002937
2938 InitializedEntity BaseEntity =
2939 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2940 InitializationKind Kind =
2941 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2942 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2943 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002944 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2945 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002946 if (BaseInit.isInvalid())
2947 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002948
Richard Smith945f8d32013-01-14 22:39:08 +00002949 // C++11 [class.base.init]p7:
2950 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002951 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002952 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002953 if (BaseInit.isInvalid())
2954 return true;
2955
2956 // If we are in a dependent context, template instantiation will
2957 // perform this type-checking again. Just save the arguments that we
2958 // received in a ParenListExpr.
2959 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2960 // of the information that we have about the base
2961 // initializer. However, deconstructing the ASTs is a dicey process,
2962 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002963 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002964 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002965
Alexis Hunt1d792652011-01-08 20:30:50 +00002966 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002967 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002968 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002969 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002970 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002971}
2972
Sebastian Redl22653ba2011-08-30 19:58:05 +00002973// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002974static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2975 if (T.isNull()) T = E->getType();
2976 QualType TargetType = SemaRef.BuildReferenceType(
2977 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002978 SourceLocation ExprLoc = E->getLocStart();
2979 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2980 TargetType, ExprLoc);
2981
2982 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2983 SourceRange(ExprLoc, ExprLoc),
2984 E->getSourceRange()).take();
2985}
2986
Anders Carlsson1b00e242010-04-23 03:10:23 +00002987/// ImplicitInitializerKind - How an implicit base or member initializer should
2988/// initialize its base or member.
2989enum ImplicitInitializerKind {
2990 IIK_Default,
2991 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002992 IIK_Move,
2993 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002994};
2995
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002996static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002997BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002998 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002999 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003000 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003001 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003002 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003003 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3004 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003005
John McCalldadc5752010-08-24 06:29:42 +00003006 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003007
3008 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003009 case IIK_Inherit: {
3010 const CXXRecordDecl *Inherited =
3011 Constructor->getInheritedConstructor()->getParent();
3012 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3013 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3014 // C++11 [class.inhctor]p8:
3015 // Each expression in the expression-list is of the form
3016 // static_cast<T&&>(p), where p is the name of the corresponding
3017 // constructor parameter and T is the declared type of p.
3018 SmallVector<Expr*, 16> Args;
3019 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3020 ParmVarDecl *PD = Constructor->getParamDecl(I);
3021 ExprResult ArgExpr =
3022 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3023 VK_LValue, SourceLocation());
3024 if (ArgExpr.isInvalid())
3025 return true;
3026 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3027 }
3028
3029 InitializationKind InitKind = InitializationKind::CreateDirect(
3030 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003031 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003032 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3033 break;
3034 }
3035 }
3036 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003037 case IIK_Default: {
3038 InitializationKind InitKind
3039 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003040 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3041 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003042 break;
3043 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003044
Sebastian Redl22653ba2011-08-30 19:58:05 +00003045 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003046 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003047 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003048 ParmVarDecl *Param = Constructor->getParamDecl(0);
3049 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003050
Anders Carlsson1b00e242010-04-23 03:10:23 +00003051 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003052 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003053 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003054 Constructor->getLocation(), ParamType,
3055 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003056
Eli Friedmanfa0df832012-02-02 03:46:19 +00003057 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3058
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003059 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003060 QualType ArgTy =
3061 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3062 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003063
Sebastian Redl22653ba2011-08-30 19:58:05 +00003064 if (Moving) {
3065 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3066 }
3067
John McCallcf142162010-08-07 06:22:56 +00003068 CXXCastPath BasePath;
3069 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003070 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3071 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003072 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003073 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003074
Anders Carlsson1b00e242010-04-23 03:10:23 +00003075 InitializationKind InitKind
3076 = InitializationKind::CreateDirect(Constructor->getLocation(),
3077 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003078 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3079 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003080 break;
3081 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003082 }
John McCallb268a282010-08-23 23:25:46 +00003083
Douglas Gregora40433a2010-12-07 00:41:46 +00003084 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003085 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003086 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003087
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003088 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003089 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003090 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3091 SourceLocation()),
3092 BaseSpec->isVirtual(),
3093 SourceLocation(),
3094 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003095 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003096 SourceLocation());
3097
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003098 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003099}
3100
Sebastian Redl22653ba2011-08-30 19:58:05 +00003101static bool RefersToRValueRef(Expr *MemRef) {
3102 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3103 return Referenced->getType()->isRValueReferenceType();
3104}
3105
Anders Carlsson3c1db572010-04-23 02:15:47 +00003106static bool
3107BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003108 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003109 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003110 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003111 if (Field->isInvalidDecl())
3112 return true;
3113
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003114 SourceLocation Loc = Constructor->getLocation();
3115
Sebastian Redl22653ba2011-08-30 19:58:05 +00003116 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3117 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003118 ParmVarDecl *Param = Constructor->getParamDecl(0);
3119 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003120
3121 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003122 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3123 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003124
Anders Carlsson423f5d82010-04-23 16:04:08 +00003125 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003126 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003127 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003128 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003129
Eli Friedmanfa0df832012-02-02 03:46:19 +00003130 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3131
Sebastian Redl22653ba2011-08-30 19:58:05 +00003132 if (Moving) {
3133 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3134 }
3135
Douglas Gregor94f9a482010-05-05 05:51:00 +00003136 // Build a reference to this field within the parameter.
3137 CXXScopeSpec SS;
3138 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3139 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003140 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3141 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003142 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003143 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003144 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003145 ParamType, Loc,
3146 /*IsArrow=*/false,
3147 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003148 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003149 /*FirstQualifierInScope=*/0,
3150 MemberLookup,
3151 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003152 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003153 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003154
3155 // C++11 [class.copy]p15:
3156 // - if a member m has rvalue reference type T&&, it is direct-initialized
3157 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003158 if (RefersToRValueRef(CtorArg.get())) {
3159 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003160 }
3161
Douglas Gregor94f9a482010-05-05 05:51:00 +00003162 // When the field we are copying is an array, create index variables for
3163 // each dimension of the array. We use these index variables to subscript
3164 // the source array, and other clients (e.g., CodeGen) will perform the
3165 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003166 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003167 QualType BaseType = Field->getType();
3168 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003169 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003170 while (const ConstantArrayType *Array
3171 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003172 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003173 // Create the iteration variable for this array index.
3174 IdentifierInfo *IterationVarName = 0;
3175 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003176 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003177 llvm::raw_svector_ostream OS(Str);
3178 OS << "__i" << IndexVariables.size();
3179 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3180 }
3181 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003182 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003183 IterationVarName, SizeType,
3184 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003185 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003186 IndexVariables.push_back(IterationVar);
3187
3188 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003189 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003190 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003191 assert(!IterationVarRef.isInvalid() &&
3192 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003193 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3194 assert(!IterationVarRef.isInvalid() &&
3195 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003196
Douglas Gregor94f9a482010-05-05 05:51:00 +00003197 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003198 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003199 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003200 Loc);
3201 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003202 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003203
Douglas Gregor94f9a482010-05-05 05:51:00 +00003204 BaseType = Array->getElementType();
3205 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003206
3207 // The array subscript expression is an lvalue, which is wrong for moving.
3208 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003209 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003210
Douglas Gregor94f9a482010-05-05 05:51:00 +00003211 // Construct the entity that we will be initializing. For an array, this
3212 // will be first element in the array, which may require several levels
3213 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003214 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003215 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003216 if (Indirect)
3217 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3218 else
3219 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003220 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3221 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3222 0,
3223 Entities.back()));
3224
3225 // Direct-initialize to use the copy constructor.
3226 InitializationKind InitKind =
3227 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3228
Sebastian Redle9c4e842011-09-04 18:14:28 +00003229 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003230 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003231
John McCalldadc5752010-08-24 06:29:42 +00003232 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003233 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003234 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003235 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003236 if (MemberInit.isInvalid())
3237 return true;
3238
Douglas Gregor493627b2011-08-10 15:22:55 +00003239 if (Indirect) {
3240 assert(IndexVariables.size() == 0 &&
3241 "Indirect field improperly initialized");
3242 CXXMemberInit
3243 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3244 Loc, Loc,
3245 MemberInit.takeAs<Expr>(),
3246 Loc);
3247 } else
3248 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3249 Loc, MemberInit.takeAs<Expr>(),
3250 Loc,
3251 IndexVariables.data(),
3252 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003253 return false;
3254 }
3255
Richard Smithc2bc61b2013-03-18 21:12:30 +00003256 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3257 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003258
Anders Carlsson3c1db572010-04-23 02:15:47 +00003259 QualType FieldBaseElementType =
3260 SemaRef.Context.getBaseElementType(Field->getType());
3261
Anders Carlsson3c1db572010-04-23 02:15:47 +00003262 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003263 InitializedEntity InitEntity
3264 = Indirect? InitializedEntity::InitializeMember(Indirect)
3265 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003266 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003267 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003268
3269 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3270 ExprResult MemberInit =
3271 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003272
Douglas Gregora40433a2010-12-07 00:41:46 +00003273 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003274 if (MemberInit.isInvalid())
3275 return true;
3276
Douglas Gregor493627b2011-08-10 15:22:55 +00003277 if (Indirect)
3278 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3279 Indirect, Loc,
3280 Loc,
3281 MemberInit.get(),
3282 Loc);
3283 else
3284 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3285 Field, Loc, Loc,
3286 MemberInit.get(),
3287 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003288 return false;
3289 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003290
Alexis Hunt8b455182011-05-17 00:19:05 +00003291 if (!Field->getParent()->isUnion()) {
3292 if (FieldBaseElementType->isReferenceType()) {
3293 SemaRef.Diag(Constructor->getLocation(),
3294 diag::err_uninitialized_member_in_ctor)
3295 << (int)Constructor->isImplicit()
3296 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3297 << 0 << Field->getDeclName();
3298 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3299 return true;
3300 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003301
Alexis Hunt8b455182011-05-17 00:19:05 +00003302 if (FieldBaseElementType.isConstQualified()) {
3303 SemaRef.Diag(Constructor->getLocation(),
3304 diag::err_uninitialized_member_in_ctor)
3305 << (int)Constructor->isImplicit()
3306 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3307 << 1 << Field->getDeclName();
3308 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3309 return true;
3310 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003311 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003312
David Blaikiebbafb8a2012-03-11 07:00:24 +00003313 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003314 FieldBaseElementType->isObjCRetainableType() &&
3315 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003317 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003318 // Default-initialize Objective-C pointers to NULL.
3319 CXXMemberInit
3320 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3321 Loc, Loc,
3322 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3323 Loc);
3324 return false;
3325 }
3326
Anders Carlsson3c1db572010-04-23 02:15:47 +00003327 // Nothing to initialize.
3328 CXXMemberInit = 0;
3329 return false;
3330}
John McCallbc83b3f2010-05-20 23:23:51 +00003331
3332namespace {
3333struct BaseAndFieldInfo {
3334 Sema &S;
3335 CXXConstructorDecl *Ctor;
3336 bool AnyErrorsInInits;
3337 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003338 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003339 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003340 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003341
3342 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3343 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003344 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3345 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003346 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003347 else if (Generated && Ctor->isMoveConstructor())
3348 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003349 else if (Ctor->getInheritedConstructor())
3350 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003351 else
3352 IIK = IIK_Default;
3353 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003354
3355 bool isImplicitCopyOrMove() const {
3356 switch (IIK) {
3357 case IIK_Copy:
3358 case IIK_Move:
3359 return true;
3360
3361 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003362 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003363 return false;
3364 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003365
3366 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003367 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003368
3369 bool addFieldInitializer(CXXCtorInitializer *Init) {
3370 AllToInit.push_back(Init);
3371
3372 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003373 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003374 S.UnusedPrivateFields.remove(Init->getAnyMember());
3375
3376 return false;
3377 }
John McCallbc83b3f2010-05-20 23:23:51 +00003378
Richard Smithab44d5b2013-12-10 08:25:00 +00003379 bool isInactiveUnionMember(FieldDecl *Field) {
3380 RecordDecl *Record = Field->getParent();
3381 if (!Record->isUnion())
3382 return false;
3383
Richard Smith8d183852013-12-10 20:56:03 +00003384 if (FieldDecl *Active =
3385 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003386 return Active != Field->getCanonicalDecl();
3387
3388 // In an implicit copy or move constructor, ignore any in-class initializer.
3389 if (isImplicitCopyOrMove())
3390 return true;
3391
3392 // If there's no explicit initialization, the field is active only if it
3393 // has an in-class initializer...
3394 if (Field->hasInClassInitializer())
3395 return false;
3396 // ... or it's an anonymous struct or union whose class has an in-class
3397 // initializer.
3398 if (!Field->isAnonymousStructOrUnion())
3399 return true;
3400 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3401 return !FieldRD->hasInClassInitializer();
3402 }
3403
3404 /// \brief Determine whether the given field is, or is within, a union member
3405 /// that is inactive (because there was an initializer given for a different
3406 /// member of the union, or because the union was not initialized at all).
3407 bool isWithinInactiveUnionMember(FieldDecl *Field,
3408 IndirectFieldDecl *Indirect) {
3409 if (!Indirect)
3410 return isInactiveUnionMember(Field);
3411
Aaron Ballman29c94602014-03-07 18:36:15 +00003412 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003413 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003414 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003415 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003416 }
3417 return false;
3418 }
3419};
Richard Smithc94ec842011-09-19 13:34:43 +00003420}
3421
Douglas Gregor10f939c2011-11-02 23:04:16 +00003422/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3423/// array type.
3424static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3425 if (T->isIncompleteArrayType())
3426 return true;
3427
3428 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3429 if (!ArrayT->getSize())
3430 return true;
3431
3432 T = ArrayT->getElementType();
3433 }
3434
3435 return false;
3436}
3437
Richard Smith938f40b2011-06-11 17:19:42 +00003438static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003439 FieldDecl *Field,
3440 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003441 if (Field->isInvalidDecl())
3442 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003443
Chandler Carruth139e9622010-06-30 02:59:29 +00003444 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003445 if (CXXCtorInitializer *Init =
3446 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003447 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003448
Richard Smithab44d5b2013-12-10 08:25:00 +00003449 // C++11 [class.base.init]p8:
3450 // if the entity is a non-static data member that has a
3451 // brace-or-equal-initializer and either
3452 // -- the constructor's class is a union and no other variant member of that
3453 // union is designated by a mem-initializer-id or
3454 // -- the constructor's class is not a union, and, if the entity is a member
3455 // of an anonymous union, no other member of that union is designated by
3456 // a mem-initializer-id,
3457 // the entity is initialized as specified in [dcl.init].
3458 //
3459 // We also apply the same rules to handle anonymous structs within anonymous
3460 // unions.
3461 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3462 return false;
3463
Douglas Gregor7db3e952011-11-28 20:03:15 +00003464 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003465 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3466 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003467 CXXCtorInitializer *Init;
3468 if (Indirect)
3469 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3470 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003471 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003472 SourceLocation());
3473 else
3474 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3475 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003476 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003477 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003478 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003479 }
3480
Douglas Gregor10f939c2011-11-02 23:04:16 +00003481 // Don't initialize incomplete or zero-length arrays.
3482 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3483 return false;
3484
John McCallbc83b3f2010-05-20 23:23:51 +00003485 // Don't try to build an implicit initializer if there were semantic
3486 // errors in any of the initializers (and therefore we might be
3487 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003488 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003489 return false;
3490
Alexis Hunt1d792652011-01-08 20:30:50 +00003491 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003492 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3493 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003494 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003495
Richard Smith0a8cfc72012-08-07 21:30:42 +00003496 if (!Init)
3497 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003498
Richard Smith0a8cfc72012-08-07 21:30:42 +00003499 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003500}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003501
3502bool
3503Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3504 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003505 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003506 Constructor->setNumCtorInitializers(1);
3507 CXXCtorInitializer **initializer =
3508 new (Context) CXXCtorInitializer*[1];
3509 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3510 Constructor->setCtorInitializers(initializer);
3511
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003512 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003513 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003514 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3515 }
3516
Alexis Hunte2622992011-05-05 00:05:47 +00003517 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003518
Alexis Hunt61bc1732011-05-01 07:04:31 +00003519 return false;
3520}
Douglas Gregor493627b2011-08-10 15:22:55 +00003521
David Blaikie3fc2f912013-01-17 05:26:25 +00003522bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3523 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003524 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003525 // Just store the initializers as written, they will be checked during
3526 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003527 if (!Initializers.empty()) {
3528 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003529 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003530 new (Context) CXXCtorInitializer*[Initializers.size()];
3531 memcpy(baseOrMemberInitializers, Initializers.data(),
3532 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003533 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003534 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003535
3536 // Let template instantiation know whether we had errors.
3537 if (AnyErrors)
3538 Constructor->setInvalidDecl();
3539
Anders Carlssondb0a9652010-04-02 06:26:44 +00003540 return false;
3541 }
3542
John McCallbc83b3f2010-05-20 23:23:51 +00003543 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003544
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003545 // We need to build the initializer AST according to order of construction
3546 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003547 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003548 if (!ClassDecl)
3549 return true;
3550
Eli Friedman9cf6b592009-11-09 19:20:36 +00003551 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003552
David Blaikie3fc2f912013-01-17 05:26:25 +00003553 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003554 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003555
Anders Carlssondb0a9652010-04-02 06:26:44 +00003556 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003557 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003558 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003559 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003560
3561 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003562 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003563 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003564 if (FD && FD->getParent()->isUnion())
3565 Info.ActiveUnionMember.insert(std::make_pair(
3566 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3567 }
3568 } else if (FieldDecl *FD = Member->getMember()) {
3569 if (FD->getParent()->isUnion())
3570 Info.ActiveUnionMember.insert(std::make_pair(
3571 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3572 }
3573 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003574 }
3575
Anders Carlsson43c64af2010-04-21 19:52:01 +00003576 // Keep track of the direct virtual bases.
3577 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003578 for (auto &I : ClassDecl->bases()) {
3579 if (I.isVirtual())
3580 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003581 }
3582
Anders Carlssondb0a9652010-04-02 06:26:44 +00003583 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003584 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003585 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003586 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003587 // [class.base.init]p7, per DR257:
3588 // A mem-initializer where the mem-initializer-id names a virtual base
3589 // class is ignored during execution of a constructor of any class that
3590 // is not the most derived class.
3591 if (ClassDecl->isAbstract()) {
3592 // FIXME: Provide a fixit to remove the base specifier. This requires
3593 // tracking the location of the associated comma for a base specifier.
3594 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003595 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003596 DiagnoseAbstractType(ClassDecl);
3597 }
3598
John McCallbc83b3f2010-05-20 23:23:51 +00003599 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003600 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3601 // [class.base.init]p8, per DR257:
3602 // If a given [...] base class is not named by a mem-initializer-id
3603 // [...] and the entity is not a virtual base class of an abstract
3604 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003605 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003606 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003607 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003608 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003609 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003610 HadError = true;
3611 continue;
3612 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003613
John McCallbc83b3f2010-05-20 23:23:51 +00003614 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003615 }
3616 }
Mike Stump11289f42009-09-09 15:08:12 +00003617
John McCallbc83b3f2010-05-20 23:23:51 +00003618 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003619 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003620 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003621 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003622 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003623
Alexis Hunt1d792652011-01-08 20:30:50 +00003624 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003625 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003626 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003627 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003628 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003629 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003630 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003631 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003632 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003633 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003634 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003635
John McCallbc83b3f2010-05-20 23:23:51 +00003636 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003637 }
3638 }
Mike Stump11289f42009-09-09 15:08:12 +00003639
John McCallbc83b3f2010-05-20 23:23:51 +00003640 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003641 for (auto *Mem : ClassDecl->decls()) {
3642 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003643 // C++ [class.bit]p2:
3644 // A declaration for a bit-field that omits the identifier declares an
3645 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3646 // initialized.
3647 if (F->isUnnamedBitfield())
3648 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003649
Sebastian Redl22653ba2011-08-30 19:58:05 +00003650 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003651 // handle anonymous struct/union fields based on their individual
3652 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003653 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003654 continue;
3655
3656 if (CollectFieldInitializer(*this, Info, F))
3657 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003658 continue;
3659 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003660
3661 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003662 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003663 continue;
3664
Aaron Ballman629afae2014-03-07 19:56:05 +00003665 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003666 if (F->getType()->isIncompleteArrayType()) {
3667 assert(ClassDecl->hasFlexibleArrayMember() &&
3668 "Incomplete array type is not valid");
3669 continue;
3670 }
3671
Douglas Gregor493627b2011-08-10 15:22:55 +00003672 // Initialize each field of an anonymous struct individually.
3673 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3674 HadError = true;
3675
3676 continue;
3677 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003678 }
Mike Stump11289f42009-09-09 15:08:12 +00003679
David Blaikie3fc2f912013-01-17 05:26:25 +00003680 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003681 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003682 Constructor->setNumCtorInitializers(NumInitializers);
3683 CXXCtorInitializer **baseOrMemberInitializers =
3684 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003685 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003686 NumInitializers * sizeof(CXXCtorInitializer*));
3687 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003688
John McCalla6309952010-03-16 21:39:52 +00003689 // Constructors implicitly reference the base and member
3690 // destructors.
3691 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3692 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003693 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003694
3695 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003696}
3697
David Blaikieb61b8152013-01-17 08:49:22 +00003698static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003699 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003700 const RecordDecl *RD = RT->getDecl();
3701 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003702 for (auto *Field : RD->fields())
3703 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003704 return;
3705 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003706 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003707 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003708}
3709
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003710static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3711 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003712}
3713
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003714static const void *GetKeyForMember(ASTContext &Context,
3715 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003716 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003717 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003718
Richard Smithcd45dbc2014-04-19 03:48:30 +00003719 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003720}
3721
David Blaikie3fc2f912013-01-17 05:26:25 +00003722static void DiagnoseBaseOrMemInitializerOrder(
3723 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3724 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003725 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003726 return;
Mike Stump11289f42009-09-09 15:08:12 +00003727
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003728 // Don't check initializers order unless the warning is enabled at the
3729 // location of at least one initializer.
3730 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003731 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003732 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003733 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3734 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003735 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003736 ShouldCheckOrder = true;
3737 break;
3738 }
3739 }
3740 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003741 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003742
John McCallbb7b6582010-04-10 07:37:23 +00003743 // Build the list of bases and members in the order that they'll
3744 // actually be initialized. The explicit initializers should be in
3745 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003746 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003747
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003748 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3749
John McCallbb7b6582010-04-10 07:37:23 +00003750 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003751 for (const auto &VBase : ClassDecl->vbases())
3752 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003753
John McCallbb7b6582010-04-10 07:37:23 +00003754 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003755 for (const auto &Base : ClassDecl->bases()) {
3756 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003757 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003758 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003759 }
Mike Stump11289f42009-09-09 15:08:12 +00003760
John McCallbb7b6582010-04-10 07:37:23 +00003761 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003762 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003763 if (Field->isUnnamedBitfield())
3764 continue;
3765
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003766 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003767 }
3768
John McCallbb7b6582010-04-10 07:37:23 +00003769 unsigned NumIdealInits = IdealInitKeys.size();
3770 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003771
Alexis Hunt1d792652011-01-08 20:30:50 +00003772 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003773 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003774 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003775 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003776
3777 // Scan forward to try to find this initializer in the idealized
3778 // initializers list.
3779 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3780 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003781 break;
John McCallbb7b6582010-04-10 07:37:23 +00003782
3783 // If we didn't find this initializer, it must be because we
3784 // scanned past it on a previous iteration. That can only
3785 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003786 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003787 Sema::SemaDiagnosticBuilder D =
3788 SemaRef.Diag(PrevInit->getSourceLocation(),
3789 diag::warn_initializer_out_of_order);
3790
Francois Pichetd583da02010-12-04 09:14:42 +00003791 if (PrevInit->isAnyMemberInitializer())
3792 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003793 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003794 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003795
Francois Pichetd583da02010-12-04 09:14:42 +00003796 if (Init->isAnyMemberInitializer())
3797 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003798 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003799 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003800
3801 // Move back to the initializer's location in the ideal list.
3802 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3803 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003804 break;
John McCallbb7b6582010-04-10 07:37:23 +00003805
3806 assert(IdealIndex != NumIdealInits &&
3807 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003808 }
John McCallbb7b6582010-04-10 07:37:23 +00003809
3810 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003811 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003812}
3813
John McCall23eebd92010-04-10 09:28:51 +00003814namespace {
3815bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003816 CXXCtorInitializer *Init,
3817 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003818 if (!PrevInit) {
3819 PrevInit = Init;
3820 return false;
3821 }
3822
Douglas Gregorea306a12013-03-25 23:28:23 +00003823 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003824 S.Diag(Init->getSourceLocation(),
3825 diag::err_multiple_mem_initialization)
3826 << Field->getDeclName()
3827 << Init->getSourceRange();
3828 else {
John McCall424cec92011-01-19 06:33:43 +00003829 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003830 assert(BaseClass && "neither field nor base");
3831 S.Diag(Init->getSourceLocation(),
3832 diag::err_multiple_base_initialization)
3833 << QualType(BaseClass, 0)
3834 << Init->getSourceRange();
3835 }
3836 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3837 << 0 << PrevInit->getSourceRange();
3838
3839 return true;
3840}
3841
Alexis Hunt1d792652011-01-08 20:30:50 +00003842typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003843typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3844
3845bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003846 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003847 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003848 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003849 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003850 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003851
3852 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003853 if (Parent->isUnion()) {
3854 UnionEntry &En = Unions[Parent];
3855 if (En.first && En.first != Child) {
3856 S.Diag(Init->getSourceLocation(),
3857 diag::err_multiple_mem_union_initialization)
3858 << Field->getDeclName()
3859 << Init->getSourceRange();
3860 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3861 << 0 << En.second->getSourceRange();
3862 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003863 }
3864 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003865 En.first = Child;
3866 En.second = Init;
3867 }
David Blaikie0f65d592011-11-17 06:01:57 +00003868 if (!Parent->isAnonymousStructOrUnion())
3869 return false;
John McCall23eebd92010-04-10 09:28:51 +00003870 }
3871
3872 Child = Parent;
3873 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003874 }
John McCall23eebd92010-04-10 09:28:51 +00003875
3876 return false;
3877}
3878}
3879
Anders Carlssone857b292010-04-02 03:37:03 +00003880/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003881void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003882 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003883 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003884 bool AnyErrors) {
3885 if (!ConstructorDecl)
3886 return;
3887
3888 AdjustDeclIfTemplate(ConstructorDecl);
3889
3890 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003891 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003892
3893 if (!Constructor) {
3894 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3895 return;
3896 }
3897
John McCall23eebd92010-04-10 09:28:51 +00003898 // Mapping for the duplicate initializers check.
3899 // For member initializers, this is keyed with a FieldDecl*.
3900 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003901 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003902
3903 // Mapping for the inconsistent anonymous-union initializers check.
3904 RedundantUnionMap MemberUnions;
3905
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003906 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003907 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003908 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003909
Abramo Bagnara341d7832010-05-26 18:09:23 +00003910 // Set the source order index.
3911 Init->setSourceOrder(i);
3912
Francois Pichetd583da02010-12-04 09:14:42 +00003913 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003914 const void *Key = GetKeyForMember(Context, Init);
3915 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003916 CheckRedundantUnionInit(*this, Init, MemberUnions))
3917 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003918 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003919 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003920 if (CheckRedundantInit(*this, Init, Members[Key]))
3921 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003922 } else {
3923 assert(Init->isDelegatingInitializer());
3924 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003925 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003926 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003927 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003928 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003929 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003930 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003931 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003932 // Return immediately as the initializer is set.
3933 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003934 }
Anders Carlssone857b292010-04-02 03:37:03 +00003935 }
3936
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003937 if (HadError)
3938 return;
3939
David Blaikie3fc2f912013-01-17 05:26:25 +00003940 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003941
David Blaikie3fc2f912013-01-17 05:26:25 +00003942 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003943
Richard Trieuef64e942013-10-25 00:56:00 +00003944 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003945}
3946
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003947void
John McCalla6309952010-03-16 21:39:52 +00003948Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3949 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003950 // Ignore dependent contexts. Also ignore unions, since their members never
3951 // have destructors implicitly called.
3952 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003953 return;
John McCall1064d7e2010-03-16 05:22:47 +00003954
3955 // FIXME: all the access-control diagnostics are positioned on the
3956 // field/base declaration. That's probably good; that said, the
3957 // user might reasonably want to know why the destructor is being
3958 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003959
Anders Carlssondee9a302009-11-17 04:44:12 +00003960 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003961 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003962 if (Field->isInvalidDecl())
3963 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003964
3965 // Don't destroy incomplete or zero-length arrays.
3966 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3967 continue;
3968
Anders Carlssondee9a302009-11-17 04:44:12 +00003969 QualType FieldType = Context.getBaseElementType(Field->getType());
3970
3971 const RecordType* RT = FieldType->getAs<RecordType>();
3972 if (!RT)
3973 continue;
3974
3975 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003976 if (FieldClassDecl->isInvalidDecl())
3977 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003978 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003979 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003980 // The destructor for an implicit anonymous union member is never invoked.
3981 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3982 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003983
Douglas Gregore71edda2010-07-01 22:47:18 +00003984 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003985 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003986 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003987 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003988 << Field->getDeclName()
3989 << FieldType);
3990
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003991 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00003992 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00003993 }
3994
John McCall1064d7e2010-03-16 05:22:47 +00003995 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3996
Anders Carlssondee9a302009-11-17 04:44:12 +00003997 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003998 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00003999 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004000 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004001
4002 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004003 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004004 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004005
John McCall1064d7e2010-03-16 05:22:47 +00004006 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004007 // If our base class is invalid, we probably can't get its dtor anyway.
4008 if (BaseClassDecl->isInvalidDecl())
4009 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004010 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004011 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004012
Douglas Gregore71edda2010-07-01 22:47:18 +00004013 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004014 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004015
4016 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004017 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004018 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004019 << Base.getType()
4020 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004021 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004022
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004023 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004024 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004025 }
4026
4027 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004028 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004029 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004030 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004031
4032 // Ignore direct virtual bases.
4033 if (DirectVirtualBases.count(RT))
4034 continue;
4035
John McCall1064d7e2010-03-16 05:22:47 +00004036 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004037 // If our base class is invalid, we probably can't get its dtor anyway.
4038 if (BaseClassDecl->isInvalidDecl())
4039 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004040 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004041 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004042
Douglas Gregore71edda2010-07-01 22:47:18 +00004043 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004044 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004045 if (CheckDestructorAccess(
4046 ClassDecl->getLocation(), Dtor,
4047 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004048 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004049 Context.getTypeDeclType(ClassDecl)) ==
4050 AR_accessible) {
4051 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004052 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004053 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4054 SourceRange(), DeclarationName(), 0);
4055 }
John McCall1064d7e2010-03-16 05:22:47 +00004056
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004057 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004058 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004059 }
4060}
4061
John McCall48871652010-08-21 09:40:31 +00004062void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004063 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004064 return;
Mike Stump11289f42009-09-09 15:08:12 +00004065
Mike Stump11289f42009-09-09 15:08:12 +00004066 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004067 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004068 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004069 DiagnoseUninitializedFields(*this, Constructor);
4070 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004071}
4072
Mike Stump11289f42009-09-09 15:08:12 +00004073bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004074 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004075 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4076 unsigned DiagID;
4077 AbstractDiagSelID SelID;
4078
4079 public:
4080 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4081 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004082
Craig Toppera798a9d2014-03-02 09:32:10 +00004083 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004084 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004085 if (SelID == -1)
4086 S.Diag(Loc, DiagID) << T;
4087 else
4088 S.Diag(Loc, DiagID) << SelID << T;
4089 }
4090 } Diagnoser(DiagID, SelID);
4091
4092 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004093}
4094
Anders Carlssoneabf7702009-08-27 00:13:57 +00004095bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004096 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004097 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004099
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004100 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004101 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004102
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004103 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004104 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004106 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004107
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004108 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004109 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004112 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004113 if (!RT)
4114 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCall67da35c2010-02-04 22:26:26 +00004116 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004117
John McCall02db245d2010-08-18 09:41:07 +00004118 // We can't answer whether something is abstract until it has a
4119 // definition. If it's currently being defined, we'll walk back
4120 // over all the declarations when we have a full definition.
4121 const CXXRecordDecl *Def = RD->getDefinition();
4122 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004123 return false;
4124
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004125 if (!RD->isAbstract())
4126 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregorae298422012-05-04 17:09:59 +00004128 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004129 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004130
John McCall02db245d2010-08-18 09:41:07 +00004131 return true;
4132}
4133
4134void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4135 // Check if we've already emitted the list of pure virtual functions
4136 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004137 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004138 return;
Mike Stump11289f42009-09-09 15:08:12 +00004139
Richard Smithbc46e432013-07-22 02:56:56 +00004140 // If the diagnostic is suppressed, don't emit the notes. We're only
4141 // going to emit them once, so try to attach them to a diagnostic we're
4142 // actually going to show.
4143 if (Diags.isLastDiagnosticIgnored())
4144 return;
4145
Douglas Gregor4165bd62010-03-23 23:47:56 +00004146 CXXFinalOverriderMap FinalOverriders;
4147 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004148
Anders Carlssona2f74f32010-06-03 01:00:02 +00004149 // Keep a set of seen pure methods so we won't diagnose the same method
4150 // more than once.
4151 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4152
Douglas Gregor4165bd62010-03-23 23:47:56 +00004153 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4154 MEnd = FinalOverriders.end();
4155 M != MEnd;
4156 ++M) {
4157 for (OverridingMethods::iterator SO = M->second.begin(),
4158 SOEnd = M->second.end();
4159 SO != SOEnd; ++SO) {
4160 // C++ [class.abstract]p4:
4161 // A class is abstract if it contains or inherits at least one
4162 // pure virtual function for which the final overrider is pure
4163 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004164
Douglas Gregor4165bd62010-03-23 23:47:56 +00004165 //
4166 if (SO->second.size() != 1)
4167 continue;
4168
4169 if (!SO->second.front().Method->isPure())
4170 continue;
4171
Anders Carlssona2f74f32010-06-03 01:00:02 +00004172 if (!SeenPureMethods.insert(SO->second.front().Method))
4173 continue;
4174
Douglas Gregor4165bd62010-03-23 23:47:56 +00004175 Diag(SO->second.front().Method->getLocation(),
4176 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004177 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004178 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004179 }
4180
4181 if (!PureVirtualClassDiagSet)
4182 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4183 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004184}
4185
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004186namespace {
John McCall02db245d2010-08-18 09:41:07 +00004187struct AbstractUsageInfo {
4188 Sema &S;
4189 CXXRecordDecl *Record;
4190 CanQualType AbstractType;
4191 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004192
John McCall02db245d2010-08-18 09:41:07 +00004193 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4194 : S(S), Record(Record),
4195 AbstractType(S.Context.getCanonicalType(
4196 S.Context.getTypeDeclType(Record))),
4197 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004198
John McCall02db245d2010-08-18 09:41:07 +00004199 void DiagnoseAbstractType() {
4200 if (Invalid) return;
4201 S.DiagnoseAbstractType(Record);
4202 Invalid = true;
4203 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004204
John McCall02db245d2010-08-18 09:41:07 +00004205 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4206};
4207
4208struct CheckAbstractUsage {
4209 AbstractUsageInfo &Info;
4210 const NamedDecl *Ctx;
4211
4212 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4213 : Info(Info), Ctx(Ctx) {}
4214
4215 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4216 switch (TL.getTypeLocClass()) {
4217#define ABSTRACT_TYPELOC(CLASS, PARENT)
4218#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004219 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004220#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004221 }
John McCall02db245d2010-08-18 09:41:07 +00004222 }
Mike Stump11289f42009-09-09 15:08:12 +00004223
John McCall02db245d2010-08-18 09:41:07 +00004224 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004225 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004226 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4227 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004228 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004229
4230 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004231 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004232 }
John McCall02db245d2010-08-18 09:41:07 +00004233 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004234
John McCall02db245d2010-08-18 09:41:07 +00004235 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4236 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4237 }
Mike Stump11289f42009-09-09 15:08:12 +00004238
John McCall02db245d2010-08-18 09:41:07 +00004239 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4240 // Visit the type parameters from a permissive context.
4241 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4242 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4243 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4244 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4245 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4246 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004247 }
John McCall02db245d2010-08-18 09:41:07 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
John McCall02db245d2010-08-18 09:41:07 +00004250 // Visit pointee types from a permissive context.
4251#define CheckPolymorphic(Type) \
4252 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4253 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4254 }
4255 CheckPolymorphic(PointerTypeLoc)
4256 CheckPolymorphic(ReferenceTypeLoc)
4257 CheckPolymorphic(MemberPointerTypeLoc)
4258 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004259 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004260
John McCall02db245d2010-08-18 09:41:07 +00004261 /// Handle all the types we haven't given a more specific
4262 /// implementation for above.
4263 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4264 // Every other kind of type that we haven't called out already
4265 // that has an inner type is either (1) sugar or (2) contains that
4266 // inner type in some way as a subobject.
4267 if (TypeLoc Next = TL.getNextTypeLoc())
4268 return Visit(Next, Sel);
4269
4270 // If there's no inner type and we're in a permissive context,
4271 // don't diagnose.
4272 if (Sel == Sema::AbstractNone) return;
4273
4274 // Check whether the type matches the abstract type.
4275 QualType T = TL.getType();
4276 if (T->isArrayType()) {
4277 Sel = Sema::AbstractArrayType;
4278 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004279 }
John McCall02db245d2010-08-18 09:41:07 +00004280 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4281 if (CT != Info.AbstractType) return;
4282
4283 // It matched; do some magic.
4284 if (Sel == Sema::AbstractArrayType) {
4285 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4286 << T << TL.getSourceRange();
4287 } else {
4288 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4289 << Sel << T << TL.getSourceRange();
4290 }
4291 Info.DiagnoseAbstractType();
4292 }
4293};
4294
4295void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4296 Sema::AbstractDiagSelID Sel) {
4297 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4298}
4299
4300}
4301
4302/// Check for invalid uses of an abstract type in a method declaration.
4303static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4304 CXXMethodDecl *MD) {
4305 // No need to do the check on definitions, which require that
4306 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004307 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004308 return;
4309
4310 // For safety's sake, just ignore it if we don't have type source
4311 // information. This should never happen for non-implicit methods,
4312 // but...
4313 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4314 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4315}
4316
4317/// Check for invalid uses of an abstract type within a class definition.
4318static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4319 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004320 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004321 if (D->isImplicit()) continue;
4322
4323 // Methods and method templates.
4324 if (isa<CXXMethodDecl>(D)) {
4325 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4326 } else if (isa<FunctionTemplateDecl>(D)) {
4327 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4328 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4329
4330 // Fields and static variables.
4331 } else if (isa<FieldDecl>(D)) {
4332 FieldDecl *FD = cast<FieldDecl>(D);
4333 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4334 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4335 } else if (isa<VarDecl>(D)) {
4336 VarDecl *VD = cast<VarDecl>(D);
4337 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4338 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4339
4340 // Nested classes and class templates.
4341 } else if (isa<CXXRecordDecl>(D)) {
4342 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4343 } else if (isa<ClassTemplateDecl>(D)) {
4344 CheckAbstractClassUsage(Info,
4345 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4346 }
4347 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004348}
4349
Douglas Gregorc99f1552009-12-03 18:33:45 +00004350/// \brief Perform semantic checks on a class definition that has been
4351/// completing, introducing implicitly-declared members, checking for
4352/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004353void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004354 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004355 return;
4356
John McCall02db245d2010-08-18 09:41:07 +00004357 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4358 AbstractUsageInfo Info(*this, Record);
4359 CheckAbstractClassUsage(Info, Record);
4360 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004361
4362 // If this is not an aggregate type and has no user-declared constructor,
4363 // complain about any non-static data members of reference or const scalar
4364 // type, since they will never get initializers.
4365 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004366 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4367 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004368 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004369 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004370 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004371 continue;
4372
Douglas Gregor454a5b62010-04-15 00:00:53 +00004373 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004374 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004375 if (!Complained) {
4376 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4377 << Record->getTagKind() << Record;
4378 Complained = true;
4379 }
4380
4381 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4382 << F->getType()->isReferenceType()
4383 << F->getDeclName();
4384 }
4385 }
4386 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004387
Anders Carlssone771e762011-01-25 18:08:22 +00004388 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004389 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004390
4391 if (Record->getIdentifier()) {
4392 // C++ [class.mem]p13:
4393 // If T is the name of a class, then each of the following shall have a
4394 // name different from T:
4395 // - every member of every anonymous union that is a member of class T.
4396 //
4397 // C++ [class.mem]p14:
4398 // In addition, if class T has a user-declared constructor (12.1), every
4399 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004400 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4401 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4402 ++I) {
4403 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004404 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4405 isa<IndirectFieldDecl>(D)) {
4406 Diag(D->getLocation(), diag::err_member_name_of_class)
4407 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004408 break;
4409 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004410 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004411 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004412
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004413 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004414 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004415 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004416 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4417 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004418 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4419 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4420 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004421
David Majnemera5433082013-10-18 00:33:31 +00004422 if (Record->isAbstract()) {
4423 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4424 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4425 << FA->isSpelledAsSealed();
4426 DiagnoseAbstractType(Record);
4427 }
David Blaikie348df502012-09-21 03:21:07 +00004428 }
4429
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004430 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004431 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004432 // See if a method overloads virtual methods in a base
4433 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004434 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004435 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004436
4437 // Check whether the explicitly-defaulted special members are valid.
4438 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004439 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004440
4441 // For an explicitly defaulted or deleted special member, we defer
4442 // determining triviality until the class is complete. That time is now!
4443 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004444 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004445 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004446 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004447
4448 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004449 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004450 }
4451 }
4452 }
4453 }
4454
4455 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4456 // function that is not a constructor declares that member function to be
4457 // const. [...] The class of which that function is a member shall be
4458 // a literal type.
4459 //
4460 // If the class has virtual bases, any constexpr members will already have
4461 // been diagnosed by the checks performed on the member declaration, so
4462 // suppress this (less useful) diagnostic.
4463 //
4464 // We delay this until we know whether an explicitly-defaulted (or deleted)
4465 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004466 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004467 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004468 for (const auto *M : Record->methods()) {
4469 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004470 switch (Record->getTemplateSpecializationKind()) {
4471 case TSK_ImplicitInstantiation:
4472 case TSK_ExplicitInstantiationDeclaration:
4473 case TSK_ExplicitInstantiationDefinition:
4474 // If a template instantiates to a non-literal type, but its members
4475 // instantiate to constexpr functions, the template is technically
4476 // ill-formed, but we allow it for sanity.
4477 continue;
4478
4479 case TSK_Undeclared:
4480 case TSK_ExplicitSpecialization:
4481 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4482 diag::err_constexpr_method_non_literal);
4483 break;
4484 }
4485
4486 // Only produce one error per class.
4487 break;
4488 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004489 }
4490 }
Sebastian Redl08905022011-02-05 19:23:19 +00004491
John McCall95833f32014-02-27 20:30:49 +00004492 // ms_struct is a request to use the same ABI rules as MSVC. Check
4493 // whether this class uses any C++ features that are implemented
4494 // completely differently in MSVC, and if so, emit a diagnostic.
4495 // That diagnostic defaults to an error, but we allow projects to
4496 // map it down to a warning (or ignore it). It's a fairly common
4497 // practice among users of the ms_struct pragma to mass-annotate
4498 // headers, sweeping up a bunch of types that the project doesn't
4499 // really rely on MSVC-compatible layout for. We must therefore
4500 // support "ms_struct except for C++ stuff" as a secondary ABI.
4501 if (Record->isMsStruct(Context) &&
4502 (Record->isPolymorphic() || Record->getNumBases())) {
4503 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004504 }
4505
Richard Smithc2bc61b2013-03-18 21:12:30 +00004506 // Declare inheriting constructors. We do this eagerly here because:
4507 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004508 // constructors from different classes.
4509 // - The lazy declaration of the other implicit constructors is so as to not
4510 // waste space and performance on classes that are not meant to be
4511 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004512 // have inheriting constructors.
4513 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004514}
4515
Richard Smith41c35d62013-11-27 03:39:20 +00004516/// Look up the special member function that would be called by a special
4517/// member function for a subobject of class type.
4518///
4519/// \param Class The class type of the subobject.
4520/// \param CSM The kind of special member function.
4521/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4522/// \param ConstRHS True if this is a copy operation with a const object
4523/// on its RHS, that is, if the argument to the outer special member
4524/// function is 'const' and this is not a field marked 'mutable'.
4525static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4526 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4527 unsigned FieldQuals, bool ConstRHS) {
4528 unsigned LHSQuals = 0;
4529 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4530 LHSQuals = FieldQuals;
4531
4532 unsigned RHSQuals = FieldQuals;
4533 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4534 RHSQuals = 0;
4535 else if (ConstRHS)
4536 RHSQuals |= Qualifiers::Const;
4537
4538 return S.LookupSpecialMember(Class, CSM,
4539 RHSQuals & Qualifiers::Const,
4540 RHSQuals & Qualifiers::Volatile,
4541 false,
4542 LHSQuals & Qualifiers::Const,
4543 LHSQuals & Qualifiers::Volatile);
4544}
4545
Richard Smithb5800092012-06-10 05:43:50 +00004546/// Is the special member function which would be selected to perform the
4547/// specified operation on the specified class type a constexpr constructor?
4548static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4549 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004550 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004551 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004552 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004553 if (!SMOR || !SMOR->getMethod())
4554 // A constructor we wouldn't select can't be "involved in initializing"
4555 // anything.
4556 return true;
4557 return SMOR->getMethod()->isConstexpr();
4558}
4559
4560/// Determine whether the specified special member function would be constexpr
4561/// if it were implicitly defined.
4562static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4563 Sema::CXXSpecialMember CSM,
4564 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004565 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004566 return false;
4567
4568 // C++11 [dcl.constexpr]p4:
4569 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004570 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004571 switch (CSM) {
4572 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004573 // Since default constructor lookup is essentially trivial (and cannot
4574 // involve, for instance, template instantiation), we compute whether a
4575 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4576 //
4577 // This is important for performance; we need to know whether the default
4578 // constructor is constexpr to determine whether the type is a literal type.
4579 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4580
Richard Smithb5800092012-06-10 05:43:50 +00004581 case Sema::CXXCopyConstructor:
4582 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004583 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004584 break;
4585
4586 case Sema::CXXCopyAssignment:
4587 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004588 if (!S.getLangOpts().CPlusPlus1y)
4589 return false;
4590 // In C++1y, we need to perform overload resolution.
4591 Ctor = false;
4592 break;
4593
Richard Smithb5800092012-06-10 05:43:50 +00004594 case Sema::CXXDestructor:
4595 case Sema::CXXInvalid:
4596 return false;
4597 }
4598
4599 // -- if the class is a non-empty union, or for each non-empty anonymous
4600 // union member of a non-union class, exactly one non-static data member
4601 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004602 //
4603 // If we squint, this is guaranteed, since exactly one non-static data member
4604 // will be initialized (if the constructor isn't deleted), we just don't know
4605 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004606 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004607 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004608
4609 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004610 if (Ctor && ClassDecl->getNumVBases())
4611 return false;
4612
4613 // C++1y [class.copy]p26:
4614 // -- [the class] is a literal type, and
4615 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004616 return false;
4617
4618 // -- every constructor involved in initializing [...] base class
4619 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004620 // -- the assignment operator selected to copy/move each direct base
4621 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004622 for (const auto &B : ClassDecl->bases()) {
4623 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004624 if (!BaseType) continue;
4625
4626 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004627 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004628 return false;
4629 }
4630
4631 // -- every constructor involved in initializing non-static data members
4632 // [...] shall be a constexpr constructor;
4633 // -- every non-static data member and base class sub-object shall be
4634 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004635 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004636 // thereof), the assignment operator selected to copy/move that member is
4637 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004638 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004639 if (F->isInvalidDecl())
4640 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004641 QualType BaseType = S.Context.getBaseElementType(F->getType());
4642 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004643 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004644 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4645 BaseType.getCVRQualifiers(),
4646 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004647 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004648 }
4649 }
4650
4651 // All OK, it's constexpr!
4652 return true;
4653}
4654
Richard Smithd3b5c9082012-07-27 04:22:15 +00004655static Sema::ImplicitExceptionSpecification
4656computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4657 switch (S.getSpecialMember(MD)) {
4658 case Sema::CXXDefaultConstructor:
4659 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4660 case Sema::CXXCopyConstructor:
4661 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4662 case Sema::CXXCopyAssignment:
4663 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4664 case Sema::CXXMoveConstructor:
4665 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4666 case Sema::CXXMoveAssignment:
4667 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4668 case Sema::CXXDestructor:
4669 return S.ComputeDefaultedDtorExceptionSpec(MD);
4670 case Sema::CXXInvalid:
4671 break;
4672 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004673 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4674 "only special members have implicit exception specs");
4675 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004676}
4677
Reid Kleckner78af0702013-08-27 23:08:25 +00004678static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4679 CXXMethodDecl *MD) {
4680 FunctionProtoType::ExtProtoInfo EPI;
4681
4682 // Build an exception specification pointing back at this member.
4683 EPI.ExceptionSpecType = EST_Unevaluated;
4684 EPI.ExceptionSpecDecl = MD;
4685
4686 // Set the calling convention to the default for C++ instance methods.
4687 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4688 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4689 /*IsCXXMethod=*/true));
4690 return EPI;
4691}
4692
Richard Smithd3b5c9082012-07-27 04:22:15 +00004693void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4694 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4695 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4696 return;
4697
Richard Smith7f782272012-07-30 23:48:14 +00004698 // Evaluate the exception specification.
4699 ImplicitExceptionSpecification ExceptSpec =
4700 computeImplicitExceptionSpec(*this, Loc, MD);
4701
Richard Smith564417a2014-03-20 21:47:22 +00004702 FunctionProtoType::ExtProtoInfo EPI;
4703 ExceptSpec.getEPI(EPI);
4704
Richard Smith7f782272012-07-30 23:48:14 +00004705 // Update the type of the special member to use it.
Richard Smith564417a2014-03-20 21:47:22 +00004706 UpdateExceptionSpec(MD, EPI);
Richard Smith7f782272012-07-30 23:48:14 +00004707
4708 // A user-provided destructor can be defined outside the class. When that
4709 // happens, be sure to update the exception specification on both
4710 // declarations.
4711 const FunctionProtoType *CanonicalFPT =
4712 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4713 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith564417a2014-03-20 21:47:22 +00004714 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004715}
4716
Richard Smithb9e90b12012-05-15 04:39:51 +00004717void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4718 CXXRecordDecl *RD = MD->getParent();
4719 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004720
Richard Smithb9e90b12012-05-15 04:39:51 +00004721 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4722 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004723
4724 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004725 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004726 bool First = MD == MD->getCanonicalDecl();
4727
4728 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004729
4730 // C++11 [dcl.fct.def.default]p1:
4731 // A function that is explicitly defaulted shall
4732 // -- be a special member function (checked elsewhere),
4733 // -- have the same type (except for ref-qualifiers, and except that a
4734 // copy operation can take a non-const reference) as an implicit
4735 // declaration, and
4736 // -- not have default arguments.
4737 unsigned ExpectedParams = 1;
4738 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4739 ExpectedParams = 0;
4740 if (MD->getNumParams() != ExpectedParams) {
4741 // This also checks for default arguments: a copy or move constructor with a
4742 // default argument is classified as a default constructor, and assignment
4743 // operations and destructors can't have default arguments.
4744 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4745 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004746 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004747 } else if (MD->isVariadic()) {
4748 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4749 << CSM << MD->getSourceRange();
4750 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004751 }
4752
Richard Smithb9e90b12012-05-15 04:39:51 +00004753 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004754
Richard Smithb5800092012-06-10 05:43:50 +00004755 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004756 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004757 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004758 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004759 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004760
Richard Smithb9e90b12012-05-15 04:39:51 +00004761 QualType ReturnType = Context.VoidTy;
4762 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4763 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004764 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004765 QualType ExpectedReturnType =
4766 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4767 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4768 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4769 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4770 HadError = true;
4771 }
4772
4773 // A defaulted special member cannot have cv-qualifiers.
4774 if (Type->getTypeQuals()) {
4775 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004776 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004777 HadError = true;
4778 }
4779 }
4780
4781 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004782 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004783 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004784 if (ExpectedParams && ArgType->isReferenceType()) {
4785 // Argument must be reference to possibly-const T.
4786 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004787 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004788
4789 if (ReferentType.isVolatileQualified()) {
4790 Diag(MD->getLocation(),
4791 diag::err_defaulted_special_member_volatile_param) << CSM;
4792 HadError = true;
4793 }
4794
Richard Smithb5800092012-06-10 05:43:50 +00004795 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004796 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4797 Diag(MD->getLocation(),
4798 diag::err_defaulted_special_member_copy_const_param)
4799 << (CSM == CXXCopyAssignment);
4800 // FIXME: Explain why this special member can't be const.
4801 } else {
4802 Diag(MD->getLocation(),
4803 diag::err_defaulted_special_member_move_const_param)
4804 << (CSM == CXXMoveAssignment);
4805 }
4806 HadError = true;
4807 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004808 } else if (ExpectedParams) {
4809 // A copy assignment operator can take its argument by value, but a
4810 // defaulted one cannot.
4811 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004812 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004813 HadError = true;
4814 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004815
Richard Smithcc36f692011-12-22 02:22:31 +00004816 // C++11 [dcl.fct.def.default]p2:
4817 // An explicitly-defaulted function may be declared constexpr only if it
4818 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004819 // Do not apply this rule to members of class templates, since core issue 1358
4820 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004821 // functions which cannot be constexpr (for non-constructors in C++11 and for
4822 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004823 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4824 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004825 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4826 : isa<CXXConstructorDecl>(MD)) &&
4827 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004828 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4829 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004830 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004831 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004832 }
Richard Smithbd305122012-12-11 01:14:52 +00004833
Richard Smithcc36f692011-12-22 02:22:31 +00004834 // and may have an explicit exception-specification only if it is compatible
4835 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004836 if (Type->hasExceptionSpec()) {
4837 // Delay the check if this is the first declaration of the special member,
4838 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004839 if (First) {
4840 // If the exception specification needs to be instantiated, do so now,
4841 // before we clobber it with an EST_Unevaluated specification below.
4842 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4843 InstantiateExceptionSpec(MD->getLocStart(), MD);
4844 Type = MD->getType()->getAs<FunctionProtoType>();
4845 }
Richard Smithbd305122012-12-11 01:14:52 +00004846 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004847 } else
Richard Smithbd305122012-12-11 01:14:52 +00004848 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4849 }
Richard Smithcc36f692011-12-22 02:22:31 +00004850
4851 // If a function is explicitly defaulted on its first declaration,
4852 if (First) {
4853 // -- it is implicitly considered to be constexpr if the implicit
4854 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004855 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004856
Richard Smithb9e90b12012-05-15 04:39:51 +00004857 // -- it is implicitly considered to have the same exception-specification
4858 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004859 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4860 EPI.ExceptionSpecType = EST_Unevaluated;
4861 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004862 MD->setType(Context.getFunctionType(ReturnType,
4863 ArrayRef<QualType>(&ArgType,
4864 ExpectedParams),
4865 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004866 }
4867
Richard Smithb9e90b12012-05-15 04:39:51 +00004868 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004869 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004870 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004871 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004872 // C++11 [dcl.fct.def.default]p4:
4873 // [For a] user-provided explicitly-defaulted function [...] if such a
4874 // function is implicitly defined as deleted, the program is ill-formed.
4875 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004876 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004877 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004878 }
4879 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004880
Richard Smithb9e90b12012-05-15 04:39:51 +00004881 if (HadError)
4882 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004883}
4884
Richard Smithbd305122012-12-11 01:14:52 +00004885/// Check whether the exception specification provided for an
4886/// explicitly-defaulted special member matches the exception specification
4887/// that would have been generated for an implicit special member, per
4888/// C++11 [dcl.fct.def.default]p2.
4889void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4890 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4891 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004892 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4893 /*IsCXXMethod=*/true);
4894 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004895 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4896 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004897 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004898
4899 // Ensure that it matches.
4900 CheckEquivalentExceptionSpec(
4901 PDiag(diag::err_incorrect_defaulted_exception_spec)
4902 << getSpecialMember(MD), PDiag(),
4903 ImplicitType, SourceLocation(),
4904 SpecifiedType, MD->getLocation());
4905}
4906
Alp Tokerae3a9442013-10-18 05:54:19 +00004907void Sema::CheckDelayedMemberExceptionSpecs() {
4908 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4909 2> Checks;
4910 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004911
Alp Tokerae3a9442013-10-18 05:54:19 +00004912 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4913 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4914
4915 // Perform any deferred checking of exception specifications for virtual
4916 // destructors.
4917 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4918 const CXXDestructorDecl *Dtor = Checks[i].first;
4919 assert(!Dtor->getParent()->isDependentType() &&
4920 "Should not ever add destructors of templates into the list.");
4921 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4922 }
4923
4924 // Check that any explicitly-defaulted methods have exception specifications
4925 // compatible with their implicit exception specifications.
4926 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4927 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4928 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004929}
4930
Richard Smithd951a1d2012-02-18 02:02:13 +00004931namespace {
4932struct SpecialMemberDeletionInfo {
4933 Sema &S;
4934 CXXMethodDecl *MD;
4935 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004936 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004937
4938 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004939 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004940 SourceLocation Loc;
4941
4942 bool AllFieldsAreConst;
4943
4944 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004945 Sema::CXXSpecialMember CSM, bool Diagnose)
4946 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004947 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004948 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004949 AllFieldsAreConst(true) {
4950 switch (CSM) {
4951 case Sema::CXXDefaultConstructor:
4952 case Sema::CXXCopyConstructor:
4953 IsConstructor = true;
4954 break;
4955 case Sema::CXXMoveConstructor:
4956 IsConstructor = true;
4957 IsMove = true;
4958 break;
4959 case Sema::CXXCopyAssignment:
4960 IsAssignment = true;
4961 break;
4962 case Sema::CXXMoveAssignment:
4963 IsAssignment = true;
4964 IsMove = true;
4965 break;
4966 case Sema::CXXDestructor:
4967 break;
4968 case Sema::CXXInvalid:
4969 llvm_unreachable("invalid special member kind");
4970 }
4971
4972 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00004973 if (const ReferenceType *RT =
4974 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
4975 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00004976 }
4977 }
4978
4979 bool inUnion() const { return MD->getParent()->isUnion(); }
4980
4981 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00004982 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00004983 unsigned Quals, bool IsMutable) {
4984 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
4985 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00004986 }
4987
Richard Smith852265f2012-03-30 20:53:28 +00004988 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00004989
Richard Smith852265f2012-03-30 20:53:28 +00004990 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00004991 bool shouldDeleteForField(FieldDecl *FD);
4992 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00004993
Richard Smithaf136f82012-07-18 03:51:16 +00004994 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4995 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00004996 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4997 Sema::SpecialMemberOverloadResult *SMOR,
4998 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00004999
5000 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005001};
5002}
5003
John McCalld4274212012-04-09 20:53:23 +00005004/// Is the given special member inaccessible when used on the given
5005/// sub-object.
5006bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5007 CXXMethodDecl *target) {
5008 /// If we're operating on a base class, the object type is the
5009 /// type of this special member.
5010 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005011 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005012 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5013 objectTy = S.Context.getTypeDeclType(MD->getParent());
5014 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5015
5016 // If we're operating on a field, the object type is the type of the field.
5017 } else {
5018 objectTy = S.Context.getTypeDeclType(target->getParent());
5019 }
5020
5021 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5022}
5023
Richard Smith852265f2012-03-30 20:53:28 +00005024/// Check whether we should delete a special member due to the implicit
5025/// definition containing a call to a special member of a subobject.
5026bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5027 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5028 bool IsDtorCallInCtor) {
5029 CXXMethodDecl *Decl = SMOR->getMethod();
5030 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5031
5032 int DiagKind = -1;
5033
5034 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5035 DiagKind = !Decl ? 0 : 1;
5036 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5037 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005038 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005039 DiagKind = 3;
5040 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5041 !Decl->isTrivial()) {
5042 // A member of a union must have a trivial corresponding special member.
5043 // As a weird special case, a destructor call from a union's constructor
5044 // must be accessible and non-deleted, but need not be trivial. Such a
5045 // destructor is never actually called, but is semantically checked as
5046 // if it were.
5047 DiagKind = 4;
5048 }
5049
5050 if (DiagKind == -1)
5051 return false;
5052
5053 if (Diagnose) {
5054 if (Field) {
5055 S.Diag(Field->getLocation(),
5056 diag::note_deleted_special_member_class_subobject)
5057 << CSM << MD->getParent() << /*IsField*/true
5058 << Field << DiagKind << IsDtorCallInCtor;
5059 } else {
5060 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5061 S.Diag(Base->getLocStart(),
5062 diag::note_deleted_special_member_class_subobject)
5063 << CSM << MD->getParent() << /*IsField*/false
5064 << Base->getType() << DiagKind << IsDtorCallInCtor;
5065 }
5066
5067 if (DiagKind == 1)
5068 S.NoteDeletedFunction(Decl);
5069 // FIXME: Explain inaccessibility if DiagKind == 3.
5070 }
5071
5072 return true;
5073}
5074
Richard Smith921bd202012-02-26 09:11:52 +00005075/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005076/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005077bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005078 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005079 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005080 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005081
5082 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005083 // -- any direct or virtual base class, or non-static data member with no
5084 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005085 // either M has no default constructor or overload resolution as applied
5086 // to M's default constructor results in an ambiguity or in a function
5087 // that is deleted or inaccessible
5088 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5089 // -- a direct or virtual base class B that cannot be copied/moved because
5090 // overload resolution, as applied to B's corresponding special member,
5091 // results in an ambiguity or a function that is deleted or inaccessible
5092 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005093 // C++11 [class.dtor]p5:
5094 // -- any direct or virtual base class [...] has a type with a destructor
5095 // that is deleted or inaccessible
5096 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005097 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005098 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5099 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005100 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005101
Richard Smith852265f2012-03-30 20:53:28 +00005102 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5103 // -- any direct or virtual base class or non-static data member has a
5104 // type with a destructor that is deleted or inaccessible
5105 if (IsConstructor) {
5106 Sema::SpecialMemberOverloadResult *SMOR =
5107 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5108 false, false, false, false, false);
5109 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5110 return true;
5111 }
5112
Richard Smith921bd202012-02-26 09:11:52 +00005113 return false;
5114}
5115
5116/// Check whether we should delete a special member function due to the class
5117/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005118bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005119 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005120 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005121}
5122
5123/// Check whether we should delete a special member function due to the class
5124/// having a particular non-static data member.
5125bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5126 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5127 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5128
5129 if (CSM == Sema::CXXDefaultConstructor) {
5130 // For a default constructor, all references must be initialized in-class
5131 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005132 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5133 if (Diagnose)
5134 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5135 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005136 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005137 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005138 // C++11 [class.ctor]p5: any non-variant non-static data member of
5139 // const-qualified type (or array thereof) with no
5140 // brace-or-equal-initializer does not have a user-provided default
5141 // constructor.
5142 if (!inUnion() && FieldType.isConstQualified() &&
5143 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005144 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5145 if (Diagnose)
5146 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005147 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005148 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005149 }
5150
5151 if (inUnion() && !FieldType.isConstQualified())
5152 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005153 } else if (CSM == Sema::CXXCopyConstructor) {
5154 // For a copy constructor, data members must not be of rvalue reference
5155 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005156 if (FieldType->isRValueReferenceType()) {
5157 if (Diagnose)
5158 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5159 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005160 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005161 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005162 } else if (IsAssignment) {
5163 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005164 if (FieldType->isReferenceType()) {
5165 if (Diagnose)
5166 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5167 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005168 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005169 }
5170 if (!FieldRecord && FieldType.isConstQualified()) {
5171 // C++11 [class.copy]p23:
5172 // -- a non-static data member of const non-class type (or array thereof)
5173 if (Diagnose)
5174 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005175 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005176 return true;
5177 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005178 }
5179
5180 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005181 // Some additional restrictions exist on the variant members.
5182 if (!inUnion() && FieldRecord->isUnion() &&
5183 FieldRecord->isAnonymousStructOrUnion()) {
5184 bool AllVariantFieldsAreConst = true;
5185
Richard Smith5704fe82012-03-29 19:00:10 +00005186 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005187 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005188 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005189
5190 if (!UnionFieldType.isConstQualified())
5191 AllVariantFieldsAreConst = false;
5192
Richard Smith921bd202012-02-26 09:11:52 +00005193 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5194 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005195 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005196 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005197 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005198 }
5199
5200 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005201 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005202 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005203 if (Diagnose)
5204 S.Diag(FieldRecord->getLocation(),
5205 diag::note_deleted_default_ctor_all_const)
5206 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005207 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005208 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005209
Richard Smith5704fe82012-03-29 19:00:10 +00005210 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005211 // This is technically non-conformant, but sanity demands it.
5212 return false;
5213 }
5214
Richard Smithaf136f82012-07-18 03:51:16 +00005215 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5216 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005217 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005218 }
5219
5220 return false;
5221}
5222
5223/// C++11 [class.ctor] p5:
5224/// A defaulted default constructor for a class X is defined as deleted if
5225/// X is a union and all of its variant members are of const-qualified type.
5226bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005227 // This is a silly definition, because it gives an empty union a deleted
5228 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005229 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005230 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005231 if (Diagnose)
5232 S.Diag(MD->getParent()->getLocation(),
5233 diag::note_deleted_default_ctor_all_const)
5234 << MD->getParent() << /*not anonymous union*/0;
5235 return true;
5236 }
5237 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005238}
5239
5240/// Determine whether a defaulted special member function should be defined as
5241/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5242/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005243bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5244 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005245 if (MD->isInvalidDecl())
5246 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005247 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005248 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005249 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005250 return false;
5251
Richard Smithd951a1d2012-02-18 02:02:13 +00005252 // C++11 [expr.lambda.prim]p19:
5253 // The closure type associated with a lambda-expression has a
5254 // deleted (8.4.3) default constructor and a deleted copy
5255 // assignment operator.
5256 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005257 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5258 if (Diagnose)
5259 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005260 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005261 }
5262
Richard Smith6f1e2c62012-04-02 20:59:25 +00005263 // For an anonymous struct or union, the copy and assignment special members
5264 // will never be used, so skip the check. For an anonymous union declared at
5265 // namespace scope, the constructor and destructor are used.
5266 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5267 RD->isAnonymousStructOrUnion())
5268 return false;
5269
Richard Smith852265f2012-03-30 20:53:28 +00005270 // C++11 [class.copy]p7, p18:
5271 // If the class definition declares a move constructor or move assignment
5272 // operator, an implicitly declared copy constructor or copy assignment
5273 // operator is defined as deleted.
5274 if (MD->isImplicit() &&
5275 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5276 CXXMethodDecl *UserDeclaredMove = 0;
5277
5278 // In Microsoft mode, a user-declared move only causes the deletion of the
5279 // corresponding copy operation, not both copy operations.
5280 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005281 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005282 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005283
5284 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005285 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005286 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005287 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005288 break;
5289 }
5290 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005291 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005292 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005293 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005294 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005295
5296 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005297 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005298 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005299 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005300 break;
5301 }
5302 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005303 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005304 }
5305
5306 if (UserDeclaredMove) {
5307 Diag(UserDeclaredMove->getLocation(),
5308 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005309 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005310 << UserDeclaredMove->isMoveAssignmentOperator();
5311 return true;
5312 }
5313 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005314
Richard Smith6f1e2c62012-04-02 20:59:25 +00005315 // Do access control from the special member function
5316 ContextRAII MethodContext(*this, MD);
5317
Richard Smith921bd202012-02-26 09:11:52 +00005318 // C++11 [class.dtor]p5:
5319 // -- for a virtual destructor, lookup of the non-array deallocation function
5320 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005321 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005322 FunctionDecl *OperatorDelete = 0;
5323 DeclarationName Name =
5324 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5325 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005326 OperatorDelete, false)) {
5327 if (Diagnose)
5328 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005329 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005330 }
Richard Smith921bd202012-02-26 09:11:52 +00005331 }
5332
Richard Smith852265f2012-03-30 20:53:28 +00005333 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005334
Aaron Ballman574705e2014-03-13 15:41:46 +00005335 for (auto &BI : RD->bases())
5336 if (!BI.isVirtual() &&
5337 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005338 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005339
Richard Smithd1627032013-07-22 18:06:23 +00005340 // Per DR1611, do not consider virtual bases of constructors of abstract
5341 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005342 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005343 for (auto &BI : RD->vbases())
5344 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005345 return true;
5346 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005347
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005348 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005349 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005350 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005351 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005352
Richard Smithd951a1d2012-02-18 02:02:13 +00005353 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005354 return true;
5355
5356 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005357}
5358
Richard Smith92f241f2012-12-08 02:53:02 +00005359/// Perform lookup for a special member of the specified kind, and determine
5360/// whether it is trivial. If the triviality can be determined without the
5361/// lookup, skip it. This is intended for use when determining whether a
5362/// special member of a containing object is trivial, and thus does not ever
5363/// perform overload resolution for default constructors.
5364///
5365/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5366/// member that was most likely to be intended to be trivial, if any.
5367static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5368 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005369 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005370 if (Selected)
5371 *Selected = 0;
5372
5373 switch (CSM) {
5374 case Sema::CXXInvalid:
5375 llvm_unreachable("not a special member");
5376
5377 case Sema::CXXDefaultConstructor:
5378 // C++11 [class.ctor]p5:
5379 // A default constructor is trivial if:
5380 // - all the [direct subobjects] have trivial default constructors
5381 //
5382 // Note, no overload resolution is performed in this case.
5383 if (RD->hasTrivialDefaultConstructor())
5384 return true;
5385
5386 if (Selected) {
5387 // If there's a default constructor which could have been trivial, dig it
5388 // out. Otherwise, if there's any user-provided default constructor, point
5389 // to that as an example of why there's not a trivial one.
5390 CXXConstructorDecl *DefCtor = 0;
5391 if (RD->needsImplicitDefaultConstructor())
5392 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005393 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005394 if (!CI->isDefaultConstructor())
5395 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005396 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005397 if (!DefCtor->isUserProvided())
5398 break;
5399 }
5400
5401 *Selected = DefCtor;
5402 }
5403
5404 return false;
5405
5406 case Sema::CXXDestructor:
5407 // C++11 [class.dtor]p5:
5408 // A destructor is trivial if:
5409 // - all the direct [subobjects] have trivial destructors
5410 if (RD->hasTrivialDestructor())
5411 return true;
5412
5413 if (Selected) {
5414 if (RD->needsImplicitDestructor())
5415 S.DeclareImplicitDestructor(RD);
5416 *Selected = RD->getDestructor();
5417 }
5418
5419 return false;
5420
5421 case Sema::CXXCopyConstructor:
5422 // C++11 [class.copy]p12:
5423 // A copy constructor is trivial if:
5424 // - the constructor selected to copy each direct [subobject] is trivial
5425 if (RD->hasTrivialCopyConstructor()) {
5426 if (Quals == Qualifiers::Const)
5427 // We must either select the trivial copy constructor or reach an
5428 // ambiguity; no need to actually perform overload resolution.
5429 return true;
5430 } else if (!Selected) {
5431 return false;
5432 }
5433 // In C++98, we are not supposed to perform overload resolution here, but we
5434 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5435 // cases like B as having a non-trivial copy constructor:
5436 // struct A { template<typename T> A(T&); };
5437 // struct B { mutable A a; };
5438 goto NeedOverloadResolution;
5439
5440 case Sema::CXXCopyAssignment:
5441 // C++11 [class.copy]p25:
5442 // A copy assignment operator is trivial if:
5443 // - the assignment operator selected to copy each direct [subobject] is
5444 // trivial
5445 if (RD->hasTrivialCopyAssignment()) {
5446 if (Quals == Qualifiers::Const)
5447 return true;
5448 } else if (!Selected) {
5449 return false;
5450 }
5451 // In C++98, we are not supposed to perform overload resolution here, but we
5452 // treat that as a language defect.
5453 goto NeedOverloadResolution;
5454
5455 case Sema::CXXMoveConstructor:
5456 case Sema::CXXMoveAssignment:
5457 NeedOverloadResolution:
5458 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005459 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005460
5461 // The standard doesn't describe how to behave if the lookup is ambiguous.
5462 // We treat it as not making the member non-trivial, just like the standard
5463 // mandates for the default constructor. This should rarely matter, because
5464 // the member will also be deleted.
5465 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5466 return true;
5467
5468 if (!SMOR->getMethod()) {
5469 assert(SMOR->getKind() ==
5470 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5471 return false;
5472 }
5473
5474 // We deliberately don't check if we found a deleted special member. We're
5475 // not supposed to!
5476 if (Selected)
5477 *Selected = SMOR->getMethod();
5478 return SMOR->getMethod()->isTrivial();
5479 }
5480
5481 llvm_unreachable("unknown special method kind");
5482}
5483
Benjamin Kramer3e350262013-02-15 12:30:38 +00005484static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005485 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005486 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005487 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005488
5489 // Look for constructor templates.
5490 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5491 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5492 if (CXXConstructorDecl *CD =
5493 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5494 return CD;
5495 }
5496
5497 return 0;
5498}
5499
5500/// The kind of subobject we are checking for triviality. The values of this
5501/// enumeration are used in diagnostics.
5502enum TrivialSubobjectKind {
5503 /// The subobject is a base class.
5504 TSK_BaseClass,
5505 /// The subobject is a non-static data member.
5506 TSK_Field,
5507 /// The object is actually the complete object.
5508 TSK_CompleteObject
5509};
5510
5511/// Check whether the special member selected for a given type would be trivial.
5512static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005513 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005514 Sema::CXXSpecialMember CSM,
5515 TrivialSubobjectKind Kind,
5516 bool Diagnose) {
5517 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5518 if (!SubRD)
5519 return true;
5520
5521 CXXMethodDecl *Selected;
5522 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005523 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005524 return true;
5525
5526 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005527 if (ConstRHS)
5528 SubType.addConst();
5529
Richard Smith92f241f2012-12-08 02:53:02 +00005530 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5531 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5532 << Kind << SubType.getUnqualifiedType();
5533 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5534 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5535 } else if (!Selected)
5536 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5537 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5538 else if (Selected->isUserProvided()) {
5539 if (Kind == TSK_CompleteObject)
5540 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5541 << Kind << SubType.getUnqualifiedType() << CSM;
5542 else {
5543 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5544 << Kind << SubType.getUnqualifiedType() << CSM;
5545 S.Diag(Selected->getLocation(), diag::note_declared_at);
5546 }
5547 } else {
5548 if (Kind != TSK_CompleteObject)
5549 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5550 << Kind << SubType.getUnqualifiedType() << CSM;
5551
5552 // Explain why the defaulted or deleted special member isn't trivial.
5553 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5554 }
5555 }
5556
5557 return false;
5558}
5559
5560/// Check whether the members of a class type allow a special member to be
5561/// trivial.
5562static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5563 Sema::CXXSpecialMember CSM,
5564 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005565 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005566 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5567 continue;
5568
5569 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5570
5571 // Pretend anonymous struct or union members are members of this class.
5572 if (FI->isAnonymousStructOrUnion()) {
5573 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5574 CSM, ConstArg, Diagnose))
5575 return false;
5576 continue;
5577 }
5578
5579 // C++11 [class.ctor]p5:
5580 // A default constructor is trivial if [...]
5581 // -- no non-static data member of its class has a
5582 // brace-or-equal-initializer
5583 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5584 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005585 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005586 return false;
5587 }
5588
5589 // Objective C ARC 4.3.5:
5590 // [...] nontrivally ownership-qualified types are [...] not trivially
5591 // default constructible, copy constructible, move constructible, copy
5592 // assignable, move assignable, or destructible [...]
5593 if (S.getLangOpts().ObjCAutoRefCount &&
5594 FieldType.hasNonTrivialObjCLifetime()) {
5595 if (Diagnose)
5596 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5597 << RD << FieldType.getObjCLifetime();
5598 return false;
5599 }
5600
Richard Smith41c35d62013-11-27 03:39:20 +00005601 bool ConstRHS = ConstArg && !FI->isMutable();
5602 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5603 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005604 return false;
5605 }
5606
5607 return true;
5608}
5609
5610/// Diagnose why the specified class does not have a trivial special member of
5611/// the given kind.
5612void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5613 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005614
Richard Smith41c35d62013-11-27 03:39:20 +00005615 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5616 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005617 TSK_CompleteObject, /*Diagnose*/true);
5618}
5619
5620/// Determine whether a defaulted or deleted special member function is trivial,
5621/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5622/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5623bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5624 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005625 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5626
5627 CXXRecordDecl *RD = MD->getParent();
5628
5629 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005630
Richard Smith2002bfe2013-11-04 02:02:27 +00005631 // C++11 [class.copy]p12, p25: [DR1593]
5632 // A [special member] is trivial if [...] its parameter-type-list is
5633 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005634 switch (CSM) {
5635 case CXXDefaultConstructor:
5636 case CXXDestructor:
5637 // Trivial default constructors and destructors cannot have parameters.
5638 break;
5639
5640 case CXXCopyConstructor:
5641 case CXXCopyAssignment: {
5642 // Trivial copy operations always have const, non-volatile parameter types.
5643 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005644 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005645 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5646 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5647 if (Diagnose)
5648 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5649 << Param0->getSourceRange() << Param0->getType()
5650 << Context.getLValueReferenceType(
5651 Context.getRecordType(RD).withConst());
5652 return false;
5653 }
5654 break;
5655 }
5656
5657 case CXXMoveConstructor:
5658 case CXXMoveAssignment: {
5659 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005660 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005661 const RValueReferenceType *RT =
5662 Param0->getType()->getAs<RValueReferenceType>();
5663 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5664 if (Diagnose)
5665 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5666 << Param0->getSourceRange() << Param0->getType()
5667 << Context.getRValueReferenceType(Context.getRecordType(RD));
5668 return false;
5669 }
5670 break;
5671 }
5672
5673 case CXXInvalid:
5674 llvm_unreachable("not a special member");
5675 }
5676
Richard Smith92f241f2012-12-08 02:53:02 +00005677 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5678 if (Diagnose)
5679 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5680 diag::note_nontrivial_default_arg)
5681 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5682 return false;
5683 }
5684 if (MD->isVariadic()) {
5685 if (Diagnose)
5686 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5687 return false;
5688 }
5689
5690 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5691 // A copy/move [constructor or assignment operator] is trivial if
5692 // -- the [member] selected to copy/move each direct base class subobject
5693 // is trivial
5694 //
5695 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5696 // A [default constructor or destructor] is trivial if
5697 // -- all the direct base classes have trivial [default constructors or
5698 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005699 for (const auto &BI : RD->bases())
5700 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005701 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005702 return false;
5703
5704 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5705 // A copy/move [constructor or assignment operator] for a class X is
5706 // trivial if
5707 // -- for each non-static data member of X that is of class type (or array
5708 // thereof), the constructor selected to copy/move that member is
5709 // trivial
5710 //
5711 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5712 // A [default constructor or destructor] is trivial if
5713 // -- for all of the non-static data members of its class that are of class
5714 // type (or array thereof), each such class has a trivial [default
5715 // constructor or destructor]
5716 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5717 return false;
5718
5719 // C++11 [class.dtor]p5:
5720 // A destructor is trivial if [...]
5721 // -- the destructor is not virtual
5722 if (CSM == CXXDestructor && MD->isVirtual()) {
5723 if (Diagnose)
5724 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5725 return false;
5726 }
5727
5728 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5729 // A [special member] for class X is trivial if [...]
5730 // -- class X has no virtual functions and no virtual base classes
5731 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5732 if (!Diagnose)
5733 return false;
5734
5735 if (RD->getNumVBases()) {
5736 // Check for virtual bases. We already know that the corresponding
5737 // member in all bases is trivial, so vbases must all be direct.
5738 CXXBaseSpecifier &BS = *RD->vbases_begin();
5739 assert(BS.isVirtual());
5740 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5741 return false;
5742 }
5743
5744 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005745 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005746 if (MI->isVirtual()) {
5747 SourceLocation MLoc = MI->getLocStart();
5748 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5749 return false;
5750 }
5751 }
5752
5753 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5754 }
5755
5756 // Looks like it's trivial!
5757 return true;
5758}
5759
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005760/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005761namespace {
5762 struct FindHiddenVirtualMethodData {
5763 Sema *S;
5764 CXXMethodDecl *Method;
5765 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005766 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005767 };
5768}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005769
David Blaikie282c92a2012-10-19 00:53:08 +00005770/// \brief Check whether any most overriden method from MD in Methods
5771static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5772 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5773 if (MD->size_overridden_methods() == 0)
5774 return Methods.count(MD->getCanonicalDecl());
5775 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5776 E = MD->end_overridden_methods();
5777 I != E; ++I)
5778 if (CheckMostOverridenMethods(*I, Methods))
5779 return true;
5780 return false;
5781}
5782
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005783/// \brief Member lookup function that determines whether a given C++
5784/// method overloads virtual methods in a base class without overriding any,
5785/// to be used with CXXRecordDecl::lookupInBases().
5786static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5787 CXXBasePath &Path,
5788 void *UserData) {
5789 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5790
5791 FindHiddenVirtualMethodData &Data
5792 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5793
5794 DeclarationName Name = Data.Method->getDeclName();
5795 assert(Name.getNameKind() == DeclarationName::Identifier);
5796
5797 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005798 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005799 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005800 !Path.Decls.empty();
5801 Path.Decls = Path.Decls.slice(1)) {
5802 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005803 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005804 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005805 foundSameNameMethod = true;
5806 // Interested only in hidden virtual methods.
5807 if (!MD->isVirtual())
5808 continue;
5809 // If the method we are checking overrides a method from its base
5810 // don't warn about the other overloaded methods.
5811 if (!Data.S->IsOverload(Data.Method, MD, false))
5812 return true;
5813 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005814 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005815 overloadedMethods.push_back(MD);
5816 }
5817 }
5818
5819 if (foundSameNameMethod)
5820 Data.OverloadedMethods.append(overloadedMethods.begin(),
5821 overloadedMethods.end());
5822 return foundSameNameMethod;
5823}
5824
David Blaikie282c92a2012-10-19 00:53:08 +00005825/// \brief Add the most overriden methods from MD to Methods
5826static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5827 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5828 if (MD->size_overridden_methods() == 0)
5829 Methods.insert(MD->getCanonicalDecl());
5830 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5831 E = MD->end_overridden_methods();
5832 I != E; ++I)
5833 AddMostOverridenMethods(*I, Methods);
5834}
5835
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005836/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005837/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005838void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5839 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005840 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005841 return;
5842
5843 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5844 /*bool RecordPaths=*/false,
5845 /*bool DetectVirtual=*/false);
5846 FindHiddenVirtualMethodData Data;
5847 Data.Method = MD;
5848 Data.S = this;
5849
5850 // Keep the base methods that were overriden or introduced in the subclass
5851 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005852 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005853 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5854 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5855 NamedDecl *ND = *I;
5856 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005857 ND = shad->getTargetDecl();
5858 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5859 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005860 }
5861
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005862 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5863 OverloadedMethods = Data.OverloadedMethods;
5864}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005865
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005866void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5867 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5868 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5869 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5870 PartialDiagnostic PD = PDiag(
5871 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5872 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5873 Diag(overloadedMD->getLocation(), PD);
5874 }
5875}
5876
5877/// \brief Diagnose methods which overload virtual methods in a base class
5878/// without overriding any.
5879void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5880 if (MD->isInvalidDecl())
5881 return;
5882
5883 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5884 MD->getLocation()) == DiagnosticsEngine::Ignored)
5885 return;
5886
5887 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5888 FindHiddenVirtualMethods(MD, OverloadedMethods);
5889 if (!OverloadedMethods.empty()) {
5890 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5891 << MD << (OverloadedMethods.size() > 1);
5892
5893 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005894 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005895}
5896
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005897void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005898 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005899 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005900 SourceLocation RBrac,
5901 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005902 if (!TagDecl)
5903 return;
Mike Stump11289f42009-09-09 15:08:12 +00005904
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005905 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005906
Rafael Espindola06e1b132012-07-12 04:32:30 +00005907 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5908 if (l->getKind() != AttributeList::AT_Visibility)
5909 continue;
5910 l->setInvalid();
5911 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5912 l->getName();
5913 }
5914
David Blaikie751c5582011-09-22 02:58:26 +00005915 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005916 // strict aliasing violation!
5917 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005918 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005919
Douglas Gregor0be31a22010-07-02 17:43:08 +00005920 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005921 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005922}
5923
Douglas Gregor05379422008-11-03 17:51:48 +00005924/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5925/// special functions, such as the default constructor, copy
5926/// constructor, or destructor, to the given C++ class (C++
5927/// [special]p1). This routine can only be executed just before the
5928/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005929void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005930 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005931 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005932
Richard Smith6b02d462012-12-08 08:32:28 +00005933 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005934 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005935
Richard Smith6b02d462012-12-08 08:32:28 +00005936 // If the properties or semantics of the copy constructor couldn't be
5937 // determined while the class was being declared, force a declaration
5938 // of it now.
5939 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5940 DeclareImplicitCopyConstructor(ClassDecl);
5941 }
5942
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005943 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005944 ++ASTContext::NumImplicitMoveConstructors;
5945
Richard Smith6b02d462012-12-08 08:32:28 +00005946 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5947 DeclareImplicitMoveConstructor(ClassDecl);
5948 }
5949
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005950 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5951 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005952
5953 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005954 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00005955 // it shows up in the right place in the vtable and that we diagnose
5956 // problems with the implicit exception specification.
5957 if (ClassDecl->isDynamicClass() ||
5958 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005959 DeclareImplicitCopyAssignment(ClassDecl);
5960 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005961
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005962 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005963 ++ASTContext::NumImplicitMoveAssignmentOperators;
5964
5965 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00005966 if (ClassDecl->isDynamicClass() ||
5967 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00005968 DeclareImplicitMoveAssignment(ClassDecl);
5969 }
5970
Douglas Gregor7454c562010-07-02 20:37:36 +00005971 if (!ClassDecl->hasUserDeclaredDestructor()) {
5972 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00005973
5974 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00005975 // have to declare the destructor immediately. This ensures that, e.g., it
5976 // shows up in the right place in the vtable and that we diagnose problems
5977 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00005978 if (ClassDecl->isDynamicClass() ||
5979 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00005980 DeclareImplicitDestructor(ClassDecl);
5981 }
Douglas Gregor05379422008-11-03 17:51:48 +00005982}
5983
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00005984unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00005985 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00005986 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00005987
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00005988 // The order of template parameters is not important here. All names
5989 // get added to the same scope.
5990 SmallVector<TemplateParameterList *, 4> ParameterLists;
5991
5992 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5993 D = TD->getTemplatedDecl();
5994
5995 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5996 ParameterLists.push_back(PSD->getTemplateParameters());
5997
5998 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
5999 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6000 ParameterLists.push_back(DD->getTemplateParameterList(i));
6001
6002 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6003 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6004 ParameterLists.push_back(FTD->getTemplateParameters());
6005 }
6006 }
6007
6008 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6009 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6010 ParameterLists.push_back(TD->getTemplateParameterList(i));
6011
6012 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6013 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6014 ParameterLists.push_back(CTD->getTemplateParameters());
6015 }
6016 }
6017
6018 unsigned Count = 0;
6019 for (TemplateParameterList *Params : ParameterLists) {
6020 if (Params->size() > 0)
6021 // Ignore explicit specializations; they don't contribute to the template
6022 // depth.
6023 ++Count;
6024 for (NamedDecl *Param : *Params) {
6025 if (Param->getDeclName()) {
6026 S->AddDecl(Param);
6027 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006028 }
6029 }
6030 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006031
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006032 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006033}
6034
John McCall48871652010-08-21 09:40:31 +00006035void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006036 if (!RecordD) return;
6037 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006038 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006039 PushDeclContext(S, Record);
6040}
6041
John McCall48871652010-08-21 09:40:31 +00006042void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006043 if (!RecordD) return;
6044 PopDeclContext();
6045}
6046
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006047/// This is used to implement the constant expression evaluation part of the
6048/// attribute enable_if extension. There is nothing in standard C++ which would
6049/// require reentering parameters.
6050void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6051 if (!Param)
6052 return;
6053
6054 S->AddDecl(Param);
6055 if (Param->getDeclName())
6056 IdResolver.AddDecl(Param);
6057}
6058
Douglas Gregor4d87df52008-12-16 21:30:33 +00006059/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6060/// parsing a top-level (non-nested) C++ class, and we are now
6061/// parsing those parts of the given Method declaration that could
6062/// not be parsed earlier (C++ [class.mem]p2), such as default
6063/// arguments. This action should enter the scope of the given
6064/// Method declaration as if we had just parsed the qualified method
6065/// name. However, it should not bring the parameters into scope;
6066/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006067void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006068}
6069
6070/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6071/// C++ method declaration. We're (re-)introducing the given
6072/// function parameter into scope for use in parsing later parts of
6073/// the method declaration. For example, we could see an
6074/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006075void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006076 if (!ParamD)
6077 return;
Mike Stump11289f42009-09-09 15:08:12 +00006078
John McCall48871652010-08-21 09:40:31 +00006079 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006080
6081 // If this parameter has an unparsed default argument, clear it out
6082 // to make way for the parsed default argument.
6083 if (Param->hasUnparsedDefaultArg())
6084 Param->setDefaultArg(0);
6085
John McCall48871652010-08-21 09:40:31 +00006086 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006087 if (Param->getDeclName())
6088 IdResolver.AddDecl(Param);
6089}
6090
6091/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6092/// processing the delayed method declaration for Method. The method
6093/// declaration is now considered finished. There may be a separate
6094/// ActOnStartOfFunctionDef action later (not necessarily
6095/// immediately!) for this method, if it was also defined inside the
6096/// class body.
John McCall48871652010-08-21 09:40:31 +00006097void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006098 if (!MethodD)
6099 return;
Mike Stump11289f42009-09-09 15:08:12 +00006100
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006101 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006102
John McCall48871652010-08-21 09:40:31 +00006103 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006104
6105 // Now that we have our default arguments, check the constructor
6106 // again. It could produce additional diagnostics or affect whether
6107 // the class has implicitly-declared destructors, among other
6108 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006109 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6110 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006111
6112 // Check the default arguments, which we may have added.
6113 if (!Method->isInvalidDecl())
6114 CheckCXXDefaultArguments(Method);
6115}
6116
Douglas Gregor831c93f2008-11-05 20:51:48 +00006117/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006118/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006119/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006120/// emit diagnostics and set the invalid bit to true. In any case, the type
6121/// will be updated to reflect a well-formed type for the constructor and
6122/// returned.
6123QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006124 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006125 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006126
6127 // C++ [class.ctor]p3:
6128 // A constructor shall not be virtual (10.3) or static (9.4). A
6129 // constructor can be invoked for a const, volatile or const
6130 // volatile object. A constructor shall not be declared const,
6131 // volatile, or const volatile (9.3.2).
6132 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006133 if (!D.isInvalidType())
6134 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6135 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6136 << SourceRange(D.getIdentifierLoc());
6137 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006138 }
John McCall8e7d6562010-08-26 03:08:43 +00006139 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006140 if (!D.isInvalidType())
6141 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6142 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6143 << SourceRange(D.getIdentifierLoc());
6144 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006145 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006146 }
Mike Stump11289f42009-09-09 15:08:12 +00006147
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006148 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006149 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006150 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006151 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6152 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006153 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006154 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6155 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006156 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006157 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6158 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006159 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006160 }
Mike Stump11289f42009-09-09 15:08:12 +00006161
Douglas Gregordb9d6642011-01-26 05:01:58 +00006162 // C++0x [class.ctor]p4:
6163 // A constructor shall not be declared with a ref-qualifier.
6164 if (FTI.hasRefQualifier()) {
6165 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6166 << FTI.RefQualifierIsLValueRef
6167 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6168 D.setInvalidType();
6169 }
6170
Douglas Gregor831c93f2008-11-05 20:51:48 +00006171 // Rebuild the function type "R" without any type qualifiers (in
6172 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006173 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006174 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006175 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006176 return R;
6177
6178 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6179 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006180 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006181
6182 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006183}
6184
Douglas Gregor4d87df52008-12-16 21:30:33 +00006185/// CheckConstructor - Checks a fully-formed constructor for
6186/// well-formedness, issuing any diagnostics required. Returns true if
6187/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006188void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006189 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006190 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6191 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006192 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006193
6194 // C++ [class.copy]p3:
6195 // A declaration of a constructor for a class X is ill-formed if
6196 // its first parameter is of type (optionally cv-qualified) X and
6197 // either there are no other parameters or else all other
6198 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006199 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006200 ((Constructor->getNumParams() == 1) ||
6201 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006202 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6203 Constructor->getTemplateSpecializationKind()
6204 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006205 QualType ParamType = Constructor->getParamDecl(0)->getType();
6206 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6207 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006208 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006209 const char *ConstRef
6210 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6211 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006212 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006213 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006214
6215 // FIXME: Rather that making the constructor invalid, we should endeavor
6216 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006217 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006218 }
6219 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006220}
6221
John McCalldeb646e2010-08-04 01:04:25 +00006222/// CheckDestructor - Checks a fully-formed destructor definition for
6223/// well-formedness, issuing any diagnostics required. Returns true
6224/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006225bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006226 CXXRecordDecl *RD = Destructor->getParent();
6227
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006228 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006229 SourceLocation Loc;
6230
6231 if (!Destructor->isImplicit())
6232 Loc = Destructor->getLocation();
6233 else
6234 Loc = RD->getLocation();
6235
6236 // If we have a virtual destructor, look up the deallocation function
6237 FunctionDecl *OperatorDelete = 0;
6238 DeclarationName Name =
6239 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006240 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006241 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006242 // If there's no class-specific operator delete, look up the global
6243 // non-array delete.
6244 if (!OperatorDelete)
6245 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006246
Eli Friedmanfa0df832012-02-02 03:46:19 +00006247 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006248
6249 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006250 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006251
6252 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006253}
6254
Douglas Gregor831c93f2008-11-05 20:51:48 +00006255/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6256/// the well-formednes of the destructor declarator @p D with type @p
6257/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006258/// emit diagnostics and set the declarator to invalid. Even if this happens,
6259/// will be updated to reflect a well-formed type for the destructor and
6260/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006261QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006262 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006263 // C++ [class.dtor]p1:
6264 // [...] A typedef-name that names a class is a class-name
6265 // (7.1.3); however, a typedef-name that names a class shall not
6266 // be used as the identifier in the declarator for a destructor
6267 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006268 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006269 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006270 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006271 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006272 else if (const TemplateSpecializationType *TST =
6273 DeclaratorType->getAs<TemplateSpecializationType>())
6274 if (TST->isTypeAlias())
6275 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6276 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006277
6278 // C++ [class.dtor]p2:
6279 // A destructor is used to destroy objects of its class type. A
6280 // destructor takes no parameters, and no return type can be
6281 // specified for it (not even void). The address of a destructor
6282 // shall not be taken. A destructor shall not be static. A
6283 // destructor can be invoked for a const, volatile or const
6284 // volatile object. A destructor shall not be declared const,
6285 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006286 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006287 if (!D.isInvalidType())
6288 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6289 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006290 << SourceRange(D.getIdentifierLoc())
6291 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6292
John McCall8e7d6562010-08-26 03:08:43 +00006293 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006294 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006295 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006296 // Destructors don't have return types, but the parser will
6297 // happily parse something like:
6298 //
6299 // class X {
6300 // float ~X();
6301 // };
6302 //
6303 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006304 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6305 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6306 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006307 }
Mike Stump11289f42009-09-09 15:08:12 +00006308
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006309 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006310 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006311 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006312 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6313 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006314 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006315 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6316 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006317 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006318 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6319 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006320 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006321 }
6322
Douglas Gregordb9d6642011-01-26 05:01:58 +00006323 // C++0x [class.dtor]p2:
6324 // A destructor shall not be declared with a ref-qualifier.
6325 if (FTI.hasRefQualifier()) {
6326 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6327 << FTI.RefQualifierIsLValueRef
6328 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6329 D.setInvalidType();
6330 }
6331
Douglas Gregor831c93f2008-11-05 20:51:48 +00006332 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006333 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006334 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6335
6336 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006337 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006338 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006339 }
6340
Mike Stump11289f42009-09-09 15:08:12 +00006341 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006342 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006343 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006344 D.setInvalidType();
6345 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006346
6347 // Rebuild the function type "R" without any type qualifiers or
6348 // parameters (in case any of the errors above fired) and with
6349 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006350 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006351 if (!D.isInvalidType())
6352 return R;
6353
Douglas Gregor95755162010-07-01 05:10:53 +00006354 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006355 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6356 EPI.Variadic = false;
6357 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006358 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006359 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006360}
6361
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006362/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6363/// well-formednes of the conversion function declarator @p D with
6364/// type @p R. If there are any errors in the declarator, this routine
6365/// will emit diagnostics and return true. Otherwise, it will return
6366/// false. Either way, the type @p R will be updated to reflect a
6367/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006368void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006369 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006370 // C++ [class.conv.fct]p1:
6371 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006372 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006373 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006374 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006375 if (!D.isInvalidType())
6376 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006377 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6378 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006379 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006380 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006381 }
John McCall212fa2e2010-04-13 00:04:31 +00006382
6383 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6384
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006385 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006386 // Conversion functions don't have return types, but the parser will
6387 // happily parse something like:
6388 //
6389 // class X {
6390 // float operator bool();
6391 // };
6392 //
6393 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006394 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6395 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6396 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006397 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006398 }
6399
John McCall212fa2e2010-04-13 00:04:31 +00006400 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6401
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006402 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006403 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006404 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6405
6406 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006407 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006408 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006409 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006410 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006411 D.setInvalidType();
6412 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006413
John McCall212fa2e2010-04-13 00:04:31 +00006414 // Diagnose "&operator bool()" and other such nonsense. This
6415 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006416 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006417 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006418 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006419 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006420 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006421 }
6422
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006423 // C++ [class.conv.fct]p4:
6424 // The conversion-type-id shall not represent a function type nor
6425 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006426 if (ConvType->isArrayType()) {
6427 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6428 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006429 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006430 } else if (ConvType->isFunctionType()) {
6431 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6432 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006433 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006434 }
6435
6436 // Rebuild the function type "R" without any parameters (in case any
6437 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006438 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006439 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006440 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006441
Douglas Gregor5fb53972009-01-14 15:45:31 +00006442 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006443 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006444 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006445 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006446 diag::warn_cxx98_compat_explicit_conversion_functions :
6447 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006448 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006449}
6450
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006451/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6452/// the declaration of the given C++ conversion function. This routine
6453/// is responsible for recording the conversion function in the C++
6454/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006455Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006456 assert(Conversion && "Expected to receive a conversion function declaration");
6457
Douglas Gregor4287b372008-12-12 08:25:50 +00006458 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006459
6460 // Make sure we aren't redeclaring the conversion function.
6461 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006462
6463 // C++ [class.conv.fct]p1:
6464 // [...] A conversion function is never used to convert a
6465 // (possibly cv-qualified) object to the (possibly cv-qualified)
6466 // same object type (or a reference to it), to a (possibly
6467 // cv-qualified) base class of that type (or a reference to it),
6468 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006469 // FIXME: Suppress this warning if the conversion function ends up being a
6470 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006471 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006472 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006473 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006474 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006475 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6476 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006477 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006478 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006479 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6480 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006481 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006482 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006483 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006484 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006485 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006486 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006487 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006488 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006489 }
6490
Douglas Gregor457104e2010-09-29 04:25:11 +00006491 if (FunctionTemplateDecl *ConversionTemplate
6492 = Conversion->getDescribedFunctionTemplate())
6493 return ConversionTemplate;
6494
John McCall48871652010-08-21 09:40:31 +00006495 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006496}
6497
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006498//===----------------------------------------------------------------------===//
6499// Namespace Handling
6500//===----------------------------------------------------------------------===//
6501
Richard Smith45bb8852012-10-04 22:13:39 +00006502/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6503/// reopened.
6504static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6505 SourceLocation Loc,
6506 IdentifierInfo *II, bool *IsInline,
6507 NamespaceDecl *PrevNS) {
6508 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006509
Richard Smithf501cc32012-10-05 01:46:25 +00006510 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6511 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6512 // inline namespaces, with the intention of bringing names into namespace std.
6513 //
6514 // We support this just well enough to get that case working; this is not
6515 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006516 if (*IsInline && II && II->getName().startswith("__atomic") &&
6517 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006518 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006519 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6520 NS = NS->getPreviousDecl())
6521 NS->setInline(*IsInline);
6522 // Patch up the lookup table for the containing namespace. This isn't really
6523 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006524 for (auto *I : PrevNS->decls())
6525 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006526 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6527 return;
6528 }
6529
6530 if (PrevNS->isInline())
6531 // The user probably just forgot the 'inline', so suggest that it
6532 // be added back.
6533 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6534 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6535 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006536 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006537
6538 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6539 *IsInline = PrevNS->isInline();
6540}
John McCallb1be5232010-08-26 09:15:37 +00006541
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006542/// ActOnStartNamespaceDef - This is called at the start of a namespace
6543/// definition.
John McCall48871652010-08-21 09:40:31 +00006544Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006545 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006546 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006547 SourceLocation IdentLoc,
6548 IdentifierInfo *II,
6549 SourceLocation LBrace,
6550 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006551 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6552 // For anonymous namespace, take the location of the left brace.
6553 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006554 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006555 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006556 bool IsStd = false;
6557 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006558 Scope *DeclRegionScope = NamespcScope->getParent();
6559
Douglas Gregore57e7522012-01-07 09:11:48 +00006560 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006561 if (II) {
6562 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006563 // The identifier in an original-namespace-definition shall not
6564 // have been previously defined in the declarative region in
6565 // which the original-namespace-definition appears. The
6566 // identifier in an original-namespace-definition is the name of
6567 // the namespace. Subsequently in that declarative region, it is
6568 // treated as an original-namespace-name.
6569 //
6570 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006571 // look through using directives, just look for any ordinary names.
6572
6573 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006574 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6575 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006576 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006577 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6578 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6579 ++I) {
6580 if ((*I)->getIdentifierNamespace() & IDNS) {
6581 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006582 break;
6583 }
6584 }
6585
Douglas Gregore57e7522012-01-07 09:11:48 +00006586 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6587
6588 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006589 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006590 if (IsInline != PrevNS->isInline())
6591 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6592 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006593 } else if (PrevDecl) {
6594 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006595 Diag(Loc, diag::err_redefinition_different_kind)
6596 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006597 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006598 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006599 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006600 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006601 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006602 // This is the first "real" definition of the namespace "std", so update
6603 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006604 PrevNS = getStdNamespace();
6605 IsStd = true;
6606 AddToKnown = !IsInline;
6607 } else {
6608 // We've seen this namespace for the first time.
6609 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006610 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006611 } else {
John McCall4fa53422009-10-01 00:25:31 +00006612 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006613
6614 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006615 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006616 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006617 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006618 } else {
6619 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006620 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006621 }
6622
Richard Smith45bb8852012-10-04 22:13:39 +00006623 if (PrevNS && IsInline != PrevNS->isInline())
6624 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6625 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006626 }
6627
6628 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6629 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006630 if (IsInvalid)
6631 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006632
6633 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006634
Douglas Gregore57e7522012-01-07 09:11:48 +00006635 // FIXME: Should we be merging attributes?
6636 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006637 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006638
6639 if (IsStd)
6640 StdNamespace = Namespc;
6641 if (AddToKnown)
6642 KnownNamespaces[Namespc] = false;
6643
6644 if (II) {
6645 PushOnScopeChains(Namespc, DeclRegionScope);
6646 } else {
6647 // Link the anonymous namespace into its parent.
6648 DeclContext *Parent = CurContext->getRedeclContext();
6649 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6650 TU->setAnonymousNamespace(Namespc);
6651 } else {
6652 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006653 }
John McCall4fa53422009-10-01 00:25:31 +00006654
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006655 CurContext->addDecl(Namespc);
6656
John McCall4fa53422009-10-01 00:25:31 +00006657 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6658 // behaves as if it were replaced by
6659 // namespace unique { /* empty body */ }
6660 // using namespace unique;
6661 // namespace unique { namespace-body }
6662 // where all occurrences of 'unique' in a translation unit are
6663 // replaced by the same identifier and this identifier differs
6664 // from all other identifiers in the entire program.
6665
6666 // We just create the namespace with an empty name and then add an
6667 // implicit using declaration, just like the standard suggests.
6668 //
6669 // CodeGen enforces the "universally unique" aspect by giving all
6670 // declarations semantically contained within an anonymous
6671 // namespace internal linkage.
6672
Douglas Gregore57e7522012-01-07 09:11:48 +00006673 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006674 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006675 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006676 /* 'using' */ LBrace,
6677 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006678 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006679 /* identifier */ SourceLocation(),
6680 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006681 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006682 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006683 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006684 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006685 }
6686
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006687 ActOnDocumentableDecl(Namespc);
6688
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006689 // Although we could have an invalid decl (i.e. the namespace name is a
6690 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006691 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6692 // for the namespace has the declarations that showed up in that particular
6693 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006694 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006695 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006696}
6697
Sebastian Redla6602e92009-11-23 15:34:23 +00006698/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6699/// is a namespace alias, returns the namespace it points to.
6700static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6701 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6702 return AD->getNamespace();
6703 return dyn_cast_or_null<NamespaceDecl>(D);
6704}
6705
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006706/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6707/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006708void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006709 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6710 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006711 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006712 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006713 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006714 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006715}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006716
John McCall28a0cf72010-08-25 07:42:41 +00006717CXXRecordDecl *Sema::getStdBadAlloc() const {
6718 return cast_or_null<CXXRecordDecl>(
6719 StdBadAlloc.get(Context.getExternalSource()));
6720}
6721
6722NamespaceDecl *Sema::getStdNamespace() const {
6723 return cast_or_null<NamespaceDecl>(
6724 StdNamespace.get(Context.getExternalSource()));
6725}
6726
Douglas Gregorcdf87022010-06-29 17:53:46 +00006727/// \brief Retrieve the special "std" namespace, which may require us to
6728/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006729NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006730 if (!StdNamespace) {
6731 // The "std" namespace has not yet been defined, so build one implicitly.
6732 StdNamespace = NamespaceDecl::Create(Context,
6733 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006734 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006735 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006736 &PP.getIdentifierTable().get("std"),
6737 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006738 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006739 }
6740
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006741 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006742}
6743
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006744bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006745 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006746 "Looking for std::initializer_list outside of C++.");
6747
6748 // We're looking for implicit instantiations of
6749 // template <typename E> class std::initializer_list.
6750
6751 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6752 return false;
6753
Sebastian Redl43144e72012-01-17 22:49:58 +00006754 ClassTemplateDecl *Template = 0;
6755 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006756
Sebastian Redl43144e72012-01-17 22:49:58 +00006757 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006758
Sebastian Redl43144e72012-01-17 22:49:58 +00006759 ClassTemplateSpecializationDecl *Specialization =
6760 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6761 if (!Specialization)
6762 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006763
Sebastian Redl43144e72012-01-17 22:49:58 +00006764 Template = Specialization->getSpecializedTemplate();
6765 Arguments = Specialization->getTemplateArgs().data();
6766 } else if (const TemplateSpecializationType *TST =
6767 Ty->getAs<TemplateSpecializationType>()) {
6768 Template = dyn_cast_or_null<ClassTemplateDecl>(
6769 TST->getTemplateName().getAsTemplateDecl());
6770 Arguments = TST->getArgs();
6771 }
6772 if (!Template)
6773 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006774
6775 if (!StdInitializerList) {
6776 // Haven't recognized std::initializer_list yet, maybe this is it.
6777 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6778 if (TemplateClass->getIdentifier() !=
6779 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006780 !getStdNamespace()->InEnclosingNamespaceSetOf(
6781 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006782 return false;
6783 // This is a template called std::initializer_list, but is it the right
6784 // template?
6785 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006786 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006787 return false;
6788 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6789 return false;
6790
6791 // It's the right template.
6792 StdInitializerList = Template;
6793 }
6794
6795 if (Template != StdInitializerList)
6796 return false;
6797
6798 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006799 if (Element)
6800 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006801 return true;
6802}
6803
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006804static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6805 NamespaceDecl *Std = S.getStdNamespace();
6806 if (!Std) {
6807 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6808 return 0;
6809 }
6810
6811 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6812 Loc, Sema::LookupOrdinaryName);
6813 if (!S.LookupQualifiedName(Result, Std)) {
6814 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6815 return 0;
6816 }
6817 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6818 if (!Template) {
6819 Result.suppressDiagnostics();
6820 // We found something weird. Complain about the first thing we found.
6821 NamedDecl *Found = *Result.begin();
6822 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6823 return 0;
6824 }
6825
6826 // We found some template called std::initializer_list. Now verify that it's
6827 // correct.
6828 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006829 if (Params->getMinRequiredArguments() != 1 ||
6830 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006831 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6832 return 0;
6833 }
6834
6835 return Template;
6836}
6837
6838QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6839 if (!StdInitializerList) {
6840 StdInitializerList = LookupStdInitializerList(*this, Loc);
6841 if (!StdInitializerList)
6842 return QualType();
6843 }
6844
6845 TemplateArgumentListInfo Args(Loc, Loc);
6846 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6847 Context.getTrivialTypeSourceInfo(Element,
6848 Loc)));
6849 return Context.getCanonicalType(
6850 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6851}
6852
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006853bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6854 // C++ [dcl.init.list]p2:
6855 // A constructor is an initializer-list constructor if its first parameter
6856 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6857 // std::initializer_list<E> for some type E, and either there are no other
6858 // parameters or else all other parameters have default arguments.
6859 if (Ctor->getNumParams() < 1 ||
6860 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6861 return false;
6862
6863 QualType ArgType = Ctor->getParamDecl(0)->getType();
6864 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6865 ArgType = RT->getPointeeType().getUnqualifiedType();
6866
6867 return isStdInitializerList(ArgType, 0);
6868}
6869
Douglas Gregora172e082011-03-26 22:25:30 +00006870/// \brief Determine whether a using statement is in a context where it will be
6871/// apply in all contexts.
6872static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6873 switch (CurContext->getDeclKind()) {
6874 case Decl::TranslationUnit:
6875 return true;
6876 case Decl::LinkageSpec:
6877 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6878 default:
6879 return false;
6880 }
6881}
6882
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006883namespace {
6884
6885// Callback to only accept typo corrections that are namespaces.
6886class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006887public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006888 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006889 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006890 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006891 return false;
6892 }
6893};
6894
6895}
6896
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006897static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6898 CXXScopeSpec &SS,
6899 SourceLocation IdentLoc,
6900 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006901 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006902 R.clear();
6903 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006904 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00006905 Validator,
6906 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006907 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006908 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6909 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006910 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006911 S.diagnoseTypo(Corrected,
6912 S.PDiag(diag::err_using_directive_member_suggest)
6913 << Ident << DC << DroppedSpecifier << SS.getRange(),
6914 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006915 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006916 S.diagnoseTypo(Corrected,
6917 S.PDiag(diag::err_using_directive_suggest) << Ident,
6918 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006919 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006920 R.addDecl(Corrected.getCorrectionDecl());
6921 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006922 }
6923 return false;
6924}
6925
John McCall48871652010-08-21 09:40:31 +00006926Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006927 SourceLocation UsingLoc,
6928 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006929 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006930 SourceLocation IdentLoc,
6931 IdentifierInfo *NamespcName,
6932 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006933 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6934 assert(NamespcName && "Invalid NamespcName.");
6935 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006936
6937 // This can only happen along a recovery path.
6938 while (S->getFlags() & Scope::TemplateParamScope)
6939 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006940 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006941
Douglas Gregor889ceb72009-02-03 19:21:40 +00006942 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006943 NestedNameSpecifier *Qualifier = 0;
6944 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006945 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006946
Douglas Gregor34074322009-01-14 22:20:51 +00006947 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006948 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6949 LookupParsedName(R, S, &SS);
6950 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006951 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006952
Douglas Gregorcdf87022010-06-29 17:53:46 +00006953 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006954 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006955 // Allow "using namespace std;" or "using namespace ::std;" even if
6956 // "std" hasn't been defined yet, for GCC compatibility.
6957 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6958 NamespcName->isStr("std")) {
6959 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006960 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006961 R.resolveKind();
6962 }
6963 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006964 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006965 }
6966
John McCall9f3059a2009-10-09 21:13:30 +00006967 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006968 NamedDecl *Named = R.getFoundDecl();
6969 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6970 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006971 // C++ [namespace.udir]p1:
6972 // A using-directive specifies that the names in the nominated
6973 // namespace can be used in the scope in which the
6974 // using-directive appears after the using-directive. During
6975 // unqualified name lookup (3.4.1), the names appear as if they
6976 // were declared in the nearest enclosing namespace which
6977 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006978 // namespace. [Note: in this context, "contains" means "contains
6979 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006980
6981 // Find enclosing context containing both using-directive and
6982 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006983 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006984 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6985 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6986 CommonAncestor = CommonAncestor->getParent();
6987
Sebastian Redla6602e92009-11-23 15:34:23 +00006988 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006989 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006990 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006991
Douglas Gregora172e082011-03-26 22:25:30 +00006992 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00006993 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006994 Diag(IdentLoc, diag::warn_using_directive_in_header);
6995 }
6996
Douglas Gregor889ceb72009-02-03 19:21:40 +00006997 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006998 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006999 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007000 }
7001
Richard Smith54ecd982013-02-20 19:22:51 +00007002 if (UDir)
7003 ProcessDeclAttributeList(S, UDir, AttrList);
7004
John McCall48871652010-08-21 09:40:31 +00007005 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007006}
7007
7008void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007009 // If the scope has an associated entity and the using directive is at
7010 // namespace or translation unit scope, add the UsingDirectiveDecl into
7011 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007012 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007013 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007014 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007015 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007016 // Otherwise, it is at block sope. The using-directives will affect lookup
7017 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007018 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007019}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007020
Douglas Gregorfec52632009-06-20 00:51:54 +00007021
John McCall48871652010-08-21 09:40:31 +00007022Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007023 AccessSpecifier AS,
7024 bool HasUsingKeyword,
7025 SourceLocation UsingLoc,
7026 CXXScopeSpec &SS,
7027 UnqualifiedId &Name,
7028 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007029 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007030 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007031 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007032
Douglas Gregor220f4272009-11-04 16:30:06 +00007033 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007034 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007035 case UnqualifiedId::IK_Identifier:
7036 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007037 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007038 case UnqualifiedId::IK_ConversionFunctionId:
7039 break;
7040
7041 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007042 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007043 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007044 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007045 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007046 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007047 diag::err_using_decl_constructor)
7048 << SS.getRange();
7049
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007050 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007051
John McCall48871652010-08-21 09:40:31 +00007052 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007053
7054 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007055 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007056 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007057 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007058
7059 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007060 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007061 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007062 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007063 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007064
7065 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7066 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007067 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007068 return 0;
John McCall3969e302009-12-08 07:46:18 +00007069
Richard Smithc2bc61b2013-03-18 21:12:30 +00007070 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007071 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007072 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007073 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7074 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007075 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007076 }
7077
Douglas Gregorc4356532010-12-16 00:46:58 +00007078 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7079 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7080 return 0;
7081
John McCall3f746822009-11-17 05:59:44 +00007082 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007083 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007084 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007085 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007086 if (UD)
7087 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007088
John McCall48871652010-08-21 09:40:31 +00007089 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007090}
7091
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007092/// \brief Determine whether a using declaration considers the given
7093/// declarations as "equivalent", e.g., if they are redeclarations of
7094/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007095static bool
7096IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7097 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007098 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007099
Richard Smithdda56e42011-04-15 14:24:37 +00007100 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007101 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007102 return Context.hasSameType(TD1->getUnderlyingType(),
7103 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007104
7105 return false;
7106}
7107
7108
John McCall84d87672009-12-10 09:41:52 +00007109/// Determines whether to create a using shadow decl for a particular
7110/// decl, given the set of decls existing prior to this using lookup.
7111bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007112 const LookupResult &Previous,
7113 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007114 // Diagnose finding a decl which is not from a base class of the
7115 // current class. We do this now because there are cases where this
7116 // function will silently decide not to build a shadow decl, which
7117 // will pre-empt further diagnostics.
7118 //
7119 // We don't need to do this in C++0x because we do the check once on
7120 // the qualifier.
7121 //
7122 // FIXME: diagnose the following if we care enough:
7123 // struct A { int foo; };
7124 // struct B : A { using A::foo; };
7125 // template <class T> struct C : A {};
7126 // template <class T> struct D : C<T> { using B::foo; } // <---
7127 // This is invalid (during instantiation) in C++03 because B::foo
7128 // resolves to the using decl in B, which is not a base class of D<T>.
7129 // We can't diagnose it immediately because C<T> is an unknown
7130 // specialization. The UsingShadowDecl in D<T> then points directly
7131 // to A::foo, which will look well-formed when we instantiate.
7132 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007133 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007134 DeclContext *OrigDC = Orig->getDeclContext();
7135
7136 // Handle enums and anonymous structs.
7137 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7138 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7139 while (OrigRec->isAnonymousStructOrUnion())
7140 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7141
7142 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7143 if (OrigDC == CurContext) {
7144 Diag(Using->getLocation(),
7145 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007146 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007147 Diag(Orig->getLocation(), diag::note_using_decl_target);
7148 return true;
7149 }
7150
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007151 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007152 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007153 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007154 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007155 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007156 Diag(Orig->getLocation(), diag::note_using_decl_target);
7157 return true;
7158 }
7159 }
7160
7161 if (Previous.empty()) return false;
7162
7163 NamedDecl *Target = Orig;
7164 if (isa<UsingShadowDecl>(Target))
7165 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7166
John McCalla17e83e2009-12-11 02:33:26 +00007167 // If the target happens to be one of the previous declarations, we
7168 // don't have a conflict.
7169 //
7170 // FIXME: but we might be increasing its access, in which case we
7171 // should redeclare it.
7172 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007173 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007174 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7175 I != E; ++I) {
7176 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007177 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7178 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7179 PrevShadow = Shadow;
7180 FoundEquivalentDecl = true;
7181 }
John McCalla17e83e2009-12-11 02:33:26 +00007182
7183 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7184 }
7185
Richard Smithfd8634a2013-10-23 02:17:46 +00007186 if (FoundEquivalentDecl)
7187 return false;
7188
Alp Tokera2794f92014-01-22 07:29:52 +00007189 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007190 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007191 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007192 case Ovl_Overload:
7193 return false;
7194
7195 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007196 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007197 break;
Richard Smith18819302014-02-06 01:31:33 +00007198
John McCall84d87672009-12-10 09:41:52 +00007199 // We found a decl with the exact signature.
7200 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007201 // If we're in a record, we want to hide the target, so we
7202 // return true (without a diagnostic) to tell the caller not to
7203 // build a shadow decl.
7204 if (CurContext->isRecord())
7205 return true;
7206
7207 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007208 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007209 break;
7210 }
7211
7212 Diag(Target->getLocation(), diag::note_using_decl_target);
7213 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7214 return true;
7215 }
7216
7217 // Target is not a function.
7218
John McCall84d87672009-12-10 09:41:52 +00007219 if (isa<TagDecl>(Target)) {
7220 // No conflict between a tag and a non-tag.
7221 if (!Tag) return false;
7222
John McCalle29c5cd2009-12-10 19:51:03 +00007223 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007224 Diag(Target->getLocation(), diag::note_using_decl_target);
7225 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7226 return true;
7227 }
7228
7229 // No conflict between a tag and a non-tag.
7230 if (!NonTag) return false;
7231
John McCalle29c5cd2009-12-10 19:51:03 +00007232 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007233 Diag(Target->getLocation(), diag::note_using_decl_target);
7234 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7235 return true;
7236}
7237
John McCall3f746822009-11-17 05:59:44 +00007238/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007239UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007240 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007241 NamedDecl *Orig,
7242 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007243
7244 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007245 NamedDecl *Target = Orig;
7246 if (isa<UsingShadowDecl>(Target)) {
7247 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7248 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007249 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007250
John McCall3f746822009-11-17 05:59:44 +00007251 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007252 = UsingShadowDecl::Create(Context, CurContext,
7253 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007254 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007255
Douglas Gregor457104e2010-09-29 04:25:11 +00007256 Shadow->setAccess(UD->getAccess());
7257 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7258 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007259
7260 Shadow->setPreviousDecl(PrevDecl);
7261
John McCall3f746822009-11-17 05:59:44 +00007262 if (S)
John McCall3969e302009-12-08 07:46:18 +00007263 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007264 else
John McCall3969e302009-12-08 07:46:18 +00007265 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007266
John McCall3969e302009-12-08 07:46:18 +00007267
John McCall84d87672009-12-10 09:41:52 +00007268 return Shadow;
7269}
John McCall3969e302009-12-08 07:46:18 +00007270
John McCall84d87672009-12-10 09:41:52 +00007271/// Hides a using shadow declaration. This is required by the current
7272/// using-decl implementation when a resolvable using declaration in a
7273/// class is followed by a declaration which would hide or override
7274/// one or more of the using decl's targets; for example:
7275///
7276/// struct Base { void foo(int); };
7277/// struct Derived : Base {
7278/// using Base::foo;
7279/// void foo(int);
7280/// };
7281///
7282/// The governing language is C++03 [namespace.udecl]p12:
7283///
7284/// When a using-declaration brings names from a base class into a
7285/// derived class scope, member functions in the derived class
7286/// override and/or hide member functions with the same name and
7287/// parameter types in a base class (rather than conflicting).
7288///
7289/// There are two ways to implement this:
7290/// (1) optimistically create shadow decls when they're not hidden
7291/// by existing declarations, or
7292/// (2) don't create any shadow decls (or at least don't make them
7293/// visible) until we've fully parsed/instantiated the class.
7294/// The problem with (1) is that we might have to retroactively remove
7295/// a shadow decl, which requires several O(n) operations because the
7296/// decl structures are (very reasonably) not designed for removal.
7297/// (2) avoids this but is very fiddly and phase-dependent.
7298void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007299 if (Shadow->getDeclName().getNameKind() ==
7300 DeclarationName::CXXConversionFunctionName)
7301 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7302
John McCall84d87672009-12-10 09:41:52 +00007303 // Remove it from the DeclContext...
7304 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007305
John McCall84d87672009-12-10 09:41:52 +00007306 // ...and the scope, if applicable...
7307 if (S) {
John McCall48871652010-08-21 09:40:31 +00007308 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007309 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007310 }
7311
John McCall84d87672009-12-10 09:41:52 +00007312 // ...and the using decl.
7313 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7314
7315 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007316 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007317}
7318
Richard Smith09d5b3a2014-05-01 00:35:04 +00007319/// Find the base specifier for a base class with the given type.
7320static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7321 QualType DesiredBase,
7322 bool &AnyDependentBases) {
7323 // Check whether the named type is a direct base class.
7324 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7325 for (auto &Base : Derived->bases()) {
7326 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7327 if (CanonicalDesiredBase == BaseType)
7328 return &Base;
7329 if (BaseType->isDependentType())
7330 AnyDependentBases = true;
7331 }
7332 return 0;
7333}
7334
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007335namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007336class UsingValidatorCCC : public CorrectionCandidateCallback {
7337public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007338 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007339 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007340 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007341 IsInstantiation(IsInstantiation), OldNNS(NNS),
7342 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007343
Craig Toppera798a9d2014-03-02 09:32:10 +00007344 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007345 NamedDecl *ND = Candidate.getCorrectionDecl();
7346
7347 // Keywords are not valid here.
7348 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007349 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007350
7351 // Completely unqualified names are invalid for a 'using' declaration.
7352 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7353 return false;
7354
Richard Smith09d5b3a2014-05-01 00:35:04 +00007355 if (RequireMemberOf) {
7356 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7357 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7358 // No-one ever wants a using-declaration to name an injected-class-name
7359 // of a base class, unless they're declaring an inheriting constructor.
7360 ASTContext &Ctx = ND->getASTContext();
7361 if (!Ctx.getLangOpts().CPlusPlus11)
7362 return false;
7363 QualType FoundType = Ctx.getRecordType(FoundRecord);
7364
7365 // Check that the injected-class-name is named as a member of its own
7366 // type; we don't want to suggest 'using Derived::Base;', since that
7367 // means something else.
7368 NestedNameSpecifier *Specifier =
7369 Candidate.WillReplaceSpecifier()
7370 ? Candidate.getCorrectionSpecifier()
7371 : OldNNS;
7372 if (!Specifier->getAsType() ||
7373 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7374 return false;
7375
7376 // Check that this inheriting constructor declaration actually names a
7377 // direct base class of the current class.
7378 bool AnyDependentBases = false;
7379 if (!findDirectBaseWithType(RequireMemberOf,
7380 Ctx.getRecordType(FoundRecord),
7381 AnyDependentBases) &&
7382 !AnyDependentBases)
7383 return false;
7384 } else {
7385 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7386 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7387 return false;
7388
7389 // FIXME: Check that the base class member is accessible?
7390 }
7391 }
7392
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007393 if (isa<TypeDecl>(ND))
7394 return HasTypenameKeyword || !IsInstantiation;
7395
7396 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007397 }
7398
7399private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007400 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007401 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007402 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007403 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007404};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007405} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007406
John McCalle61f2ba2009-11-18 02:36:19 +00007407/// Builds a using declaration.
7408///
7409/// \param IsInstantiation - Whether this call arises from an
7410/// instantiation of an unresolved using declaration. We treat
7411/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007412NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7413 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007414 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007415 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007416 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007417 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007418 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007419 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007420 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007421 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007422 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007423
Anders Carlssonf038fc22009-08-28 05:49:21 +00007424 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007425
Anders Carlsson59140b32009-08-28 03:16:11 +00007426 if (SS.isEmpty()) {
7427 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007428 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007429 }
Mike Stump11289f42009-09-09 15:08:12 +00007430
John McCall84d87672009-12-10 09:41:52 +00007431 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007432 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007433 ForRedeclaration);
7434 Previous.setHideTags(false);
7435 if (S) {
7436 LookupName(Previous, S);
7437
7438 // It is really dumb that we have to do this.
7439 LookupResult::Filter F = Previous.makeFilter();
7440 while (F.hasNext()) {
7441 NamedDecl *D = F.next();
7442 if (!isDeclInScope(D, CurContext, S))
7443 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007444 // If we found a local extern declaration that's not ordinarily visible,
7445 // and this declaration is being added to a non-block scope, ignore it.
7446 // We're only checking for scope conflicts here, not also for violations
7447 // of the linkage rules.
7448 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7449 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7450 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007451 }
7452 F.done();
7453 } else {
7454 assert(IsInstantiation && "no scope in non-instantiation");
7455 assert(CurContext->isRecord() && "scope not record in instantiation");
7456 LookupQualifiedName(Previous, CurContext);
7457 }
7458
John McCall84d87672009-12-10 09:41:52 +00007459 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007460 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7461 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007462 return 0;
7463
7464 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007465 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
John McCallb96ec562009-12-04 22:46:56 +00007466 return 0;
7467
John McCall84c16cf2009-11-12 03:15:40 +00007468 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007469 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007470 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007471 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007472 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007473 // FIXME: not all declaration name kinds are legal here
7474 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7475 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007476 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007477 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007478 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007479 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7480 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007481 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007482 D->setAccess(AS);
7483 CurContext->addDecl(D);
7484 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007485 }
John McCallb96ec562009-12-04 22:46:56 +00007486
Richard Smith09d5b3a2014-05-01 00:35:04 +00007487 auto Build = [&](bool Invalid) {
7488 UsingDecl *UD =
7489 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7490 HasTypenameKeyword);
7491 UD->setAccess(AS);
7492 CurContext->addDecl(UD);
7493 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007494 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007495 };
7496 auto BuildInvalid = [&]{ return Build(true); };
7497 auto BuildValid = [&]{ return Build(false); };
7498
7499 if (RequireCompleteDeclContext(SS, LookupContext))
7500 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007501
Richard Smith23d55872012-04-02 01:30:27 +00007502 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007503 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007504 UsingDecl *UD = BuildValid();
7505 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007506 return UD;
7507 }
7508
7509 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007510
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007511 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007512
John McCall3969e302009-12-08 07:46:18 +00007513 // Unlike most lookups, we don't always want to hide tag
7514 // declarations: tag names are visible through the using declaration
7515 // even if hidden by ordinary names, *except* in a dependent context
7516 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007517 if (!IsInstantiation)
7518 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007519
John McCall5dadb652012-04-07 03:04:20 +00007520 // For the purposes of this lookup, we have a base object type
7521 // equal to that of the current context.
7522 if (CurContext->isRecord()) {
7523 R.setBaseObjectType(
7524 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7525 }
7526
John McCall27b18f82009-11-17 02:14:36 +00007527 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007528
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007529 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007530 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007531 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007532 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007533 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007534 R.getLookupKind(), S, &SS, CCC,
7535 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007536 // We reject any correction for which ND would be NULL.
7537 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007538
Richard Smithf9b15102013-08-17 00:46:16 +00007539 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007540 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007541 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7542 << NameInfo.getName() << LookupContext << 0
7543 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007544
7545 // If we corrected to an inheriting constructor, handle it as one.
7546 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7547 if (RD && RD->isInjectedClassName()) {
7548 // Fix up the information we'll use to build the using declaration.
7549 if (Corrected.WillReplaceSpecifier()) {
7550 NestedNameSpecifierLocBuilder Builder;
7551 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7552 QualifierLoc.getSourceRange());
7553 QualifierLoc = Builder.getWithLocInContext(Context);
7554 }
7555
7556 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7557 Context.getCanonicalType(Context.getRecordType(RD))));
7558 NameInfo.setNamedTypeInfo(0);
7559
7560 // Build it and process it as an inheriting constructor.
7561 UsingDecl *UD = BuildValid();
7562 CheckInheritingConstructorUsingDecl(UD);
7563 return UD;
7564 }
7565
7566 // FIXME: Pick up all the declarations if we found an overloaded function.
7567 R.setLookupName(Corrected.getCorrection());
7568 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007569 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007570 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007571 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007572 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007573 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007574 }
7575
Richard Smith09d5b3a2014-05-01 00:35:04 +00007576 if (R.isAmbiguous())
7577 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007578
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007579 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007580 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007581 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007582 Diag(IdentLoc, diag::err_using_typename_non_type);
7583 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7584 Diag((*I)->getUnderlyingDecl()->getLocation(),
7585 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007586 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007587 }
7588 } else {
7589 // If we asked for a non-typename and we got a type, error out,
7590 // but only if this is an instantiation of an unresolved using
7591 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007592 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007593 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7594 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007595 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007596 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007597 }
7598
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007599 // C++0x N2914 [namespace.udecl]p6:
7600 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007601 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007602 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7603 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007604 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007605 }
Mike Stump11289f42009-09-09 15:08:12 +00007606
Richard Smith09d5b3a2014-05-01 00:35:04 +00007607 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007608 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007609 UsingShadowDecl *PrevDecl = 0;
7610 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7611 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007612 }
John McCall3f746822009-11-17 05:59:44 +00007613
7614 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007615}
7616
Sebastian Redl08905022011-02-05 19:23:19 +00007617/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007618bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007619 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007620
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007621 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007622 assert(SourceType &&
7623 "Using decl naming constructor doesn't have type in scope spec.");
7624 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7625
7626 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007627 bool AnyDependentBases = false;
7628 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7629 AnyDependentBases);
7630 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007631 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007632 diag::err_using_decl_constructor_not_in_direct_base)
7633 << UD->getNameInfo().getSourceRange()
7634 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007635 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007636 return true;
7637 }
7638
Richard Smith09d5b3a2014-05-01 00:35:04 +00007639 if (Base)
7640 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007641
7642 return false;
7643}
7644
John McCall84d87672009-12-10 09:41:52 +00007645/// Checks that the given using declaration is not an invalid
7646/// redeclaration. Note that this is checking only for the using decl
7647/// itself, not for any ill-formedness among the UsingShadowDecls.
7648bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007649 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007650 const CXXScopeSpec &SS,
7651 SourceLocation NameLoc,
7652 const LookupResult &Prev) {
7653 // C++03 [namespace.udecl]p8:
7654 // C++0x [namespace.udecl]p10:
7655 // A using-declaration is a declaration and can therefore be used
7656 // repeatedly where (and only where) multiple declarations are
7657 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007658 //
John McCall032092f2010-11-29 18:01:58 +00007659 // That's in non-member contexts.
7660 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007661 return false;
7662
Aaron Ballman4a979672014-01-03 13:56:08 +00007663 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007664
7665 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7666 NamedDecl *D = *I;
7667
7668 bool DTypename;
7669 NestedNameSpecifier *DQual;
7670 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007671 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007672 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007673 } else if (UnresolvedUsingValueDecl *UD
7674 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7675 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007676 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007677 } else if (UnresolvedUsingTypenameDecl *UD
7678 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7679 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007680 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007681 } else continue;
7682
7683 // using decls differ if one says 'typename' and the other doesn't.
7684 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007685 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007686
7687 // using decls differ if they name different scopes (but note that
7688 // template instantiation can cause this check to trigger when it
7689 // didn't before instantiation).
7690 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7691 Context.getCanonicalNestedNameSpecifier(DQual))
7692 continue;
7693
7694 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007695 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007696 return true;
7697 }
7698
7699 return false;
7700}
7701
John McCall3969e302009-12-08 07:46:18 +00007702
John McCallb96ec562009-12-04 22:46:56 +00007703/// Checks that the given nested-name qualifier used in a using decl
7704/// in the current context is appropriately related to the current
7705/// scope. If an error is found, diagnoses it and returns true.
7706bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7707 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007708 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007709 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007710 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007711
John McCall3969e302009-12-08 07:46:18 +00007712 if (!CurContext->isRecord()) {
7713 // C++03 [namespace.udecl]p3:
7714 // C++0x [namespace.udecl]p8:
7715 // A using-declaration for a class member shall be a member-declaration.
7716
7717 // If we weren't able to compute a valid scope, it must be a
7718 // dependent class scope.
7719 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007720 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7721 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7722 RD = 0;
7723
John McCall3969e302009-12-08 07:46:18 +00007724 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7725 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007726
7727 // If we have a complete, non-dependent source type, try to suggest a
7728 // way to get the same effect.
7729 if (!RD)
7730 return true;
7731
7732 // Find what this using-declaration was referring to.
7733 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7734 R.setHideTags(false);
7735 R.suppressDiagnostics();
7736 LookupQualifiedName(R, RD);
7737
7738 if (R.getAsSingle<TypeDecl>()) {
7739 if (getLangOpts().CPlusPlus11) {
7740 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7741 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7742 << 0 // alias declaration
7743 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7744 NameInfo.getName().getAsString() +
7745 " = ");
7746 } else {
7747 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7748 SourceLocation InsertLoc =
7749 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7750 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7751 << 1 // typedef declaration
7752 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7753 << FixItHint::CreateInsertion(
7754 InsertLoc, " " + NameInfo.getName().getAsString());
7755 }
7756 } else if (R.getAsSingle<VarDecl>()) {
7757 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7758 // repeating the type of the static data member here.
7759 FixItHint FixIt;
7760 if (getLangOpts().CPlusPlus11) {
7761 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7762 FixIt = FixItHint::CreateReplacement(
7763 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7764 }
7765
7766 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7767 << 2 // reference declaration
7768 << FixIt;
7769 }
John McCall3969e302009-12-08 07:46:18 +00007770 return true;
7771 }
7772
7773 // Otherwise, everything is known to be fine.
7774 return false;
7775 }
7776
7777 // The current scope is a record.
7778
7779 // If the named context is dependent, we can't decide much.
7780 if (!NamedContext) {
7781 // FIXME: in C++0x, we can diagnose if we can prove that the
7782 // nested-name-specifier does not refer to a base class, which is
7783 // still possible in some cases.
7784
7785 // Otherwise we have to conservatively report that things might be
7786 // okay.
7787 return false;
7788 }
7789
7790 if (!NamedContext->isRecord()) {
7791 // Ideally this would point at the last name in the specifier,
7792 // but we don't have that level of source info.
7793 Diag(SS.getRange().getBegin(),
7794 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007795 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007796 return true;
7797 }
7798
Douglas Gregor7c842292010-12-21 07:41:49 +00007799 if (!NamedContext->isDependentContext() &&
7800 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7801 return true;
7802
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007803 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007804 // C++0x [namespace.udecl]p3:
7805 // In a using-declaration used as a member-declaration, the
7806 // nested-name-specifier shall name a base class of the class
7807 // being defined.
7808
7809 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7810 cast<CXXRecordDecl>(NamedContext))) {
7811 if (CurContext == NamedContext) {
7812 Diag(NameLoc,
7813 diag::err_using_decl_nested_name_specifier_is_current_class)
7814 << SS.getRange();
7815 return true;
7816 }
7817
7818 Diag(SS.getRange().getBegin(),
7819 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007820 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007821 << cast<CXXRecordDecl>(CurContext)
7822 << SS.getRange();
7823 return true;
7824 }
7825
7826 return false;
7827 }
7828
7829 // C++03 [namespace.udecl]p4:
7830 // A using-declaration used as a member-declaration shall refer
7831 // to a member of a base class of the class being defined [etc.].
7832
7833 // Salient point: SS doesn't have to name a base class as long as
7834 // lookup only finds members from base classes. Therefore we can
7835 // diagnose here only if we can prove that that can't happen,
7836 // i.e. if the class hierarchies provably don't intersect.
7837
7838 // TODO: it would be nice if "definitely valid" results were cached
7839 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7840 // need to be repeated.
7841
7842 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007843 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007844
7845 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7846 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7847 Data->Bases.insert(Base);
7848 return true;
7849 }
7850
7851 bool hasDependentBases(const CXXRecordDecl *Class) {
7852 return !Class->forallBases(collect, this);
7853 }
7854
7855 /// Returns true if the base is dependent or is one of the
7856 /// accumulated base classes.
7857 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7858 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7859 return !Data->Bases.count(Base);
7860 }
7861
7862 bool mightShareBases(const CXXRecordDecl *Class) {
7863 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7864 }
7865 };
7866
7867 UserData Data;
7868
7869 // Returns false if we find a dependent base.
7870 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7871 return false;
7872
7873 // Returns false if the class has a dependent base or if it or one
7874 // of its bases is present in the base set of the current context.
7875 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7876 return false;
7877
7878 Diag(SS.getRange().getBegin(),
7879 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007880 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007881 << cast<CXXRecordDecl>(CurContext)
7882 << SS.getRange();
7883
7884 return true;
John McCallb96ec562009-12-04 22:46:56 +00007885}
7886
Richard Smithdda56e42011-04-15 14:24:37 +00007887Decl *Sema::ActOnAliasDeclaration(Scope *S,
7888 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007889 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007890 SourceLocation UsingLoc,
7891 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007892 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007893 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007894 // Skip up to the relevant declaration scope.
7895 while (S->getFlags() & Scope::TemplateParamScope)
7896 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007897 assert((S->getFlags() & Scope::DeclScope) &&
7898 "got alias-declaration outside of declaration scope");
7899
7900 if (Type.isInvalid())
7901 return 0;
7902
7903 bool Invalid = false;
7904 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7905 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007906 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007907
7908 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7909 return 0;
7910
7911 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007912 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007913 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007914 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7915 TInfo->getTypeLoc().getBeginLoc());
7916 }
Richard Smithdda56e42011-04-15 14:24:37 +00007917
7918 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7919 LookupName(Previous, S);
7920
7921 // Warn about shadowing the name of a template parameter.
7922 if (Previous.isSingleResult() &&
7923 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007924 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007925 Previous.clear();
7926 }
7927
7928 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7929 "name in alias declaration must be an identifier");
7930 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7931 Name.StartLocation,
7932 Name.Identifier, TInfo);
7933
7934 NewTD->setAccess(AS);
7935
7936 if (Invalid)
7937 NewTD->setInvalidDecl();
7938
Richard Smith54ecd982013-02-20 19:22:51 +00007939 ProcessDeclAttributeList(S, NewTD, AttrList);
7940
Richard Smith3f1b5d02011-05-05 21:57:07 +00007941 CheckTypedefForVariablyModifiedType(S, NewTD);
7942 Invalid |= NewTD->isInvalidDecl();
7943
Richard Smithdda56e42011-04-15 14:24:37 +00007944 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007945
7946 NamedDecl *NewND;
7947 if (TemplateParamLists.size()) {
7948 TypeAliasTemplateDecl *OldDecl = 0;
7949 TemplateParameterList *OldTemplateParams = 0;
7950
7951 if (TemplateParamLists.size() != 1) {
7952 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007953 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7954 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007955 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007956 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007957
7958 // Only consider previous declarations in the same scope.
7959 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7960 /*ExplicitInstantiationOrSpecialization*/false);
7961 if (!Previous.empty()) {
7962 Redeclaration = true;
7963
7964 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7965 if (!OldDecl && !Invalid) {
7966 Diag(UsingLoc, diag::err_redefinition_different_kind)
7967 << Name.Identifier;
7968
7969 NamedDecl *OldD = Previous.getRepresentativeDecl();
7970 if (OldD->getLocation().isValid())
7971 Diag(OldD->getLocation(), diag::note_previous_definition);
7972
7973 Invalid = true;
7974 }
7975
7976 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7977 if (TemplateParameterListsAreEqual(TemplateParams,
7978 OldDecl->getTemplateParameters(),
7979 /*Complain=*/true,
7980 TPL_TemplateMatch))
7981 OldTemplateParams = OldDecl->getTemplateParameters();
7982 else
7983 Invalid = true;
7984
7985 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7986 if (!Invalid &&
7987 !Context.hasSameType(OldTD->getUnderlyingType(),
7988 NewTD->getUnderlyingType())) {
7989 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7990 // but we can't reasonably accept it.
7991 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7992 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7993 if (OldTD->getLocation().isValid())
7994 Diag(OldTD->getLocation(), diag::note_previous_definition);
7995 Invalid = true;
7996 }
7997 }
7998 }
7999
8000 // Merge any previous default template arguments into our parameters,
8001 // and check the parameter list.
8002 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8003 TPC_TypeAliasTemplate))
8004 return 0;
8005
8006 TypeAliasTemplateDecl *NewDecl =
8007 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8008 Name.Identifier, TemplateParams,
8009 NewTD);
8010
8011 NewDecl->setAccess(AS);
8012
8013 if (Invalid)
8014 NewDecl->setInvalidDecl();
8015 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008016 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008017
8018 NewND = NewDecl;
8019 } else {
8020 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8021 NewND = NewTD;
8022 }
Richard Smithdda56e42011-04-15 14:24:37 +00008023
8024 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008025 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008026
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008027 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008028 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008029}
8030
John McCall48871652010-08-21 09:40:31 +00008031Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008032 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008033 SourceLocation AliasLoc,
8034 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008035 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008036 SourceLocation IdentLoc,
8037 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008038
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008039 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008040 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8041 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008042
Anders Carlssondca83c42009-03-28 06:23:46 +00008043 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008044 NamedDecl *PrevDecl
8045 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8046 ForRedeclaration);
8047 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8048 PrevDecl = 0;
8049
8050 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008051 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008052 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008053 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008054 // FIXME: At some point, we'll want to create the (redundant)
8055 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008056 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008057 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00008058 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008059 }
Mike Stump11289f42009-09-09 15:08:12 +00008060
Anders Carlssondca83c42009-03-28 06:23:46 +00008061 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8062 diag::err_redefinition_different_kind;
8063 Diag(AliasLoc, DiagID) << Alias;
8064 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00008065 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00008066 }
8067
John McCall27b18f82009-11-17 02:14:36 +00008068 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008069 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00008070
John McCall9f3059a2009-10-09 21:13:30 +00008071 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008072 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008073 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008074 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008075 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008076 }
Mike Stump11289f42009-09-09 15:08:12 +00008077
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008078 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008079 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008080 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008081 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008082
John McCalld8d0d432010-02-16 06:53:13 +00008083 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008084 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008085}
8086
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008087Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008088Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8089 CXXMethodDecl *MD) {
8090 CXXRecordDecl *ClassDecl = MD->getParent();
8091
Douglas Gregor6d880b12010-07-01 22:31:05 +00008092 // C++ [except.spec]p14:
8093 // An implicitly declared special member function (Clause 12) shall have an
8094 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008095 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008096 if (ClassDecl->isInvalidDecl())
8097 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008098
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008099 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008100 for (const auto &B : ClassDecl->bases()) {
8101 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008102 continue;
8103
Aaron Ballman574705e2014-03-13 15:41:46 +00008104 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008105 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008106 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8107 // If this is a deleted function, add it anyway. This might be conformant
8108 // with the standard. This might not. I'm not sure. It might not matter.
8109 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008110 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008111 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008112 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008113
8114 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008115 for (const auto &B : ClassDecl->vbases()) {
8116 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008117 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008118 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8119 // If this is a deleted function, add it anyway. This might be conformant
8120 // with the standard. This might not. I'm not sure. It might not matter.
8121 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008122 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008123 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008124 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008125
8126 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008127 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008128 if (F->hasInClassInitializer()) {
8129 if (Expr *E = F->getInClassInitializer())
8130 ExceptSpec.CalledExpr(E);
8131 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008132 // DR1351:
8133 // If the brace-or-equal-initializer of a non-static data member
8134 // invokes a defaulted default constructor of its class or of an
8135 // enclosing class in a potentially evaluated subexpression, the
8136 // program is ill-formed.
8137 //
8138 // This resolution is unworkable: the exception specification of the
8139 // default constructor can be needed in an unevaluated context, in
8140 // particular, in the operand of a noexcept-expression, and we can be
8141 // unable to compute an exception specification for an enclosed class.
8142 //
8143 // We do not allow an in-class initializer to require the evaluation
8144 // of the exception specification for any in-class initializer whose
8145 // definition is not lexically complete.
8146 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008147 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008148 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008149 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8150 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8151 // If this is a deleted function, add it anyway. This might be conformant
8152 // with the standard. This might not. I'm not sure. It might not matter.
8153 // In particular, the problem is that this function never gets called. It
8154 // might just be ill-formed because this function attempts to refer to
8155 // a deleted function here.
8156 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008157 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008158 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008159 }
John McCalldb40c7f2010-12-14 08:05:40 +00008160
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008161 return ExceptSpec;
8162}
8163
Richard Smithc2bc61b2013-03-18 21:12:30 +00008164Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008165Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8166 CXXRecordDecl *ClassDecl = CD->getParent();
8167
8168 // C++ [except.spec]p14:
8169 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008170 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008171 if (ClassDecl->isInvalidDecl())
8172 return ExceptSpec;
8173
8174 // Inherited constructor.
8175 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8176 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8177 // FIXME: Copying or moving the parameters could add extra exceptions to the
8178 // set, as could the default arguments for the inherited constructor. This
8179 // will be addressed when we implement the resolution of core issue 1351.
8180 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8181
8182 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008183 for (const auto &B : ClassDecl->bases()) {
8184 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008185 continue;
8186
Aaron Ballman574705e2014-03-13 15:41:46 +00008187 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008188 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8189 if (BaseClassDecl == InheritedDecl)
8190 continue;
8191 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8192 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008193 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008194 }
8195 }
8196
8197 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008198 for (const auto &B : ClassDecl->vbases()) {
8199 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008200 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8201 if (BaseClassDecl == InheritedDecl)
8202 continue;
8203 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8204 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008205 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008206 }
8207 }
8208
8209 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008210 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008211 if (F->hasInClassInitializer()) {
8212 if (Expr *E = F->getInClassInitializer())
8213 ExceptSpec.CalledExpr(E);
8214 else if (!F->isInvalidDecl())
8215 Diag(CD->getLocation(),
8216 diag::err_in_class_initializer_references_def_ctor) << CD;
8217 } else if (const RecordType *RecordTy
8218 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8219 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8220 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8221 if (Constructor)
8222 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8223 }
8224 }
8225
Richard Smithc2bc61b2013-03-18 21:12:30 +00008226 return ExceptSpec;
8227}
8228
Richard Smith8bf22e52012-11-29 01:34:07 +00008229namespace {
8230/// RAII object to register a special member as being currently declared.
8231struct DeclaringSpecialMember {
8232 Sema &S;
8233 Sema::SpecialMemberDecl D;
8234 bool WasAlreadyBeingDeclared;
8235
8236 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8237 : S(S), D(RD, CSM) {
8238 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8239 if (WasAlreadyBeingDeclared)
8240 // This almost never happens, but if it does, ensure that our cache
8241 // doesn't contain a stale result.
8242 S.SpecialMemberCache.clear();
8243
8244 // FIXME: Register a note to be produced if we encounter an error while
8245 // declaring the special member.
8246 }
8247 ~DeclaringSpecialMember() {
8248 if (!WasAlreadyBeingDeclared)
8249 S.SpecialMembersBeingDeclared.erase(D);
8250 }
8251
8252 /// \brief Are we already trying to declare this special member?
8253 bool isAlreadyBeingDeclared() const {
8254 return WasAlreadyBeingDeclared;
8255 }
8256};
8257}
8258
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008259CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8260 CXXRecordDecl *ClassDecl) {
8261 // C++ [class.ctor]p5:
8262 // A default constructor for a class X is a constructor of class X
8263 // that can be called without an argument. If there is no
8264 // user-declared constructor for class X, a default constructor is
8265 // implicitly declared. An implicitly-declared default constructor
8266 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008267 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008268 "Should not build implicit default constructor!");
8269
Richard Smith8bf22e52012-11-29 01:34:07 +00008270 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8271 if (DSM.isAlreadyBeingDeclared())
8272 return 0;
8273
Richard Smithb5800092012-06-10 05:43:50 +00008274 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8275 CXXDefaultConstructor,
8276 false);
8277
Douglas Gregor6d880b12010-07-01 22:31:05 +00008278 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008279 CanQualType ClassType
8280 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008281 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008282 DeclarationName Name
8283 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008284 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008285 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008286 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008287 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008288 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008289 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008290 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008291 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008292
8293 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008294 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008295 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008296
Richard Smith6b02d462012-12-08 08:32:28 +00008297 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8298 // constructors is easy to compute.
8299 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8300
8301 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008302 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008303
Douglas Gregor9672f922010-07-03 00:47:00 +00008304 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008305 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008306
Douglas Gregor0be31a22010-07-02 17:43:08 +00008307 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008308 PushOnScopeChains(DefaultCon, S, false);
8309 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008310
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008311 return DefaultCon;
8312}
8313
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008314void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8315 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008316 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008317 !Constructor->doesThisDeclarationHaveABody() &&
8318 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008319 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008320
Anders Carlsson423f5d82010-04-23 16:04:08 +00008321 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008322 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008323
Eli Friedmaneaf34142012-10-18 20:14:08 +00008324 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008325 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008326 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008327 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008328 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008329 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008330 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008331 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008332 }
Douglas Gregor73193272010-09-20 16:48:21 +00008333
8334 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008335 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008336
Eli Friedman276dd182013-09-05 00:02:25 +00008337 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008338 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008339
8340 if (ASTMutationListener *L = getASTMutationListener()) {
8341 L->CompletedImplicitDefinition(Constructor);
8342 }
Richard Trieuef64e942013-10-25 00:56:00 +00008343
8344 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008345}
8346
Richard Smith938f40b2011-06-11 17:19:42 +00008347void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008348 // Perform any delayed checks on exception specifications.
8349 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008350}
8351
Richard Smith185be182013-04-10 05:48:59 +00008352namespace {
8353/// Information on inheriting constructors to declare.
8354class InheritingConstructorInfo {
8355public:
8356 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8357 : SemaRef(SemaRef), Derived(Derived) {
8358 // Mark the constructors that we already have in the derived class.
8359 //
8360 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8361 // unless there is a user-declared constructor with the same signature in
8362 // the class where the using-declaration appears.
8363 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8364 }
8365
8366 void inheritAll(CXXRecordDecl *RD) {
8367 visitAll(RD, &InheritingConstructorInfo::inherit);
8368 }
8369
8370private:
8371 /// Information about an inheriting constructor.
8372 struct InheritingConstructor {
8373 InheritingConstructor()
8374 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8375
8376 /// If \c true, a constructor with this signature is already declared
8377 /// in the derived class.
8378 bool DeclaredInDerived;
8379
8380 /// The constructor which is inherited.
8381 const CXXConstructorDecl *BaseCtor;
8382
8383 /// The derived constructor we declared.
8384 CXXConstructorDecl *DerivedCtor;
8385 };
8386
8387 /// Inheriting constructors with a given canonical type. There can be at
8388 /// most one such non-template constructor, and any number of templated
8389 /// constructors.
8390 struct InheritingConstructorsForType {
8391 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008392 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8393 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008394
8395 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8396 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8397 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8398 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8399 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8400 false, S.TPL_TemplateMatch))
8401 return Templates[I].second;
8402 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8403 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008404 }
Richard Smith185be182013-04-10 05:48:59 +00008405
8406 return NonTemplate;
8407 }
8408 };
8409
8410 /// Get or create the inheriting constructor record for a constructor.
8411 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8412 QualType CtorType) {
8413 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8414 .getEntry(SemaRef, Ctor);
8415 }
8416
8417 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8418
8419 /// Process all constructors for a class.
8420 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008421 for (const auto *Ctor : RD->ctors())
8422 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008423 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8424 I(RD->decls_begin()), E(RD->decls_end());
8425 I != E; ++I) {
8426 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8427 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8428 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008429 }
8430 }
Richard Smith185be182013-04-10 05:48:59 +00008431
8432 /// Note that a constructor (or constructor template) was declared in Derived.
8433 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8434 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8435 }
8436
8437 /// Inherit a single constructor.
8438 void inherit(const CXXConstructorDecl *Ctor) {
8439 const FunctionProtoType *CtorType =
8440 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008441 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008442 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8443
8444 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8445
8446 // Core issue (no number yet): the ellipsis is always discarded.
8447 if (EPI.Variadic) {
8448 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8449 SemaRef.Diag(Ctor->getLocation(),
8450 diag::note_using_decl_constructor_ellipsis);
8451 EPI.Variadic = false;
8452 }
8453
8454 // Declare a constructor for each number of parameters.
8455 //
8456 // C++11 [class.inhctor]p1:
8457 // The candidate set of inherited constructors from the class X named in
8458 // the using-declaration consists of [... modulo defects ...] for each
8459 // constructor or constructor template of X, the set of constructors or
8460 // constructor templates that results from omitting any ellipsis parameter
8461 // specification and successively omitting parameters with a default
8462 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008463 unsigned MinParams = minParamsToInherit(Ctor);
8464 unsigned Params = Ctor->getNumParams();
8465 if (Params >= MinParams) {
8466 do
8467 declareCtor(UsingLoc, Ctor,
8468 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008469 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008470 while (Params > MinParams &&
8471 Ctor->getParamDecl(--Params)->hasDefaultArg());
8472 }
Richard Smith185be182013-04-10 05:48:59 +00008473 }
8474
8475 /// Find the using-declaration which specified that we should inherit the
8476 /// constructors of \p Base.
8477 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8478 // No fancy lookup required; just look for the base constructor name
8479 // directly within the derived class.
8480 ASTContext &Context = SemaRef.Context;
8481 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8482 Context.getCanonicalType(Context.getRecordType(Base)));
8483 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8484 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8485 }
8486
8487 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8488 // C++11 [class.inhctor]p3:
8489 // [F]or each constructor template in the candidate set of inherited
8490 // constructors, a constructor template is implicitly declared
8491 if (Ctor->getDescribedFunctionTemplate())
8492 return 0;
8493
8494 // For each non-template constructor in the candidate set of inherited
8495 // constructors other than a constructor having no parameters or a
8496 // copy/move constructor having a single parameter, a constructor is
8497 // implicitly declared [...]
8498 if (Ctor->getNumParams() == 0)
8499 return 1;
8500 if (Ctor->isCopyOrMoveConstructor())
8501 return 2;
8502
8503 // Per discussion on core reflector, never inherit a constructor which
8504 // would become a default, copy, or move constructor of Derived either.
8505 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8506 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8507 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8508 }
8509
8510 /// Declare a single inheriting constructor, inheriting the specified
8511 /// constructor, with the given type.
8512 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8513 QualType DerivedType) {
8514 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8515
8516 // C++11 [class.inhctor]p3:
8517 // ... a constructor is implicitly declared with the same constructor
8518 // characteristics unless there is a user-declared constructor with
8519 // the same signature in the class where the using-declaration appears
8520 if (Entry.DeclaredInDerived)
8521 return;
8522
8523 // C++11 [class.inhctor]p7:
8524 // If two using-declarations declare inheriting constructors with the
8525 // same signature, the program is ill-formed
8526 if (Entry.DerivedCtor) {
8527 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8528 // Only diagnose this once per constructor.
8529 if (Entry.DerivedCtor->isInvalidDecl())
8530 return;
8531 Entry.DerivedCtor->setInvalidDecl();
8532
8533 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8534 SemaRef.Diag(BaseCtor->getLocation(),
8535 diag::note_using_decl_constructor_conflict_current_ctor);
8536 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8537 diag::note_using_decl_constructor_conflict_previous_ctor);
8538 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8539 diag::note_using_decl_constructor_conflict_previous_using);
8540 } else {
8541 // Core issue (no number): if the same inheriting constructor is
8542 // produced by multiple base class constructors from the same base
8543 // class, the inheriting constructor is defined as deleted.
8544 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8545 }
8546
8547 return;
8548 }
8549
8550 ASTContext &Context = SemaRef.Context;
8551 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8552 Context.getCanonicalType(Context.getRecordType(Derived)));
8553 DeclarationNameInfo NameInfo(Name, UsingLoc);
8554
8555 TemplateParameterList *TemplateParams = 0;
8556 if (const FunctionTemplateDecl *FTD =
8557 BaseCtor->getDescribedFunctionTemplate()) {
8558 TemplateParams = FTD->getTemplateParameters();
8559 // We're reusing template parameters from a different DeclContext. This
8560 // is questionable at best, but works out because the template depth in
8561 // both places is guaranteed to be 0.
8562 // FIXME: Rebuild the template parameters in the new context, and
8563 // transform the function type to refer to them.
8564 }
8565
8566 // Build type source info pointing at the using-declaration. This is
8567 // required by template instantiation.
8568 TypeSourceInfo *TInfo =
8569 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8570 FunctionProtoTypeLoc ProtoLoc =
8571 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8572
8573 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8574 Context, Derived, UsingLoc, NameInfo, DerivedType,
8575 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8576 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8577
8578 // Build an unevaluated exception specification for this constructor.
8579 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8580 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8581 EPI.ExceptionSpecType = EST_Unevaluated;
8582 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008583 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008584 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008585
8586 // Build the parameter declarations.
8587 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008588 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008589 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008590 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008591 ParmVarDecl *PD = ParmVarDecl::Create(
8592 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008593 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008594 PD->setScopeInfo(0, I);
8595 PD->setImplicit();
8596 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008597 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008598 }
8599
8600 // Set up the new constructor.
8601 DerivedCtor->setAccess(BaseCtor->getAccess());
8602 DerivedCtor->setParams(ParamDecls);
8603 DerivedCtor->setInheritedConstructor(BaseCtor);
8604 if (BaseCtor->isDeleted())
8605 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8606
8607 // If this is a constructor template, build the template declaration.
8608 if (TemplateParams) {
8609 FunctionTemplateDecl *DerivedTemplate =
8610 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8611 TemplateParams, DerivedCtor);
8612 DerivedTemplate->setAccess(BaseCtor->getAccess());
8613 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8614 Derived->addDecl(DerivedTemplate);
8615 } else {
8616 Derived->addDecl(DerivedCtor);
8617 }
8618
8619 Entry.BaseCtor = BaseCtor;
8620 Entry.DerivedCtor = DerivedCtor;
8621 }
8622
8623 Sema &SemaRef;
8624 CXXRecordDecl *Derived;
8625 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8626 MapType Map;
8627};
8628}
8629
8630void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8631 // Defer declaring the inheriting constructors until the class is
8632 // instantiated.
8633 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008634 return;
8635
Richard Smith185be182013-04-10 05:48:59 +00008636 // Find base classes from which we might inherit constructors.
8637 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008638 for (const auto &BaseIt : ClassDecl->bases())
8639 if (BaseIt.getInheritConstructors())
8640 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008641
Richard Smith185be182013-04-10 05:48:59 +00008642 // Go no further if we're not inheriting any constructors.
8643 if (InheritedBases.empty())
8644 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008645
Richard Smith185be182013-04-10 05:48:59 +00008646 // Declare the inherited constructors.
8647 InheritingConstructorInfo ICI(*this, ClassDecl);
8648 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8649 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008650}
8651
Richard Smithc2bc61b2013-03-18 21:12:30 +00008652void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8653 CXXConstructorDecl *Constructor) {
8654 CXXRecordDecl *ClassDecl = Constructor->getParent();
8655 assert(Constructor->getInheritedConstructor() &&
8656 !Constructor->doesThisDeclarationHaveABody() &&
8657 !Constructor->isDeleted());
8658
8659 SynthesizedFunctionScope Scope(*this, Constructor);
8660 DiagnosticErrorTrap Trap(Diags);
8661 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8662 Trap.hasErrorOccurred()) {
8663 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8664 << Context.getTagDeclType(ClassDecl);
8665 Constructor->setInvalidDecl();
8666 return;
8667 }
8668
8669 SourceLocation Loc = Constructor->getLocation();
8670 Constructor->setBody(new (Context) CompoundStmt(Loc));
8671
Eli Friedman276dd182013-09-05 00:02:25 +00008672 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008673 MarkVTableUsed(CurrentLocation, ClassDecl);
8674
8675 if (ASTMutationListener *L = getASTMutationListener()) {
8676 L->CompletedImplicitDefinition(Constructor);
8677 }
8678}
8679
8680
Alexis Huntf91729462011-05-12 22:46:25 +00008681Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008682Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8683 CXXRecordDecl *ClassDecl = MD->getParent();
8684
Douglas Gregorf1203042010-07-01 19:09:28 +00008685 // C++ [except.spec]p14:
8686 // An implicitly declared special member function (Clause 12) shall have
8687 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008688 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008689 if (ClassDecl->isInvalidDecl())
8690 return ExceptSpec;
8691
Douglas Gregorf1203042010-07-01 19:09:28 +00008692 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008693 for (const auto &B : ClassDecl->bases()) {
8694 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008695 continue;
8696
Aaron Ballman574705e2014-03-13 15:41:46 +00008697 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8698 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008699 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008700 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008701
Douglas Gregorf1203042010-07-01 19:09:28 +00008702 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008703 for (const auto &B : ClassDecl->vbases()) {
8704 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8705 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008706 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008707 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008708
Douglas Gregorf1203042010-07-01 19:09:28 +00008709 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008710 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008711 if (const RecordType *RecordTy
8712 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008713 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008714 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008715 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008716
Alexis Huntf91729462011-05-12 22:46:25 +00008717 return ExceptSpec;
8718}
8719
8720CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8721 // C++ [class.dtor]p2:
8722 // If a class has no user-declared destructor, a destructor is
8723 // declared implicitly. An implicitly-declared destructor is an
8724 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008725 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008726
Richard Smith8bf22e52012-11-29 01:34:07 +00008727 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8728 if (DSM.isAlreadyBeingDeclared())
8729 return 0;
8730
Douglas Gregor7454c562010-07-02 20:37:36 +00008731 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008732 CanQualType ClassType
8733 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008734 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008735 DeclarationName Name
8736 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008737 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008738 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008739 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8740 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008741 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008742 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008743 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008744 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008745
8746 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008747 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008748 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008749
Richard Smith6b02d462012-12-08 08:32:28 +00008750 AddOverriddenMethods(ClassDecl, Destructor);
8751
8752 // We don't need to use SpecialMemberIsTrivial here; triviality for
8753 // destructors is easy to compute.
8754 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8755
8756 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008757 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008758
Douglas Gregor7454c562010-07-02 20:37:36 +00008759 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008760 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008761
Douglas Gregor7454c562010-07-02 20:37:36 +00008762 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008763 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008764 PushOnScopeChains(Destructor, S, false);
8765 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008766
Douglas Gregorf1203042010-07-01 19:09:28 +00008767 return Destructor;
8768}
8769
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008770void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008771 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008772 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008773 !Destructor->doesThisDeclarationHaveABody() &&
8774 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008775 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008776 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008777 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008778
Douglas Gregor54818f02010-05-12 16:39:35 +00008779 if (Destructor->isInvalidDecl())
8780 return;
8781
Eli Friedmaneaf34142012-10-18 20:14:08 +00008782 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008783
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008784 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008785 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8786 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008787
Douglas Gregor54818f02010-05-12 16:39:35 +00008788 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008789 Diag(CurrentLocation, diag::note_member_synthesized_at)
8790 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8791
8792 Destructor->setInvalidDecl();
8793 return;
8794 }
8795
Douglas Gregor73193272010-09-20 16:48:21 +00008796 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008797 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008798 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008799 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008800
8801 if (ASTMutationListener *L = getASTMutationListener()) {
8802 L->CompletedImplicitDefinition(Destructor);
8803 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008804}
8805
Richard Smith84973e52012-04-21 18:42:51 +00008806/// \brief Perform any semantic analysis which needs to be delayed until all
8807/// pending class member declarations have been parsed.
8808void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008809 // If the context is an invalid C++ class, just suppress these checks.
8810 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8811 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008812 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008813 DelayedDestructorExceptionSpecChecks.clear();
8814 return;
8815 }
8816 }
Richard Smith84973e52012-04-21 18:42:51 +00008817}
8818
Richard Smithd3b5c9082012-07-27 04:22:15 +00008819void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8820 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008821 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008822 "adjusting dtor exception specs was introduced in c++11");
8823
Sebastian Redl623ea822011-05-19 05:13:44 +00008824 // C++11 [class.dtor]p3:
8825 // A declaration of a destructor that does not have an exception-
8826 // specification is implicitly considered to have the same exception-
8827 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008828 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008829 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008830 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008831 return;
8832
Chandler Carruth9a797572011-09-20 04:55:26 +00008833 // Replace the destructor's type, building off the existing one. Fortunately,
8834 // the only thing of interest in the destructor type is its extended info.
8835 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008836 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8837 EPI.ExceptionSpecType = EST_Unevaluated;
8838 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008839 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008840
Sebastian Redl623ea822011-05-19 05:13:44 +00008841 // FIXME: If the destructor has a body that could throw, and the newly created
8842 // spec doesn't allow exceptions, we should emit a warning, because this
8843 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008844 // However, we don't have a body or an exception specification yet, so it
8845 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008846}
8847
Pavel Labath58934982013-08-30 08:52:28 +00008848namespace {
8849/// \brief An abstract base class for all helper classes used in building the
8850// copy/move operators. These classes serve as factory functions and help us
8851// avoid using the same Expr* in the AST twice.
8852class ExprBuilder {
8853 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8854 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8855
8856protected:
8857 static Expr *assertNotNull(Expr *E) {
8858 assert(E && "Expression construction must not fail.");
8859 return E;
8860 }
8861
8862public:
8863 ExprBuilder() {}
8864 virtual ~ExprBuilder() {}
8865
8866 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8867};
8868
8869class RefBuilder: public ExprBuilder {
8870 VarDecl *Var;
8871 QualType VarType;
8872
8873public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008874 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008875 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8876 }
8877
8878 RefBuilder(VarDecl *Var, QualType VarType)
8879 : Var(Var), VarType(VarType) {}
8880};
8881
8882class ThisBuilder: public ExprBuilder {
8883public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008884 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008885 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8886 }
8887};
8888
8889class CastBuilder: public ExprBuilder {
8890 const ExprBuilder &Builder;
8891 QualType Type;
8892 ExprValueKind Kind;
8893 const CXXCastPath &Path;
8894
8895public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008896 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008897 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8898 CK_UncheckedDerivedToBase, Kind,
8899 &Path).take());
8900 }
8901
8902 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8903 const CXXCastPath &Path)
8904 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8905};
8906
8907class DerefBuilder: public ExprBuilder {
8908 const ExprBuilder &Builder;
8909
8910public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008911 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008912 return assertNotNull(
8913 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8914 }
8915
8916 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8917};
8918
8919class MemberBuilder: public ExprBuilder {
8920 const ExprBuilder &Builder;
8921 QualType Type;
8922 CXXScopeSpec SS;
8923 bool IsArrow;
8924 LookupResult &MemberLookup;
8925
8926public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008927 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008928 return assertNotNull(S.BuildMemberReferenceExpr(
8929 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8930 MemberLookup, 0).take());
8931 }
8932
8933 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8934 LookupResult &MemberLookup)
8935 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8936 MemberLookup(MemberLookup) {}
8937};
8938
8939class MoveCastBuilder: public ExprBuilder {
8940 const ExprBuilder &Builder;
8941
8942public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008943 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008944 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8945 }
8946
8947 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8948};
8949
8950class LvalueConvBuilder: public ExprBuilder {
8951 const ExprBuilder &Builder;
8952
8953public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008954 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008955 return assertNotNull(
8956 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8957 }
8958
8959 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8960};
8961
8962class SubscriptBuilder: public ExprBuilder {
8963 const ExprBuilder &Base;
8964 const ExprBuilder &Index;
8965
8966public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008967 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008968 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8969 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8970 }
8971
8972 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8973 : Base(Base), Index(Index) {}
8974};
8975
8976} // end anonymous namespace
8977
Richard Smith41ae3282012-11-14 00:50:40 +00008978/// When generating a defaulted copy or move assignment operator, if a field
8979/// should be copied with __builtin_memcpy rather than via explicit assignments,
8980/// do so. This optimization only applies for arrays of scalars, and for arrays
8981/// of class type where the selected copy/move-assignment operator is trivial.
8982static StmtResult
8983buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008984 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008985 // Compute the size of the memory buffer to be copied.
8986 QualType SizeType = S.Context.getSizeType();
8987 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8988 S.Context.getTypeSizeInChars(T).getQuantity());
8989
8990 // Take the address of the field references for "from" and "to". We
8991 // directly construct UnaryOperators here because semantic analysis
8992 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008993 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008994 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8995 S.Context.getPointerType(From->getType()),
8996 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008997 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008998 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8999 S.Context.getPointerType(To->getType()),
9000 VK_RValue, OK_Ordinary, Loc);
9001
9002 const Type *E = T->getBaseElementTypeUnsafe();
9003 bool NeedsCollectableMemCpy =
9004 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9005
9006 // Create a reference to the __builtin_objc_memmove_collectable function
9007 StringRef MemCpyName = NeedsCollectableMemCpy ?
9008 "__builtin_objc_memmove_collectable" :
9009 "__builtin_memcpy";
9010 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9011 Sema::LookupOrdinaryName);
9012 S.LookupName(R, S.TUScope, true);
9013
9014 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9015 if (!MemCpy)
9016 // Something went horribly wrong earlier, and we will have complained
9017 // about it.
9018 return StmtError();
9019
9020 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9021 VK_RValue, Loc, 0);
9022 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9023
9024 Expr *CallArgs[] = {
9025 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9026 };
9027 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
9028 Loc, CallArgs, Loc);
9029
9030 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9031 return S.Owned(Call.takeAs<Stmt>());
9032}
9033
Sebastian Redl22653ba2011-08-30 19:58:05 +00009034/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009035/// \c To.
9036///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009037/// This routine is used to copy/move the members of a class with an
9038/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009039/// copied are arrays, this routine builds for loops to copy them.
9040///
9041/// \param S The Sema object used for type-checking.
9042///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009043/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009044///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009045/// \param T The type of the expressions being copied/moved. Both expressions
9046/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009047///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009048/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009049///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009050/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009051///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009052/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009053/// Otherwise, it's a non-static member subobject.
9054///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009055/// \param Copying Whether we're copying or moving.
9056///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009057/// \param Depth Internal parameter recording the depth of the recursion.
9058///
Richard Smith41ae3282012-11-14 00:50:40 +00009059/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9060/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009061static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009062buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009063 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009064 bool CopyingBaseSubobject, bool Copying,
9065 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009066 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009067 // Each subobject is assigned in the manner appropriate to its type:
9068 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009069 // - if the subobject is of class type, as if by a call to operator= with
9070 // the subobject as the object expression and the corresponding
9071 // subobject of x as a single function argument (as if by explicit
9072 // qualification; that is, ignoring any possible virtual overriding
9073 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009074 //
9075 // C++03 [class.copy]p13:
9076 // - if the subobject is of class type, the copy assignment operator for
9077 // the class is used (as if by explicit qualification; that is,
9078 // ignoring any possible virtual overriding functions in more derived
9079 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009080 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9081 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009082
Douglas Gregorb139cd52010-05-01 20:49:11 +00009083 // Look for operator=.
9084 DeclarationName Name
9085 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9086 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9087 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009088
Richard Smith52c0b582012-11-13 00:54:12 +00009089 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9090 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009091 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009092 LookupResult::Filter F = OpLookup.makeFilter();
9093 while (F.hasNext()) {
9094 NamedDecl *D = F.next();
9095 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9096 if (Method->isCopyAssignmentOperator() ||
9097 (!Copying && Method->isMoveAssignmentOperator()))
9098 continue;
9099
9100 F.erase();
9101 }
9102 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009103 }
Richard Smith52c0b582012-11-13 00:54:12 +00009104
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009105 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009106 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009107 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009108 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009109 // ambiguities), we need to cast "this" to that subobject type; to
9110 // ensure that we don't go through the virtual call mechanism, we need
9111 // to qualify the operator= name with the base class (see below). However,
9112 // this means that if the base class has a protected copy assignment
9113 // operator, the protected member access check will fail. So, we
9114 // rewrite "protected" access to "public" access in this case, since we
9115 // know by construction that we're calling from a derived class.
9116 if (CopyingBaseSubobject) {
9117 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9118 L != LEnd; ++L) {
9119 if (L.getAccess() == AS_protected)
9120 L.setAccess(AS_public);
9121 }
9122 }
Richard Smith52c0b582012-11-13 00:54:12 +00009123
Douglas Gregorb139cd52010-05-01 20:49:11 +00009124 // Create the nested-name-specifier that will be used to qualify the
9125 // reference to operator=; this is required to suppress the virtual
9126 // call mechanism.
9127 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009128 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009129 SS.MakeTrivial(S.Context,
9130 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009131 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009132 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009133
Douglas Gregorb139cd52010-05-01 20:49:11 +00009134 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009135 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009136 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9137 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009138 /*FirstQualifierInScope=*/0,
9139 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009140 /*TemplateArgs=*/0,
9141 /*SuppressQualifierCheck=*/true);
9142 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009143 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009144
Douglas Gregorb139cd52010-05-01 20:49:11 +00009145 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009146
Pavel Labath58934982013-08-30 08:52:28 +00009147 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009148 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009149 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009150 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009151 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009152 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009153
Richard Smith41ae3282012-11-14 00:50:40 +00009154 // If we built a call to a trivial 'operator=' while copying an array,
9155 // bail out. We'll replace the whole shebang with a memcpy.
9156 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9157 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9158 return StmtResult((Stmt*)0);
9159
Richard Smith52c0b582012-11-13 00:54:12 +00009160 // Convert to an expression-statement, and clean up any produced
9161 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009162 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009163 }
John McCallab8c2732010-03-16 06:11:48 +00009164
Richard Smith52c0b582012-11-13 00:54:12 +00009165 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009166 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009167 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009168 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009169 ExprResult Assignment = S.CreateBuiltinBinOp(
9170 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009171 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009172 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009173 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009174 }
Richard Smith52c0b582012-11-13 00:54:12 +00009175
9176 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009177 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009178
Douglas Gregorb139cd52010-05-01 20:49:11 +00009179 // Construct a loop over the array bounds, e.g.,
9180 //
9181 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9182 //
9183 // that will copy each of the array elements.
9184 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009185
Douglas Gregorb139cd52010-05-01 20:49:11 +00009186 // Create the iteration variable.
9187 IdentifierInfo *IterationVarName = 0;
9188 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009189 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009190 llvm::raw_svector_ostream OS(Str);
9191 OS << "__i" << Depth;
9192 IterationVarName = &S.Context.Idents.get(OS.str());
9193 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009194 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009195 IterationVarName, SizeType,
9196 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009197 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009198
Douglas Gregorb139cd52010-05-01 20:49:11 +00009199 // Initialize the iteration variable to zero.
9200 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009201 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009202
Pavel Labath58934982013-08-30 08:52:28 +00009203 // Creates a reference to the iteration variable.
9204 RefBuilder IterationVarRef(IterationVar, SizeType);
9205 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009206
Douglas Gregorb139cd52010-05-01 20:49:11 +00009207 // Create the DeclStmt that holds the iteration variable.
9208 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009209
Douglas Gregorb139cd52010-05-01 20:49:11 +00009210 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009211 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9212 MoveCastBuilder FromIndexMove(FromIndexCopy);
9213 const ExprBuilder *FromIndex;
9214 if (Copying)
9215 FromIndex = &FromIndexCopy;
9216 else
9217 FromIndex = &FromIndexMove;
9218
9219 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009220
9221 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009222 StmtResult Copy =
9223 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009224 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009225 Copying, Depth + 1);
9226 // Bail out if copying fails or if we determined that we should use memcpy.
9227 if (Copy.isInvalid() || !Copy.get())
9228 return Copy;
9229
9230 // Create the comparison against the array bound.
9231 llvm::APInt Upper
9232 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9233 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009234 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009235 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9236 BO_NE, S.Context.BoolTy,
9237 VK_RValue, OK_Ordinary, Loc, false);
9238
9239 // Create the pre-increment of the iteration variable.
9240 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009241 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9242 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009243
Douglas Gregorb139cd52010-05-01 20:49:11 +00009244 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009245 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009246 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009247 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009248 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009249}
9250
Richard Smith41ae3282012-11-14 00:50:40 +00009251static StmtResult
9252buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009253 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009254 bool CopyingBaseSubobject, bool Copying) {
9255 // Maybe we should use a memcpy?
9256 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9257 T.isTriviallyCopyableType(S.Context))
9258 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9259
9260 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9261 CopyingBaseSubobject,
9262 Copying, 0));
9263
9264 // If we ended up picking a trivial assignment operator for an array of a
9265 // non-trivially-copyable class type, just emit a memcpy.
9266 if (!Result.isInvalid() && !Result.get())
9267 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9268
9269 return Result;
9270}
9271
Richard Smithd3b5c9082012-07-27 04:22:15 +00009272Sema::ImplicitExceptionSpecification
9273Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9274 CXXRecordDecl *ClassDecl = MD->getParent();
9275
9276 ImplicitExceptionSpecification ExceptSpec(*this);
9277 if (ClassDecl->isInvalidDecl())
9278 return ExceptSpec;
9279
9280 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009281 assert(T->getNumParams() == 1 && "not a copy assignment op");
9282 unsigned ArgQuals =
9283 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009284
Douglas Gregor68e11362010-07-01 17:48:08 +00009285 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009286 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009287 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009288
9289 // It is unspecified whether or not an implicit copy assignment operator
9290 // attempts to deduplicate calls to assignment operators of virtual bases are
9291 // made. As such, this exception specification is effectively unspecified.
9292 // Based on a similar decision made for constness in C++0x, we're erring on
9293 // the side of assuming such calls to be made regardless of whether they
9294 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009295 for (const auto &Base : ClassDecl->bases()) {
9296 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009297 continue;
9298
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009299 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009300 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009301 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9302 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009303 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009304 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009305
Aaron Ballman445a9392014-03-13 16:15:17 +00009306 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009307 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009308 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009309 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9310 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009311 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009312 }
9313
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009314 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009315 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009316 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9317 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009318 LookupCopyingAssignment(FieldClassDecl,
9319 ArgQuals | FieldType.getCVRQualifiers(),
9320 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009321 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009322 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009323 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009324
Richard Smithd3b5c9082012-07-27 04:22:15 +00009325 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009326}
9327
9328CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9329 // Note: The following rules are largely analoguous to the copy
9330 // constructor rules. Note that virtual bases are not taken into account
9331 // for determining the argument type of the operator. Note also that
9332 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009333 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009334
Richard Smith8bf22e52012-11-29 01:34:07 +00009335 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9336 if (DSM.isAlreadyBeingDeclared())
9337 return 0;
9338
Alexis Hunt119f3652011-05-14 05:23:20 +00009339 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9340 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009341 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9342 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009343 ArgType = ArgType.withConst();
9344 ArgType = Context.getLValueReferenceType(ArgType);
9345
Richard Smith99005e62013-05-07 03:19:20 +00009346 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9347 CXXCopyAssignment,
9348 Const);
9349
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009350 // An implicitly-declared copy assignment operator is an inline public
9351 // member of its class.
9352 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009353 SourceLocation ClassLoc = ClassDecl->getLocation();
9354 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009355 CXXMethodDecl *CopyAssignment =
9356 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9357 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9358 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009359 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009360 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009361 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009362
9363 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009364 FunctionProtoType::ExtProtoInfo EPI =
9365 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009366 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009367
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009368 // Add the parameter to the operator.
9369 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009370 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009371 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009372 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009373 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009374
Richard Smith6b02d462012-12-08 08:32:28 +00009375 AddOverriddenMethods(ClassDecl, CopyAssignment);
9376
9377 CopyAssignment->setTrivial(
9378 ClassDecl->needsOverloadResolutionForCopyAssignment()
9379 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9380 : ClassDecl->hasTrivialCopyAssignment());
9381
Richard Smith852265f2012-03-30 20:53:28 +00009382 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009383 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009384
Richard Smith6b02d462012-12-08 08:32:28 +00009385 // Note that we have added this copy-assignment operator.
9386 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9387
9388 if (Scope *S = getScopeForContext(ClassDecl))
9389 PushOnScopeChains(CopyAssignment, S, false);
9390 ClassDecl->addDecl(CopyAssignment);
9391
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009392 return CopyAssignment;
9393}
9394
Richard Smithd577fbb2013-06-13 03:23:42 +00009395/// Diagnose an implicit copy operation for a class which is odr-used, but
9396/// which is deprecated because the class has a user-declared copy constructor,
9397/// copy assignment operator, or destructor.
9398static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9399 SourceLocation UseLoc) {
9400 assert(CopyOp->isImplicit());
9401
9402 CXXRecordDecl *RD = CopyOp->getParent();
9403 CXXMethodDecl *UserDeclaredOperation = 0;
9404
9405 // In Microsoft mode, assignment operations don't affect constructors and
9406 // vice versa.
9407 if (RD->hasUserDeclaredDestructor()) {
9408 UserDeclaredOperation = RD->getDestructor();
9409 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9410 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009411 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009412 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009413 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009414 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009415 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009416 break;
9417 }
9418 }
9419 assert(UserDeclaredOperation);
9420 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9421 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009422 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009423 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009424 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009425 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009426 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009427 break;
9428 }
9429 }
9430 assert(UserDeclaredOperation);
9431 }
9432
9433 if (UserDeclaredOperation) {
9434 S.Diag(UserDeclaredOperation->getLocation(),
9435 diag::warn_deprecated_copy_operation)
9436 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9437 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9438 S.Diag(UseLoc, diag::note_member_synthesized_at)
9439 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9440 : Sema::CXXCopyAssignment)
9441 << RD;
9442 }
9443}
9444
Douglas Gregorb139cd52010-05-01 20:49:11 +00009445void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9446 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009447 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009448 CopyAssignOperator->isOverloadedOperator() &&
9449 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009450 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9451 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009452 "DefineImplicitCopyAssignment called for wrong function");
9453
9454 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9455
9456 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9457 CopyAssignOperator->setInvalidDecl();
9458 return;
9459 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009460
9461 // C++11 [class.copy]p18:
9462 // The [definition of an implicitly declared copy assignment operator] is
9463 // deprecated if the class has a user-declared copy constructor or a
9464 // user-declared destructor.
9465 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9466 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9467
Eli Friedman276dd182013-09-05 00:02:25 +00009468 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009469
Eli Friedmaneaf34142012-10-18 20:14:08 +00009470 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009471 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009472
9473 // C++0x [class.copy]p30:
9474 // The implicitly-defined or explicitly-defaulted copy assignment operator
9475 // for a non-union class X performs memberwise copy assignment of its
9476 // subobjects. The direct base classes of X are assigned first, in the
9477 // order of their declaration in the base-specifier-list, and then the
9478 // immediate non-static data members of X are assigned, in the order in
9479 // which they were declared in the class definition.
9480
9481 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009482 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009483
9484 // The parameter for the "other" object, which we are copying from.
9485 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9486 Qualifiers OtherQuals = Other->getType().getQualifiers();
9487 QualType OtherRefType = Other->getType();
9488 if (const LValueReferenceType *OtherRef
9489 = OtherRefType->getAs<LValueReferenceType>()) {
9490 OtherRefType = OtherRef->getPointeeType();
9491 OtherQuals = OtherRefType.getQualifiers();
9492 }
9493
9494 // Our location for everything implicitly-generated.
9495 SourceLocation Loc = CopyAssignOperator->getLocation();
9496
Pavel Labath58934982013-08-30 08:52:28 +00009497 // Builds a DeclRefExpr for the "other" object.
9498 RefBuilder OtherRef(Other, OtherRefType);
9499
9500 // Builds the "this" pointer.
9501 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009502
9503 // Assign base classes.
9504 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009505 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009506 // Form the assignment:
9507 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009508 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009509 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009510 Invalid = true;
9511 continue;
9512 }
9513
John McCallcf142162010-08-07 06:22:56 +00009514 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009515 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009516
Douglas Gregorb139cd52010-05-01 20:49:11 +00009517 // Construct the "from" expression, which is an implicit cast to the
9518 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009519 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9520 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009521
9522 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009523 DerefBuilder DerefThis(This);
9524 CastBuilder To(DerefThis,
9525 Context.getCVRQualifiedType(
9526 BaseType, CopyAssignOperator->getTypeQualifiers()),
9527 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009528
9529 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009530 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009531 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009532 /*CopyingBaseSubobject=*/true,
9533 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009534 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009535 Diag(CurrentLocation, diag::note_member_synthesized_at)
9536 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9537 CopyAssignOperator->setInvalidDecl();
9538 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009539 }
9540
9541 // Success! Record the copy.
9542 Statements.push_back(Copy.takeAs<Expr>());
9543 }
9544
Douglas Gregorb139cd52010-05-01 20:49:11 +00009545 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009546 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009547 if (Field->isUnnamedBitfield())
9548 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009549
9550 if (Field->isInvalidDecl()) {
9551 Invalid = true;
9552 continue;
9553 }
9554
Douglas Gregorb139cd52010-05-01 20:49:11 +00009555 // Check for members of reference type; we can't copy those.
9556 if (Field->getType()->isReferenceType()) {
9557 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9558 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9559 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009560 Diag(CurrentLocation, diag::note_member_synthesized_at)
9561 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009562 Invalid = true;
9563 continue;
9564 }
9565
9566 // Check for members of const-qualified, non-class type.
9567 QualType BaseType = Context.getBaseElementType(Field->getType());
9568 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9569 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9570 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9571 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009572 Diag(CurrentLocation, diag::note_member_synthesized_at)
9573 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009574 Invalid = true;
9575 continue;
9576 }
John McCall1b1a1db2011-06-17 00:18:42 +00009577
9578 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009579 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9580 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009581
9582 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009583 if (FieldType->isIncompleteArrayType()) {
9584 assert(ClassDecl->hasFlexibleArrayMember() &&
9585 "Incomplete array type is not valid");
9586 continue;
9587 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009588
9589 // Build references to the field in the object we're copying from and to.
9590 CXXScopeSpec SS; // Intentionally empty
9591 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9592 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009593 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009594 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009595
9596 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9597
9598 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009599
Douglas Gregorb139cd52010-05-01 20:49:11 +00009600 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009601 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009602 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009603 /*CopyingBaseSubobject=*/false,
9604 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009605 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009606 Diag(CurrentLocation, diag::note_member_synthesized_at)
9607 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9608 CopyAssignOperator->setInvalidDecl();
9609 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009610 }
9611
9612 // Success! Record the copy.
9613 Statements.push_back(Copy.takeAs<Stmt>());
9614 }
9615
9616 if (!Invalid) {
9617 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009618 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009619
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009620 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009621 if (Return.isInvalid())
9622 Invalid = true;
9623 else {
9624 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009625
9626 if (Trap.hasErrorOccurred()) {
9627 Diag(CurrentLocation, diag::note_member_synthesized_at)
9628 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9629 Invalid = true;
9630 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009631 }
9632 }
9633
9634 if (Invalid) {
9635 CopyAssignOperator->setInvalidDecl();
9636 return;
9637 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009638
9639 StmtResult Body;
9640 {
9641 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009642 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009643 /*isStmtExpr=*/false);
9644 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9645 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009646 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009647
9648 if (ASTMutationListener *L = getASTMutationListener()) {
9649 L->CompletedImplicitDefinition(CopyAssignOperator);
9650 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009651}
9652
Sebastian Redl22653ba2011-08-30 19:58:05 +00009653Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009654Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9655 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009656
Richard Smithd3b5c9082012-07-27 04:22:15 +00009657 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009658 if (ClassDecl->isInvalidDecl())
9659 return ExceptSpec;
9660
9661 // C++0x [except.spec]p14:
9662 // An implicitly declared special member function (Clause 12) shall have an
9663 // exception-specification. [...]
9664
9665 // It is unspecified whether or not an implicit move assignment operator
9666 // attempts to deduplicate calls to assignment operators of virtual bases are
9667 // made. As such, this exception specification is effectively unspecified.
9668 // Based on a similar decision made for constness in C++0x, we're erring on
9669 // the side of assuming such calls to be made regardless of whether they
9670 // actually happen.
9671 // Note that a move constructor is not implicitly declared when there are
9672 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009673 for (const auto &Base : ClassDecl->bases()) {
9674 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009675 continue;
9676
9677 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009678 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009679 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009680 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009681 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009682 }
9683
Aaron Ballman445a9392014-03-13 16:15:17 +00009684 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009685 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009686 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009687 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009688 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009689 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009690 }
9691
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009692 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009693 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009694 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009695 if (CXXMethodDecl *MoveAssign =
9696 LookupMovingAssignment(FieldClassDecl,
9697 FieldType.getCVRQualifiers(),
9698 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009699 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009700 }
9701 }
9702
9703 return ExceptSpec;
9704}
9705
9706CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009707 assert(ClassDecl->needsImplicitMoveAssignment());
9708
Richard Smith8bf22e52012-11-29 01:34:07 +00009709 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9710 if (DSM.isAlreadyBeingDeclared())
9711 return 0;
9712
Sebastian Redl22653ba2011-08-30 19:58:05 +00009713 // Note: The following rules are largely analoguous to the move
9714 // constructor rules.
9715
Sebastian Redl22653ba2011-08-30 19:58:05 +00009716 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9717 QualType RetType = Context.getLValueReferenceType(ArgType);
9718 ArgType = Context.getRValueReferenceType(ArgType);
9719
Richard Smith99005e62013-05-07 03:19:20 +00009720 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9721 CXXMoveAssignment,
9722 false);
9723
Sebastian Redl22653ba2011-08-30 19:58:05 +00009724 // An implicitly-declared move assignment operator is an inline public
9725 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009726 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9727 SourceLocation ClassLoc = ClassDecl->getLocation();
9728 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009729 CXXMethodDecl *MoveAssignment =
9730 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9731 /*TInfo=*/0, /*StorageClass=*/SC_None,
9732 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009733 MoveAssignment->setAccess(AS_public);
9734 MoveAssignment->setDefaulted();
9735 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009736
Richard Smithd3b5c9082012-07-27 04:22:15 +00009737 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009738 FunctionProtoType::ExtProtoInfo EPI =
9739 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009740 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009741
Sebastian Redl22653ba2011-08-30 19:58:05 +00009742 // Add the parameter to the operator.
9743 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9744 ClassLoc, ClassLoc, /*Id=*/0,
9745 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009746 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009747 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009748
Richard Smith6b02d462012-12-08 08:32:28 +00009749 AddOverriddenMethods(ClassDecl, MoveAssignment);
9750
9751 MoveAssignment->setTrivial(
9752 ClassDecl->needsOverloadResolutionForMoveAssignment()
9753 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9754 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009755
Richard Smithd951a1d2012-02-18 02:02:13 +00009756 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009757 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9758 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009759 }
9760
Richard Smith6b02d462012-12-08 08:32:28 +00009761 // Note that we have added this copy-assignment operator.
9762 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9763
Sebastian Redl22653ba2011-08-30 19:58:05 +00009764 if (Scope *S = getScopeForContext(ClassDecl))
9765 PushOnScopeChains(MoveAssignment, S, false);
9766 ClassDecl->addDecl(MoveAssignment);
9767
Sebastian Redl22653ba2011-08-30 19:58:05 +00009768 return MoveAssignment;
9769}
9770
Richard Smithb2504bd2013-11-04 04:26:14 +00009771/// Check if we're implicitly defining a move assignment operator for a class
9772/// with virtual bases. Such a move assignment might move-assign the virtual
9773/// base multiple times.
9774static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9775 SourceLocation CurrentLocation) {
9776 assert(!Class->isDependentContext() && "should not define dependent move");
9777
9778 // Only a virtual base could get implicitly move-assigned multiple times.
9779 // Only a non-trivial move assignment can observe this. We only want to
9780 // diagnose if we implicitly define an assignment operator that assigns
9781 // two base classes, both of which move-assign the same virtual base.
9782 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9783 Class->getNumBases() < 2)
9784 return;
9785
9786 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9787 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9788 VBaseMap VBases;
9789
Aaron Ballman574705e2014-03-13 15:41:46 +00009790 for (auto &BI : Class->bases()) {
9791 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009792 while (!Worklist.empty()) {
9793 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9794 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9795
9796 // If the base has no non-trivial move assignment operators,
9797 // we don't care about moves from it.
9798 if (!Base->hasNonTrivialMoveAssignment())
9799 continue;
9800
9801 // If there's nothing virtual here, skip it.
9802 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9803 continue;
9804
9805 // If we're not actually going to call a move assignment for this base,
9806 // or the selected move assignment is trivial, skip it.
9807 Sema::SpecialMemberOverloadResult *SMOR =
9808 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9809 /*ConstArg*/false, /*VolatileArg*/false,
9810 /*RValueThis*/true, /*ConstThis*/false,
9811 /*VolatileThis*/false);
9812 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9813 !SMOR->getMethod()->isMoveAssignmentOperator())
9814 continue;
9815
9816 if (BaseSpec->isVirtual()) {
9817 // We're going to move-assign this virtual base, and its move
9818 // assignment operator is not trivial. If this can happen for
9819 // multiple distinct direct bases of Class, diagnose it. (If it
9820 // only happens in one base, we'll diagnose it when synthesizing
9821 // that base class's move assignment operator.)
9822 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +00009823 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +00009824 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +00009825 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009826 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9827 << Class << Base;
9828 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9829 << (Base->getCanonicalDecl() ==
9830 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9831 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +00009832 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +00009833 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +00009834 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9835 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +00009836
9837 // Only diagnose each vbase once.
9838 Existing = 0;
9839 }
9840 } else {
9841 // Only walk over bases that have defaulted move assignment operators.
9842 // We assume that any user-provided move assignment operator handles
9843 // the multiple-moves-of-vbase case itself somehow.
9844 if (!SMOR->getMethod()->isDefaulted())
9845 continue;
9846
9847 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +00009848 for (auto &BI : Base->bases())
9849 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009850 }
9851 }
9852 }
9853}
9854
Sebastian Redl22653ba2011-08-30 19:58:05 +00009855void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9856 CXXMethodDecl *MoveAssignOperator) {
9857 assert((MoveAssignOperator->isDefaulted() &&
9858 MoveAssignOperator->isOverloadedOperator() &&
9859 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009860 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9861 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009862 "DefineImplicitMoveAssignment called for wrong function");
9863
9864 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9865
9866 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9867 MoveAssignOperator->setInvalidDecl();
9868 return;
9869 }
9870
Eli Friedman276dd182013-09-05 00:02:25 +00009871 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009872
Eli Friedmaneaf34142012-10-18 20:14:08 +00009873 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009874 DiagnosticErrorTrap Trap(Diags);
9875
9876 // C++0x [class.copy]p28:
9877 // The implicitly-defined or move assignment operator for a non-union class
9878 // X performs memberwise move assignment of its subobjects. The direct base
9879 // classes of X are assigned first, in the order of their declaration in the
9880 // base-specifier-list, and then the immediate non-static data members of X
9881 // are assigned, in the order in which they were declared in the class
9882 // definition.
9883
Richard Smithb2504bd2013-11-04 04:26:14 +00009884 // Issue a warning if our implicit move assignment operator will move
9885 // from a virtual base more than once.
9886 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009887
Sebastian Redl22653ba2011-08-30 19:58:05 +00009888 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009889 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009890
9891 // The parameter for the "other" object, which we are move from.
9892 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9893 QualType OtherRefType = Other->getType()->
9894 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009895 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009896 "Bad argument type of defaulted move assignment");
9897
9898 // Our location for everything implicitly-generated.
9899 SourceLocation Loc = MoveAssignOperator->getLocation();
9900
Pavel Labath58934982013-08-30 08:52:28 +00009901 // Builds a reference to the "other" object.
9902 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009903 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009904 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009905
Pavel Labath58934982013-08-30 08:52:28 +00009906 // Builds the "this" pointer.
9907 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009908
Sebastian Redl22653ba2011-08-30 19:58:05 +00009909 // Assign base classes.
9910 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009911 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009912 // C++11 [class.copy]p28:
9913 // It is unspecified whether subobjects representing virtual base classes
9914 // are assigned more than once by the implicitly-defined copy assignment
9915 // operator.
9916 // FIXME: Do not assign to a vbase that will be assigned by some other base
9917 // class. For a move-assignment, this can result in the vbase being moved
9918 // multiple times.
9919
Sebastian Redl22653ba2011-08-30 19:58:05 +00009920 // Form the assignment:
9921 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009922 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009923 if (!BaseType->isRecordType()) {
9924 Invalid = true;
9925 continue;
9926 }
9927
9928 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009929 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009930
9931 // Construct the "from" expression, which is an implicit cast to the
9932 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009933 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009934
9935 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009936 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009937
9938 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009939 CastBuilder To(DerefThis,
9940 Context.getCVRQualifiedType(
9941 BaseType, MoveAssignOperator->getTypeQualifiers()),
9942 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009943
9944 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009945 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009946 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009947 /*CopyingBaseSubobject=*/true,
9948 /*Copying=*/false);
9949 if (Move.isInvalid()) {
9950 Diag(CurrentLocation, diag::note_member_synthesized_at)
9951 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9952 MoveAssignOperator->setInvalidDecl();
9953 return;
9954 }
9955
9956 // Success! Record the move.
9957 Statements.push_back(Move.takeAs<Expr>());
9958 }
9959
Sebastian Redl22653ba2011-08-30 19:58:05 +00009960 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009961 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009962 if (Field->isUnnamedBitfield())
9963 continue;
9964
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009965 if (Field->isInvalidDecl()) {
9966 Invalid = true;
9967 continue;
9968 }
9969
Sebastian Redl22653ba2011-08-30 19:58:05 +00009970 // Check for members of reference type; we can't move those.
9971 if (Field->getType()->isReferenceType()) {
9972 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9973 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9974 Diag(Field->getLocation(), diag::note_declared_at);
9975 Diag(CurrentLocation, diag::note_member_synthesized_at)
9976 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9977 Invalid = true;
9978 continue;
9979 }
9980
9981 // Check for members of const-qualified, non-class type.
9982 QualType BaseType = Context.getBaseElementType(Field->getType());
9983 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9984 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9985 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9986 Diag(Field->getLocation(), diag::note_declared_at);
9987 Diag(CurrentLocation, diag::note_member_synthesized_at)
9988 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9989 Invalid = true;
9990 continue;
9991 }
9992
9993 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009994 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9995 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009996
9997 QualType FieldType = Field->getType().getNonReferenceType();
9998 if (FieldType->isIncompleteArrayType()) {
9999 assert(ClassDecl->hasFlexibleArrayMember() &&
10000 "Incomplete array type is not valid");
10001 continue;
10002 }
10003
10004 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010005 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10006 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010007 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010008 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010009 MemberBuilder From(MoveOther, OtherRefType,
10010 /*IsArrow=*/false, MemberLookup);
10011 MemberBuilder To(This, getCurrentThisType(),
10012 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010013
Pavel Labath58934982013-08-30 08:52:28 +000010014 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010015 "Member reference with rvalue base must be rvalue except for reference "
10016 "members, which aren't allowed for move assignment.");
10017
Sebastian Redl22653ba2011-08-30 19:58:05 +000010018 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010019 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010020 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010021 /*CopyingBaseSubobject=*/false,
10022 /*Copying=*/false);
10023 if (Move.isInvalid()) {
10024 Diag(CurrentLocation, diag::note_member_synthesized_at)
10025 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10026 MoveAssignOperator->setInvalidDecl();
10027 return;
10028 }
Richard Smith11d19592012-11-12 23:33:00 +000010029
Sebastian Redl22653ba2011-08-30 19:58:05 +000010030 // Success! Record the copy.
10031 Statements.push_back(Move.takeAs<Stmt>());
10032 }
10033
10034 if (!Invalid) {
10035 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010036 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +000010037
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010038 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010039 if (Return.isInvalid())
10040 Invalid = true;
10041 else {
10042 Statements.push_back(Return.takeAs<Stmt>());
10043
10044 if (Trap.hasErrorOccurred()) {
10045 Diag(CurrentLocation, diag::note_member_synthesized_at)
10046 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10047 Invalid = true;
10048 }
10049 }
10050 }
10051
10052 if (Invalid) {
10053 MoveAssignOperator->setInvalidDecl();
10054 return;
10055 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010056
10057 StmtResult Body;
10058 {
10059 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010060 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010061 /*isStmtExpr=*/false);
10062 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10063 }
Sebastian Redl22653ba2011-08-30 19:58:05 +000010064 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10065
10066 if (ASTMutationListener *L = getASTMutationListener()) {
10067 L->CompletedImplicitDefinition(MoveAssignOperator);
10068 }
10069}
10070
Richard Smithd3b5c9082012-07-27 04:22:15 +000010071Sema::ImplicitExceptionSpecification
10072Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10073 CXXRecordDecl *ClassDecl = MD->getParent();
10074
10075 ImplicitExceptionSpecification ExceptSpec(*this);
10076 if (ClassDecl->isInvalidDecl())
10077 return ExceptSpec;
10078
10079 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010080 assert(T->getNumParams() >= 1 && "not a copy ctor");
10081 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010082
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010083 // C++ [except.spec]p14:
10084 // An implicitly declared special member function (Clause 12) shall have an
10085 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010086 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010087 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010088 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010089 continue;
10090
Douglas Gregora6d69502010-07-02 23:41:54 +000010091 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010092 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010093 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010094 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010095 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010096 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010097 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010098 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010099 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010100 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010101 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010102 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010103 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010104 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010105 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010106 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10107 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010108 LookupCopyingConstructor(FieldClassDecl,
10109 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010110 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010111 }
10112 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010113
Richard Smithd3b5c9082012-07-27 04:22:15 +000010114 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010115}
10116
10117CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10118 CXXRecordDecl *ClassDecl) {
10119 // C++ [class.copy]p4:
10120 // If the class definition does not explicitly declare a copy
10121 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010122 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010123
Richard Smith8bf22e52012-11-29 01:34:07 +000010124 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10125 if (DSM.isAlreadyBeingDeclared())
10126 return 0;
10127
Alexis Hunt913820d2011-05-13 06:10:58 +000010128 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10129 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010130 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010131 if (Const)
10132 ArgType = ArgType.withConst();
10133 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010134
Richard Smithb5800092012-06-10 05:43:50 +000010135 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10136 CXXCopyConstructor,
10137 Const);
10138
Douglas Gregor54be3392010-07-01 17:57:27 +000010139 DeclarationName Name
10140 = Context.DeclarationNames.getCXXConstructorName(
10141 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010142 SourceLocation ClassLoc = ClassDecl->getLocation();
10143 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010144
10145 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010146 // member of its class.
10147 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010148 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010149 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010150 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010151 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010152 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010153
Richard Smithd3b5c9082012-07-27 04:22:15 +000010154 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010155 FunctionProtoType::ExtProtoInfo EPI =
10156 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010157 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010158 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010159
Douglas Gregor54be3392010-07-01 17:57:27 +000010160 // Add the parameter to the constructor.
10161 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010162 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010163 /*IdentifierInfo=*/0,
10164 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010165 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010166 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010167
Richard Smith6b02d462012-12-08 08:32:28 +000010168 CopyConstructor->setTrivial(
10169 ClassDecl->needsOverloadResolutionForCopyConstructor()
10170 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10171 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010172
Richard Smith852265f2012-03-30 20:53:28 +000010173 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010174 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010175
Richard Smith6b02d462012-12-08 08:32:28 +000010176 // Note that we have declared this constructor.
10177 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10178
10179 if (Scope *S = getScopeForContext(ClassDecl))
10180 PushOnScopeChains(CopyConstructor, S, false);
10181 ClassDecl->addDecl(CopyConstructor);
10182
Douglas Gregor54be3392010-07-01 17:57:27 +000010183 return CopyConstructor;
10184}
10185
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010186void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010187 CXXConstructorDecl *CopyConstructor) {
10188 assert((CopyConstructor->isDefaulted() &&
10189 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010190 !CopyConstructor->doesThisDeclarationHaveABody() &&
10191 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010192 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010193
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010194 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010195 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010196
Richard Smithd577fbb2013-06-13 03:23:42 +000010197 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010198 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010199 // deprecated if the class has a user-declared copy assignment operator
10200 // or a user-declared destructor.
10201 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10202 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10203
Eli Friedmaneaf34142012-10-18 20:14:08 +000010204 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010205 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010206
David Blaikie3fc2f912013-01-17 05:26:25 +000010207 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010208 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010209 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010210 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010211 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010212 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010213 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010214 CopyConstructor->setBody(ActOnCompoundStmt(
10215 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10216 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010217 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010218
Eli Friedman276dd182013-09-05 00:02:25 +000010219 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010220 if (ASTMutationListener *L = getASTMutationListener()) {
10221 L->CompletedImplicitDefinition(CopyConstructor);
10222 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010223}
10224
Sebastian Redl22653ba2011-08-30 19:58:05 +000010225Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010226Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10227 CXXRecordDecl *ClassDecl = MD->getParent();
10228
Sebastian Redl22653ba2011-08-30 19:58:05 +000010229 // C++ [except.spec]p14:
10230 // An implicitly declared special member function (Clause 12) shall have an
10231 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010232 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010233 if (ClassDecl->isInvalidDecl())
10234 return ExceptSpec;
10235
10236 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010237 for (const auto &B : ClassDecl->bases()) {
10238 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010239 continue;
10240
Aaron Ballman574705e2014-03-13 15:41:46 +000010241 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010242 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010243 CXXConstructorDecl *Constructor =
10244 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010245 // If this is a deleted function, add it anyway. This might be conformant
10246 // with the standard. This might not. I'm not sure. It might not matter.
10247 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010248 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010249 }
10250 }
10251
10252 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010253 for (const auto &B : ClassDecl->vbases()) {
10254 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010255 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010256 CXXConstructorDecl *Constructor =
10257 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010258 // If this is a deleted function, add it anyway. This might be conformant
10259 // with the standard. This might not. I'm not sure. It might not matter.
10260 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010261 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010262 }
10263 }
10264
10265 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010266 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010267 QualType FieldType = Context.getBaseElementType(F->getType());
10268 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10269 CXXConstructorDecl *Constructor =
10270 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010271 // If this is a deleted function, add it anyway. This might be conformant
10272 // with the standard. This might not. I'm not sure. It might not matter.
10273 // In particular, the problem is that this function never gets called. It
10274 // might just be ill-formed because this function attempts to refer to
10275 // a deleted function here.
10276 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010277 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010278 }
10279 }
10280
10281 return ExceptSpec;
10282}
10283
10284CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10285 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010286 assert(ClassDecl->needsImplicitMoveConstructor());
10287
Richard Smith8bf22e52012-11-29 01:34:07 +000010288 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10289 if (DSM.isAlreadyBeingDeclared())
10290 return 0;
10291
Sebastian Redl22653ba2011-08-30 19:58:05 +000010292 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10293 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010294
Richard Smithb5800092012-06-10 05:43:50 +000010295 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10296 CXXMoveConstructor,
10297 false);
10298
Sebastian Redl22653ba2011-08-30 19:58:05 +000010299 DeclarationName Name
10300 = Context.DeclarationNames.getCXXConstructorName(
10301 Context.getCanonicalType(ClassType));
10302 SourceLocation ClassLoc = ClassDecl->getLocation();
10303 DeclarationNameInfo NameInfo(Name, ClassLoc);
10304
Richard Smith99005e62013-05-07 03:19:20 +000010305 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010306 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010307 // member of its class.
10308 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010309 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010310 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010311 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010312 MoveConstructor->setAccess(AS_public);
10313 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010314
Richard Smithd3b5c9082012-07-27 04:22:15 +000010315 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010316 FunctionProtoType::ExtProtoInfo EPI =
10317 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010318 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010319 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010320
Sebastian Redl22653ba2011-08-30 19:58:05 +000010321 // Add the parameter to the constructor.
10322 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10323 ClassLoc, ClassLoc,
10324 /*IdentifierInfo=*/0,
10325 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010326 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010327 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010328
Richard Smith6b02d462012-12-08 08:32:28 +000010329 MoveConstructor->setTrivial(
10330 ClassDecl->needsOverloadResolutionForMoveConstructor()
10331 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10332 : ClassDecl->hasTrivialMoveConstructor());
10333
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010334 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010335 ClassDecl->setImplicitMoveConstructorIsDeleted();
10336 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010337 }
10338
10339 // Note that we have declared this constructor.
10340 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10341
10342 if (Scope *S = getScopeForContext(ClassDecl))
10343 PushOnScopeChains(MoveConstructor, S, false);
10344 ClassDecl->addDecl(MoveConstructor);
10345
10346 return MoveConstructor;
10347}
10348
10349void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10350 CXXConstructorDecl *MoveConstructor) {
10351 assert((MoveConstructor->isDefaulted() &&
10352 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010353 !MoveConstructor->doesThisDeclarationHaveABody() &&
10354 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010355 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10356
10357 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10358 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10359
Eli Friedmaneaf34142012-10-18 20:14:08 +000010360 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010361 DiagnosticErrorTrap Trap(Diags);
10362
David Blaikie3fc2f912013-01-17 05:26:25 +000010363 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010364 Trap.hasErrorOccurred()) {
10365 Diag(CurrentLocation, diag::note_member_synthesized_at)
10366 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10367 MoveConstructor->setInvalidDecl();
10368 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010369 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010370 MoveConstructor->setBody(ActOnCompoundStmt(
10371 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10372 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010373 }
10374
Eli Friedman276dd182013-09-05 00:02:25 +000010375 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010376
10377 if (ASTMutationListener *L = getASTMutationListener()) {
10378 L->CompletedImplicitDefinition(MoveConstructor);
10379 }
10380}
10381
Douglas Gregor74f7d502012-02-15 19:33:52 +000010382bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010383 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010384}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010385
10386void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010387 SourceLocation CurrentLocation,
10388 CXXConversionDecl *Conv) {
10389 CXXRecordDecl *Lambda = Conv->getParent();
10390 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10391 // If we are defining a specialization of a conversion to function-ptr
10392 // cache the deduced template arguments for this specialization
10393 // so that we can use them to retrieve the corresponding call-operator
10394 // and static-invoker.
10395 const TemplateArgumentList *DeducedTemplateArgs = 0;
10396
Douglas Gregor355efbb2012-02-17 03:02:34 +000010397
Faisal Vali571df122013-09-29 08:45:24 +000010398 // Retrieve the corresponding call-operator specialization.
10399 if (Lambda->isGenericLambda()) {
10400 assert(Conv->isFunctionTemplateSpecialization());
10401 FunctionTemplateDecl *CallOpTemplate =
10402 CallOp->getDescribedFunctionTemplate();
10403 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10404 void *InsertPos = 0;
10405 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10406 DeducedTemplateArgs->data(),
10407 DeducedTemplateArgs->size(),
10408 InsertPos);
10409 assert(CallOpSpec &&
10410 "Conversion operator must have a corresponding call operator");
10411 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10412 }
10413 // Mark the call operator referenced (and add to pending instantiations
10414 // if necessary).
10415 // For both the conversion and static-invoker template specializations
10416 // we construct their body's in this function, so no need to add them
10417 // to the PendingInstantiations.
10418 MarkFunctionReferenced(CurrentLocation, CallOp);
10419
Eli Friedmaneaf34142012-10-18 20:14:08 +000010420 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010421 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010422
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010423 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010424 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10425 // ... and get the corresponding specialization for a generic lambda.
10426 if (Lambda->isGenericLambda()) {
10427 assert(DeducedTemplateArgs &&
10428 "Must have deduced template arguments from Conversion Operator");
10429 FunctionTemplateDecl *InvokeTemplate =
10430 Invoker->getDescribedFunctionTemplate();
10431 void *InsertPos = 0;
10432 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10433 DeducedTemplateArgs->data(),
10434 DeducedTemplateArgs->size(),
10435 InsertPos);
10436 assert(InvokeSpec &&
10437 "Must have a corresponding static invoker specialization");
10438 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10439 }
10440 // Construct the body of the conversion function { return __invoke; }.
10441 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10442 VK_LValue, Conv->getLocation()).take();
10443 assert(FunctionRef && "Can't refer to __invoke function?");
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010444 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).take();
Faisal Vali571df122013-09-29 08:45:24 +000010445 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10446 Conv->getLocation(),
10447 Conv->getLocation()));
10448
10449 Conv->markUsed(Context);
10450 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010451
Faisal Vali571df122013-09-29 08:45:24 +000010452 // Fill in the __invoke function with a dummy implementation. IR generation
10453 // will fill in the actual details.
10454 Invoker->markUsed(Context);
10455 Invoker->setReferenced();
10456 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10457
Douglas Gregord3b672c2012-02-16 01:06:16 +000010458 if (ASTMutationListener *L = getASTMutationListener()) {
10459 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010460 L->CompletedImplicitDefinition(Invoker);
10461 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010462}
10463
Faisal Vali571df122013-09-29 08:45:24 +000010464
10465
Douglas Gregord3b672c2012-02-16 01:06:16 +000010466void Sema::DefineImplicitLambdaToBlockPointerConversion(
10467 SourceLocation CurrentLocation,
10468 CXXConversionDecl *Conv)
10469{
Faisal Vali850da1a2013-09-29 17:08:32 +000010470 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010471
Eli Friedman276dd182013-09-05 00:02:25 +000010472 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010473
Eli Friedmaneaf34142012-10-18 20:14:08 +000010474 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010475 DiagnosticErrorTrap Trap(Diags);
10476
Douglas Gregored90df32012-02-22 05:02:47 +000010477 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010478 Expr *This = ActOnCXXThis(CurrentLocation).take();
10479 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010480
Eli Friedman98b01ed2012-03-01 04:01:32 +000010481 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10482 Conv->getLocation(),
10483 Conv, DerefThis);
10484
10485 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10486 // behavior. Note that only the general conversion function does this
10487 // (since it's unusable otherwise); in the case where we inline the
10488 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010489 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010490 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10491 CK_CopyAndAutoreleaseBlockObject,
10492 BuildBlock.get(), 0, VK_RValue);
10493
10494 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010495 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010496 Conv->setInvalidDecl();
10497 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010498 }
Douglas Gregored90df32012-02-22 05:02:47 +000010499
Douglas Gregored90df32012-02-22 05:02:47 +000010500 // Create the return statement that returns the block from the conversion
10501 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010502 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010503 if (Return.isInvalid()) {
10504 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10505 Conv->setInvalidDecl();
10506 return;
10507 }
10508
10509 // Set the body of the conversion function.
10510 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010511 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010512 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010513 Conv->getLocation()));
10514
Douglas Gregored90df32012-02-22 05:02:47 +000010515 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010516 if (ASTMutationListener *L = getASTMutationListener()) {
10517 L->CompletedImplicitDefinition(Conv);
10518 }
10519}
10520
Douglas Gregord2f70072012-03-10 06:53:13 +000010521/// \brief Determine whether the given list arguments contains exactly one
10522/// "real" (non-default) argument.
10523static bool hasOneRealArgument(MultiExprArg Args) {
10524 switch (Args.size()) {
10525 case 0:
10526 return false;
10527
10528 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010529 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010530 return false;
10531
10532 // fall through
10533 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010534 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010535 }
10536
10537 return false;
10538}
10539
John McCalldadc5752010-08-24 06:29:42 +000010540ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010541Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010542 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010543 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010544 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010545 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010546 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010547 unsigned ConstructKind,
10548 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010549 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010550
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010551 // C++0x [class.copy]p34:
10552 // When certain criteria are met, an implementation is allowed to
10553 // omit the copy/move construction of a class object, even if the
10554 // copy/move constructor and/or destructor for the object have
10555 // side effects. [...]
10556 // - when a temporary class object that has not been bound to a
10557 // reference (12.2) would be copied/moved to a class object
10558 // with the same cv-unqualified type, the copy/move operation
10559 // can be omitted by constructing the temporary object
10560 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010561 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010562 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010563 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010564 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010565 }
Mike Stump11289f42009-09-09 15:08:12 +000010566
10567 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010568 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010569 IsListInitialization, RequiresZeroInit,
10570 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010571}
10572
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010573/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10574/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010575ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010576Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10577 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010578 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010579 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010580 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010581 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010582 unsigned ConstructKind,
10583 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010584 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010585 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010586 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010587 HadMultipleCandidates,
10588 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010589 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10590 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010591}
10592
John McCall03c48482010-02-02 09:10:11 +000010593void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010594 if (VD->isInvalidDecl()) return;
10595
John McCall03c48482010-02-02 09:10:11 +000010596 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010597 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010598 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010599 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010600
Chandler Carruth86d17d32011-03-27 21:26:48 +000010601 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010602 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010603 CheckDestructorAccess(VD->getLocation(), Destructor,
10604 PDiag(diag::err_access_dtor_var)
10605 << VD->getDeclName()
10606 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010607 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010608
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010609 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010610 if (!VD->hasGlobalStorage()) return;
10611
10612 // Emit warning for non-trivial dtor in global scope (a real global,
10613 // class-static, function-static).
10614 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10615
10616 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010617 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010618 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010619}
10620
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010621/// \brief Given a constructor and the set of arguments provided for the
10622/// constructor, convert the arguments and add any required default arguments
10623/// to form a proper call to this constructor.
10624///
10625/// \returns true if an error occurred, false otherwise.
10626bool
10627Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10628 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010629 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010630 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010631 bool AllowExplicit,
10632 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010633 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10634 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010635 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010636
10637 const FunctionProtoType *Proto
10638 = Constructor->getType()->getAs<FunctionProtoType>();
10639 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010640 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010641
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010642 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010643 if (NumArgs < NumParams)
10644 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010645 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010646 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010647
10648 VariadicCallType CallType =
10649 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010650 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010651 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010652 Proto, 0,
10653 llvm::makeArrayRef(Args, NumArgs),
10654 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010655 CallType, AllowExplicit,
10656 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010657 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010658
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010659 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010660
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010661 CheckConstructorCall(Constructor,
10662 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10663 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010664 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010665
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010666 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010667}
10668
Anders Carlssone363c8e2009-12-12 00:32:00 +000010669static inline bool
10670CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10671 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010672 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010673 if (isa<NamespaceDecl>(DC)) {
10674 return SemaRef.Diag(FnDecl->getLocation(),
10675 diag::err_operator_new_delete_declared_in_namespace)
10676 << FnDecl->getDeclName();
10677 }
10678
10679 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010680 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010681 return SemaRef.Diag(FnDecl->getLocation(),
10682 diag::err_operator_new_delete_declared_static)
10683 << FnDecl->getDeclName();
10684 }
10685
Anders Carlsson60659a82009-12-12 02:43:16 +000010686 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010687}
10688
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010689static inline bool
10690CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10691 CanQualType ExpectedResultType,
10692 CanQualType ExpectedFirstParamType,
10693 unsigned DependentParamTypeDiag,
10694 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010695 QualType ResultType =
10696 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010697
10698 // Check that the result type is not dependent.
10699 if (ResultType->isDependentType())
10700 return SemaRef.Diag(FnDecl->getLocation(),
10701 diag::err_operator_new_delete_dependent_result_type)
10702 << FnDecl->getDeclName() << ExpectedResultType;
10703
10704 // Check that the result type is what we expect.
10705 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10706 return SemaRef.Diag(FnDecl->getLocation(),
10707 diag::err_operator_new_delete_invalid_result_type)
10708 << FnDecl->getDeclName() << ExpectedResultType;
10709
10710 // A function template must have at least 2 parameters.
10711 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10712 return SemaRef.Diag(FnDecl->getLocation(),
10713 diag::err_operator_new_delete_template_too_few_parameters)
10714 << FnDecl->getDeclName();
10715
10716 // The function decl must have at least 1 parameter.
10717 if (FnDecl->getNumParams() == 0)
10718 return SemaRef.Diag(FnDecl->getLocation(),
10719 diag::err_operator_new_delete_too_few_parameters)
10720 << FnDecl->getDeclName();
10721
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010722 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010723 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10724 if (FirstParamType->isDependentType())
10725 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10726 << FnDecl->getDeclName() << ExpectedFirstParamType;
10727
10728 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010729 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010730 ExpectedFirstParamType)
10731 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10732 << FnDecl->getDeclName() << ExpectedFirstParamType;
10733
10734 return false;
10735}
10736
Anders Carlsson12308f42009-12-11 23:23:22 +000010737static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010738CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010739 // C++ [basic.stc.dynamic.allocation]p1:
10740 // A program is ill-formed if an allocation function is declared in a
10741 // namespace scope other than global scope or declared static in global
10742 // scope.
10743 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10744 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010745
10746 CanQualType SizeTy =
10747 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10748
10749 // C++ [basic.stc.dynamic.allocation]p1:
10750 // The return type shall be void*. The first parameter shall have type
10751 // std::size_t.
10752 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10753 SizeTy,
10754 diag::err_operator_new_dependent_param_type,
10755 diag::err_operator_new_param_type))
10756 return true;
10757
10758 // C++ [basic.stc.dynamic.allocation]p1:
10759 // The first parameter shall not have an associated default argument.
10760 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010761 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010762 diag::err_operator_new_default_arg)
10763 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10764
10765 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010766}
10767
10768static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010769CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010770 // C++ [basic.stc.dynamic.deallocation]p1:
10771 // A program is ill-formed if deallocation functions are declared in a
10772 // namespace scope other than global scope or declared static in global
10773 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010774 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10775 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010776
10777 // C++ [basic.stc.dynamic.deallocation]p2:
10778 // Each deallocation function shall return void and its first parameter
10779 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010780 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10781 SemaRef.Context.VoidPtrTy,
10782 diag::err_operator_delete_dependent_param_type,
10783 diag::err_operator_delete_param_type))
10784 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010785
Anders Carlsson12308f42009-12-11 23:23:22 +000010786 return false;
10787}
10788
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010789/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10790/// of this overloaded operator is well-formed. If so, returns false;
10791/// otherwise, emits appropriate diagnostics and returns true.
10792bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010793 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010794 "Expected an overloaded operator declaration");
10795
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010796 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10797
Mike Stump11289f42009-09-09 15:08:12 +000010798 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010799 // The allocation and deallocation functions, operator new,
10800 // operator new[], operator delete and operator delete[], are
10801 // described completely in 3.7.3. The attributes and restrictions
10802 // found in the rest of this subclause do not apply to them unless
10803 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010804 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010805 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010806
Anders Carlsson22f443f2009-12-12 00:26:23 +000010807 if (Op == OO_New || Op == OO_Array_New)
10808 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010809
10810 // C++ [over.oper]p6:
10811 // An operator function shall either be a non-static member
10812 // function or be a non-member function and have at least one
10813 // parameter whose type is a class, a reference to a class, an
10814 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010815 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10816 if (MethodDecl->isStatic())
10817 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010818 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010819 } else {
10820 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010821 for (auto Param : FnDecl->params()) {
10822 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010823 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10824 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010825 ClassOrEnumParam = true;
10826 break;
10827 }
10828 }
10829
Douglas Gregord69246b2008-11-17 16:14:12 +000010830 if (!ClassOrEnumParam)
10831 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010832 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010833 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010834 }
10835
10836 // C++ [over.oper]p8:
10837 // An operator function cannot have default arguments (8.3.6),
10838 // except where explicitly stated below.
10839 //
Mike Stump11289f42009-09-09 15:08:12 +000010840 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010841 // (C++ [over.call]p1).
10842 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010843 for (auto Param : FnDecl->params()) {
10844 if (Param->hasDefaultArg())
10845 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010846 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010847 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010848 }
10849 }
10850
Douglas Gregor6cf08062008-11-10 13:38:07 +000010851 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10852 { false, false, false }
10853#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10854 , { Unary, Binary, MemberOnly }
10855#include "clang/Basic/OperatorKinds.def"
10856 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010857
Douglas Gregor6cf08062008-11-10 13:38:07 +000010858 bool CanBeUnaryOperator = OperatorUses[Op][0];
10859 bool CanBeBinaryOperator = OperatorUses[Op][1];
10860 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010861
10862 // C++ [over.oper]p8:
10863 // [...] Operator functions cannot have more or fewer parameters
10864 // than the number required for the corresponding operator, as
10865 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010866 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010867 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010868 if (Op != OO_Call &&
10869 ((NumParams == 1 && !CanBeUnaryOperator) ||
10870 (NumParams == 2 && !CanBeBinaryOperator) ||
10871 (NumParams < 1) || (NumParams > 2))) {
10872 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010873 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010874 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010875 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010876 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010877 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010878 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010879 assert(CanBeBinaryOperator &&
10880 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010881 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010882 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010883
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010884 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010885 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010886 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010887
Douglas Gregord69246b2008-11-17 16:14:12 +000010888 // Overloaded operators other than operator() cannot be variadic.
10889 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010890 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010891 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010892 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010893 }
10894
10895 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010896 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10897 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010898 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010899 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010900 }
10901
10902 // C++ [over.inc]p1:
10903 // The user-defined function called operator++ implements the
10904 // prefix and postfix ++ operator. If this function is a member
10905 // function with no parameters, or a non-member function with one
10906 // parameter of class or enumeration type, it defines the prefix
10907 // increment operator ++ for objects of that type. If the function
10908 // is a member function with one parameter (which shall be of type
10909 // int) or a non-member function with two parameters (the second
10910 // of which shall be of type int), it defines the postfix
10911 // increment operator ++ for objects of that type.
10912 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10913 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010914 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010915
Richard Smith538b52a2014-01-30 22:24:05 +000010916 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10917 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010918 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010919 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010920 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010921 }
10922
Douglas Gregord69246b2008-11-17 16:14:12 +000010923 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010924}
Chris Lattner3b024a32008-12-17 07:09:26 +000010925
Alexis Huntc88db062010-01-13 09:01:02 +000010926/// CheckLiteralOperatorDeclaration - Check whether the declaration
10927/// of this literal operator function is well-formed. If so, returns
10928/// false; otherwise, emits appropriate diagnostics and returns true.
10929bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010930 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010931 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10932 << FnDecl->getDeclName();
10933 return true;
10934 }
10935
Richard Smith72eebee2012-03-04 09:41:16 +000010936 if (FnDecl->isExternC()) {
10937 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10938 return true;
10939 }
10940
Alexis Huntc88db062010-01-13 09:01:02 +000010941 bool Valid = false;
10942
Richard Smithbcc22fc2012-03-09 08:00:36 +000010943 // This might be the definition of a literal operator template.
10944 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10945 // This might be a specialization of a literal operator template.
10946 if (!TpDecl)
10947 TpDecl = FnDecl->getPrimaryTemplate();
10948
Richard Smithb8b41d32013-10-07 19:57:58 +000010949 // template <char...> type operator "" name() and
10950 // template <class T, T...> type operator "" name() are the only valid
10951 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010952 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010953 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010954 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010955 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10956 if (Params->size() == 1) {
10957 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010958 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010959
Alexis Hunt7dd26172010-04-07 23:11:06 +000010960 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010961 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10962 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10963 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010964 } else if (Params->size() == 2) {
10965 TemplateTypeParmDecl *PmType =
10966 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10967 NonTypeTemplateParmDecl *PmArgs =
10968 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10969
10970 // The second template parameter must be a parameter pack with the
10971 // first template parameter as its type.
10972 if (PmType && PmArgs &&
10973 !PmType->isTemplateParameterPack() &&
10974 PmArgs->isTemplateParameterPack()) {
10975 const TemplateTypeParmType *TArgs =
10976 PmArgs->getType()->getAs<TemplateTypeParmType>();
10977 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10978 TArgs->getIndex() == PmType->getIndex()) {
10979 Valid = true;
10980 if (ActiveTemplateInstantiations.empty())
10981 Diag(FnDecl->getLocation(),
10982 diag::ext_string_literal_operator_template);
10983 }
10984 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010985 }
10986 }
Richard Smith72eebee2012-03-04 09:41:16 +000010987 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010988 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010989 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10990
Richard Smith72eebee2012-03-04 09:41:16 +000010991 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010992
Alexis Hunt079a6f72010-04-07 22:57:35 +000010993 // unsigned long long int, long double, and any character type are allowed
10994 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010995 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10996 Context.hasSameType(T, Context.LongDoubleTy) ||
10997 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010998 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010999 Context.hasSameType(T, Context.Char16Ty) ||
11000 Context.hasSameType(T, Context.Char32Ty)) {
11001 if (++Param == FnDecl->param_end())
11002 Valid = true;
11003 goto FinishedParams;
11004 }
11005
Alexis Hunt079a6f72010-04-07 22:57:35 +000011006 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011007 const PointerType *PT = T->getAs<PointerType>();
11008 if (!PT)
11009 goto FinishedParams;
11010 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011011 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011012 goto FinishedParams;
11013 T = T.getUnqualifiedType();
11014
11015 // Move on to the second parameter;
11016 ++Param;
11017
11018 // If there is no second parameter, the first must be a const char *
11019 if (Param == FnDecl->param_end()) {
11020 if (Context.hasSameType(T, Context.CharTy))
11021 Valid = true;
11022 goto FinishedParams;
11023 }
11024
11025 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11026 // are allowed as the first parameter to a two-parameter function
11027 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011028 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011029 Context.hasSameType(T, Context.Char16Ty) ||
11030 Context.hasSameType(T, Context.Char32Ty)))
11031 goto FinishedParams;
11032
11033 // The second and final parameter must be an std::size_t
11034 T = (*Param)->getType().getUnqualifiedType();
11035 if (Context.hasSameType(T, Context.getSizeType()) &&
11036 ++Param == FnDecl->param_end())
11037 Valid = true;
11038 }
11039
11040 // FIXME: This diagnostic is absolutely terrible.
11041FinishedParams:
11042 if (!Valid) {
11043 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11044 << FnDecl->getDeclName();
11045 return true;
11046 }
11047
Richard Smith768cecc2012-03-09 08:16:22 +000011048 // A parameter-declaration-clause containing a default argument is not
11049 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011050 for (auto Param : FnDecl->params()) {
11051 if (Param->hasDefaultArg()) {
11052 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011053 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011054 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011055 break;
11056 }
11057 }
11058
Richard Smith0df56f42012-03-08 02:39:21 +000011059 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011060 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11061 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011062 // C++11 [usrlit.suffix]p1:
11063 // Literal suffix identifiers that do not start with an underscore
11064 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011065 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11066 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011067 }
Richard Smith0df56f42012-03-08 02:39:21 +000011068
Alexis Huntc88db062010-01-13 09:01:02 +000011069 return false;
11070}
11071
Douglas Gregor07665a62009-01-05 19:45:36 +000011072/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11073/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011074/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11075/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011076/// the '{' brace. Otherwise, this linkage specification does not
11077/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011078Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011079 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011080 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011081 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11082 if (!Lit->isAscii()) {
11083 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11084 << LangStr->getSourceRange();
11085 return 0;
11086 }
11087
11088 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011089 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011090 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011091 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011092 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011093 Language = LinkageSpecDecl::lang_cxx;
11094 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011095 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11096 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011097 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011098 }
Mike Stump11289f42009-09-09 15:08:12 +000011099
Chris Lattner438e5012008-12-17 07:13:27 +000011100 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011101
Richard Smith4ee696d2014-02-17 23:25:27 +000011102 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11103 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011104 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011105 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011106 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011107 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011108}
11109
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011110/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011111/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11112/// valid, it's the position of the closing '}' brace in a linkage
11113/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011114Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011115 Decl *LinkageSpec,
11116 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011117 if (RBraceLoc.isValid()) {
11118 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11119 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011120 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011121 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011122 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011123}
11124
Michael Han84324352013-02-22 17:15:32 +000011125Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11126 AttributeList *AttrList,
11127 SourceLocation SemiLoc) {
11128 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11129 // Attribute declarations appertain to empty declaration so we handle
11130 // them here.
11131 if (AttrList)
11132 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011133
Michael Han84324352013-02-22 17:15:32 +000011134 CurContext->addDecl(ED);
11135 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011136}
11137
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011138/// \brief Perform semantic analysis for the variable declaration that
11139/// occurs within a C++ catch clause, returning the newly-created
11140/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011141VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011142 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011143 SourceLocation StartLoc,
11144 SourceLocation Loc,
11145 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011146 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011147 QualType ExDeclType = TInfo->getType();
11148
Sebastian Redl54c04d42008-12-22 19:15:10 +000011149 // Arrays and functions decay.
11150 if (ExDeclType->isArrayType())
11151 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11152 else if (ExDeclType->isFunctionType())
11153 ExDeclType = Context.getPointerType(ExDeclType);
11154
11155 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11156 // The exception-declaration shall not denote a pointer or reference to an
11157 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011158 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011159 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011160 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011161 Invalid = true;
11162 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011163
Sebastian Redl54c04d42008-12-22 19:15:10 +000011164 QualType BaseType = ExDeclType;
11165 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011166 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011167 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011168 BaseType = Ptr->getPointeeType();
11169 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011170 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011171 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011172 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011173 BaseType = Ref->getPointeeType();
11174 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011175 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011176 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011177 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011178 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011179 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011180
Mike Stump11289f42009-09-09 15:08:12 +000011181 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011182 RequireNonAbstractType(Loc, ExDeclType,
11183 diag::err_abstract_type_in_decl,
11184 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011185 Invalid = true;
11186
John McCall2ca705e2010-07-24 00:37:23 +000011187 // Only the non-fragile NeXT runtime currently supports C++ catches
11188 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011189 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011190 QualType T = ExDeclType;
11191 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11192 T = RT->getPointeeType();
11193
11194 if (T->isObjCObjectType()) {
11195 Diag(Loc, diag::err_objc_object_catch);
11196 Invalid = true;
11197 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011198 // FIXME: should this be a test for macosx-fragile specifically?
11199 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011200 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011201 }
11202 }
11203
Abramo Bagnaradff19302011-03-08 08:55:46 +000011204 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011205 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011206 ExDecl->setExceptionVariable(true);
11207
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011208 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011209 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011210 Invalid = true;
11211
Douglas Gregor750734c2011-07-06 18:14:43 +000011212 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011213 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011214 // Insulate this from anything else we might currently be parsing.
11215 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11216
Douglas Gregor6de584c2010-03-05 23:38:39 +000011217 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011218 // The object declared in an exception-declaration or, if the
11219 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011220 // copy-initialized (8.5) from the exception object. [...]
11221 // The object is destroyed when the handler exits, after the destruction
11222 // of any automatic objects initialized within the handler.
11223 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011224 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011225 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011226 QualType initType = ExDeclType;
11227
11228 InitializedEntity entity =
11229 InitializedEntity::InitializeVariable(ExDecl);
11230 InitializationKind initKind =
11231 InitializationKind::CreateCopy(Loc, SourceLocation());
11232
11233 Expr *opaqueValue =
11234 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011235 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11236 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011237 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011238 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011239 else {
11240 // If the constructor used was non-trivial, set this as the
11241 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011242 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011243 if (!construct->getConstructor()->isTrivial()) {
11244 Expr *init = MaybeCreateExprWithCleanups(construct);
11245 ExDecl->setInit(init);
11246 }
11247
11248 // And make sure it's destructable.
11249 FinalizeVarWithDestructor(ExDecl, recordType);
11250 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011251 }
11252 }
11253
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011254 if (Invalid)
11255 ExDecl->setInvalidDecl();
11256
11257 return ExDecl;
11258}
11259
11260/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11261/// handler.
John McCall48871652010-08-21 09:40:31 +000011262Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011263 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011264 bool Invalid = D.isInvalidType();
11265
11266 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011267 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11268 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011269 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11270 D.getIdentifierLoc());
11271 Invalid = true;
11272 }
11273
Sebastian Redl54c04d42008-12-22 19:15:10 +000011274 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011275 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011276 LookupOrdinaryName,
11277 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011278 // The scope should be freshly made just for us. There is just no way
11279 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011280 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011281 if (PrevDecl->isTemplateParameter()) {
11282 // Maybe we will complain about the shadowed template parameter.
11283 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011284 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011285 }
11286 }
11287
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011288 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011289 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11290 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011291 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011292 }
11293
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011294 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011295 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011296 D.getIdentifierLoc(),
11297 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011298 if (Invalid)
11299 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011300
Sebastian Redl54c04d42008-12-22 19:15:10 +000011301 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011302 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011303 PushOnScopeChains(ExDecl, S);
11304 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011305 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011306
Douglas Gregor758a8692009-06-17 21:51:59 +000011307 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011308 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011309}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011310
Abramo Bagnaraea947882011-03-08 16:41:52 +000011311Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011312 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011313 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011314 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011315 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011316
Richard Smithded9c2e2012-07-11 22:37:56 +000011317 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11318 return 0;
11319
11320 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11321 AssertMessage, RParenLoc, false);
11322}
11323
11324Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11325 Expr *AssertExpr,
11326 StringLiteral *AssertMessage,
11327 SourceLocation RParenLoc,
11328 bool Failed) {
11329 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11330 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011331 // In a static_assert-declaration, the constant-expression shall be a
11332 // constant expression that can be contextually converted to bool.
11333 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11334 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011335 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011336
Richard Smith902ca212011-12-14 23:32:26 +000011337 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011338 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011339 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011340 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011341 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011342
Richard Smithded9c2e2012-07-11 22:37:56 +000011343 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011344 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011345 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011346 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011347 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011348 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011349 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011350 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011351 }
Mike Stump11289f42009-09-09 15:08:12 +000011352
Abramo Bagnaraea947882011-03-08 16:41:52 +000011353 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011354 AssertExpr, AssertMessage, RParenLoc,
11355 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011356
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011357 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011358 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011359}
Sebastian Redlf769df52009-03-24 22:27:57 +000011360
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011361/// \brief Perform semantic analysis of the given friend type declaration.
11362///
11363/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011364FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011365 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011366 TypeSourceInfo *TSInfo) {
11367 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11368
11369 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011370 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011371
Richard Smithc8239732011-10-18 21:39:00 +000011372 // C++03 [class.friend]p2:
11373 // An elaborated-type-specifier shall be used in a friend declaration
11374 // for a class.*
11375 //
11376 // * The class-key of the elaborated-type-specifier is required.
11377 if (!ActiveTemplateInstantiations.empty()) {
11378 // Do not complain about the form of friend template types during
11379 // template instantiation; we will already have complained when the
11380 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011381 } else {
11382 if (!T->isElaboratedTypeSpecifier()) {
11383 // If we evaluated the type to a record type, suggest putting
11384 // a tag in front.
11385 if (const RecordType *RT = T->getAs<RecordType>()) {
11386 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011387
11388 SmallString<16> InsertionText(" ");
11389 InsertionText += RD->getKindName();
11390
Nick Lewycky36722d22013-02-06 05:59:33 +000011391 Diag(TypeRange.getBegin(),
11392 getLangOpts().CPlusPlus11 ?
11393 diag::warn_cxx98_compat_unelaborated_friend_type :
11394 diag::ext_unelaborated_friend_type)
11395 << (unsigned) RD->getTagKind()
11396 << T
11397 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11398 InsertionText);
11399 } else {
11400 Diag(FriendLoc,
11401 getLangOpts().CPlusPlus11 ?
11402 diag::warn_cxx98_compat_nonclass_type_friend :
11403 diag::ext_nonclass_type_friend)
11404 << T
11405 << TypeRange;
11406 }
11407 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011408 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011409 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011410 diag::warn_cxx98_compat_enum_friend :
11411 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011412 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011413 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011414 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011415
Nick Lewycky36722d22013-02-06 05:59:33 +000011416 // C++11 [class.friend]p3:
11417 // A friend declaration that does not declare a function shall have one
11418 // of the following forms:
11419 // friend elaborated-type-specifier ;
11420 // friend simple-type-specifier ;
11421 // friend typename-specifier ;
11422 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11423 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11424 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011425
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011426 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011427 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011428 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011429 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011430}
11431
John McCallace48cd2010-10-19 01:40:49 +000011432/// Handle a friend tag declaration where the scope specifier was
11433/// templated.
11434Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11435 unsigned TagSpec, SourceLocation TagLoc,
11436 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011437 IdentifierInfo *Name,
11438 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011439 AttributeList *Attr,
11440 MultiTemplateParamsArg TempParamLists) {
11441 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11442
11443 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011444 bool Invalid = false;
11445
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011446 if (TemplateParameterList *TemplateParams =
11447 MatchTemplateParametersToScopeSpecifier(
Richard Smith4b55a9c2014-04-17 03:29:33 +000011448 TagLoc, NameLoc, SS, 0, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011449 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011450 if (TemplateParams->size() > 0) {
11451 // This is a declaration of a class template.
11452 if (Invalid)
11453 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011454
Eric Christopher6f228b52011-07-21 05:34:24 +000011455 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11456 SS, Name, NameLoc, Attr,
11457 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011458 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011459 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011460 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011461 } else {
11462 // The "template<>" header is extraneous.
11463 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11464 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11465 isExplicitSpecialization = true;
11466 }
11467 }
11468
11469 if (Invalid) return 0;
11470
John McCallace48cd2010-10-19 01:40:49 +000011471 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011472 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011473 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011474 isAllExplicitSpecializations = false;
11475 break;
11476 }
11477 }
11478
11479 // FIXME: don't ignore attributes.
11480
11481 // If it's explicit specializations all the way down, just forget
11482 // about the template header and build an appropriate non-templated
11483 // friend. TODO: for source fidelity, remember the headers.
11484 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011485 if (SS.isEmpty()) {
11486 bool Owned = false;
11487 bool IsDependent = false;
11488 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011489 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011490 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011491 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011492 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011493 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011494 /*UnderlyingType=*/TypeResult(),
11495 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011496 }
Richard Smith649c7b062014-01-08 00:56:48 +000011497
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011498 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011499 ElaboratedTypeKeyword Keyword
11500 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011501 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011502 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011503 if (T.isNull())
11504 return 0;
11505
11506 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11507 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011508 DependentNameTypeLoc TL =
11509 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011510 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011511 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011512 TL.setNameLoc(NameLoc);
11513 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011514 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011515 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011516 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011517 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011518 }
11519
11520 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011521 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011522 Friend->setAccess(AS_public);
11523 CurContext->addDecl(Friend);
11524 return Friend;
11525 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011526
11527 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11528
11529
John McCallace48cd2010-10-19 01:40:49 +000011530
11531 // Handle the case of a templated-scope friend class. e.g.
11532 // template <class T> class A<T>::B;
11533 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011534 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11535 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011536 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11537 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11538 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011539 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011540 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011541 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011542 TL.setNameLoc(NameLoc);
11543
11544 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011545 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011546 Friend->setAccess(AS_public);
11547 Friend->setUnsupportedFriend(true);
11548 CurContext->addDecl(Friend);
11549 return Friend;
11550}
11551
11552
John McCall11083da2009-09-16 22:47:08 +000011553/// Handle a friend type declaration. This works in tandem with
11554/// ActOnTag.
11555///
11556/// Notes on friend class templates:
11557///
11558/// We generally treat friend class declarations as if they were
11559/// declaring a class. So, for example, the elaborated type specifier
11560/// in a friend declaration is required to obey the restrictions of a
11561/// class-head (i.e. no typedefs in the scope chain), template
11562/// parameters are required to match up with simple template-ids, &c.
11563/// However, unlike when declaring a template specialization, it's
11564/// okay to refer to a template specialization without an empty
11565/// template parameter declaration, e.g.
11566/// friend class A<T>::B<unsigned>;
11567/// We permit this as a special case; if there are any template
11568/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011569/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011570Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011571 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011572 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011573
11574 assert(DS.isFriendSpecified());
11575 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11576
John McCall11083da2009-09-16 22:47:08 +000011577 // Try to convert the decl specifier to a type. This works for
11578 // friend templates because ActOnTag never produces a ClassTemplateDecl
11579 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011580 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011581 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11582 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011583 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011584 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011585
Douglas Gregor6c110f32010-12-16 01:14:37 +000011586 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11587 return 0;
11588
John McCall11083da2009-09-16 22:47:08 +000011589 // This is definitely an error in C++98. It's probably meant to
11590 // be forbidden in C++0x, too, but the specification is just
11591 // poorly written.
11592 //
11593 // The problem is with declarations like the following:
11594 // template <T> friend A<T>::foo;
11595 // where deciding whether a class C is a friend or not now hinges
11596 // on whether there exists an instantiation of A that causes
11597 // 'foo' to equal C. There are restrictions on class-heads
11598 // (which we declare (by fiat) elaborated friend declarations to
11599 // be) that makes this tractable.
11600 //
11601 // FIXME: handle "template <> friend class A<T>;", which
11602 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011603 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011604 Diag(Loc, diag::err_tagless_friend_type_template)
11605 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011606 return 0;
John McCall11083da2009-09-16 22:47:08 +000011607 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011608
John McCallaa74a0c2009-08-28 07:59:38 +000011609 // C++98 [class.friend]p1: A friend of a class is a function
11610 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011611 // This is fixed in DR77, which just barely didn't make the C++03
11612 // deadline. It's also a very silly restriction that seriously
11613 // affects inner classes and which nobody else seems to implement;
11614 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011615 //
11616 // But note that we could warn about it: it's always useless to
11617 // friend one of your own members (it's not, however, worthless to
11618 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011619
John McCall11083da2009-09-16 22:47:08 +000011620 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011621 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011622 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011623 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011624 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011625 TSI,
John McCall11083da2009-09-16 22:47:08 +000011626 DS.getFriendSpecLoc());
11627 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011628 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011629
11630 if (!D)
John McCall48871652010-08-21 09:40:31 +000011631 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011632
John McCall11083da2009-09-16 22:47:08 +000011633 D->setAccess(AS_public);
11634 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011635
John McCall48871652010-08-21 09:40:31 +000011636 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011637}
11638
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011639NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11640 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011641 const DeclSpec &DS = D.getDeclSpec();
11642
11643 assert(DS.isFriendSpecified());
11644 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11645
11646 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011647 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011648
11649 // C++ [class.friend]p1
11650 // A friend of a class is a function or class....
11651 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011652 // It *doesn't* see through dependent types, which is correct
11653 // according to [temp.arg.type]p3:
11654 // If a declaration acquires a function type through a
11655 // type dependent on a template-parameter and this causes
11656 // a declaration that does not use the syntactic form of a
11657 // function declarator to have a function type, the program
11658 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011659 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011660 Diag(Loc, diag::err_unexpected_friend);
11661
11662 // It might be worthwhile to try to recover by creating an
11663 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011664 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011665 }
11666
11667 // C++ [namespace.memdef]p3
11668 // - If a friend declaration in a non-local class first declares a
11669 // class or function, the friend class or function is a member
11670 // of the innermost enclosing namespace.
11671 // - The name of the friend is not found by simple name lookup
11672 // until a matching declaration is provided in that namespace
11673 // scope (either before or after the class declaration granting
11674 // friendship).
11675 // - If a friend function is called, its name may be found by the
11676 // name lookup that considers functions from namespaces and
11677 // classes associated with the types of the function arguments.
11678 // - When looking for a prior declaration of a class or a function
11679 // declared as a friend, scopes outside the innermost enclosing
11680 // namespace scope are not considered.
11681
John McCallde3fd222010-10-12 23:13:28 +000011682 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011683 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11684 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011685 assert(Name);
11686
Douglas Gregor6c110f32010-12-16 01:14:37 +000011687 // Check for unexpanded parameter packs.
11688 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11689 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11690 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11691 return 0;
11692
John McCall07e91c02009-08-06 02:15:43 +000011693 // The context we found the declaration in, or in which we should
11694 // create the declaration.
11695 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011696 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011697 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011698 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011699
Richard Smith114394f2013-08-09 04:35:01 +000011700 // There are five cases here.
11701 // - There's no scope specifier and we're in a local class. Only look
11702 // for functions declared in the immediately-enclosing block scope.
11703 // We recover from invalid scope qualifiers as if they just weren't there.
11704 FunctionDecl *FunctionContainingLocalClass = 0;
11705 if ((SS.isInvalid() || !SS.isSet()) &&
11706 (FunctionContainingLocalClass =
11707 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11708 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011709 // If a friend declaration appears in a local class and the name
11710 // specified is an unqualified name, a prior declaration is
11711 // looked up without considering scopes that are outside the
11712 // innermost enclosing non-class scope. For a friend function
11713 // declaration, if there is no prior declaration, the program is
11714 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011715
11716 // Find the innermost enclosing non-class scope. This is the block
11717 // scope containing the local class definition (or for a nested class,
11718 // the outer local class).
11719 DCScope = S->getFnParent();
11720
11721 // Look up the function name in the scope.
11722 Previous.clear(LookupLocalFriendName);
11723 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11724
11725 if (!Previous.empty()) {
11726 // All possible previous declarations must have the same context:
11727 // either they were declared at block scope or they are members of
11728 // one of the enclosing local classes.
11729 DC = Previous.getRepresentativeDecl()->getDeclContext();
11730 } else {
11731 // This is ill-formed, but provide the context that we would have
11732 // declared the function in, if we were permitted to, for error recovery.
11733 DC = FunctionContainingLocalClass;
11734 }
Richard Smith541b38b2013-09-20 01:15:31 +000011735 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011736
11737 // C++ [class.friend]p6:
11738 // A function can be defined in a friend declaration of a class if and
11739 // only if the class is a non-local class (9.8), the function name is
11740 // unqualified, and the function has namespace scope.
11741 if (D.isFunctionDefinition()) {
11742 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11743 }
11744
11745 // - There's no scope specifier, in which case we just go to the
11746 // appropriate scope and look for a function or function template
11747 // there as appropriate.
11748 } else if (SS.isInvalid() || !SS.isSet()) {
11749 // C++11 [namespace.memdef]p3:
11750 // If the name in a friend declaration is neither qualified nor
11751 // a template-id and the declaration is a function or an
11752 // elaborated-type-specifier, the lookup to determine whether
11753 // the entity has been previously declared shall not consider
11754 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011755 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011756
John McCallf7cfb222010-10-13 05:45:15 +000011757 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011758 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011759
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011760 // Skip class contexts. If someone can cite chapter and verse
11761 // for this behavior, that would be nice --- it's what GCC and
11762 // EDG do, and it seems like a reasonable intent, but the spec
11763 // really only says that checks for unqualified existing
11764 // declarations should stop at the nearest enclosing namespace,
11765 // not that they should only consider the nearest enclosing
11766 // namespace.
11767 while (DC->isRecord())
11768 DC = DC->getParent();
11769
11770 DeclContext *LookupDC = DC;
11771 while (LookupDC->isTransparentContext())
11772 LookupDC = LookupDC->getParent();
11773
11774 while (true) {
11775 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011776
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011777 if (!Previous.empty()) {
11778 DC = LookupDC;
11779 break;
John McCallf4776592010-10-14 22:22:28 +000011780 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011781
11782 if (isTemplateId) {
11783 if (isa<TranslationUnitDecl>(LookupDC)) break;
11784 } else {
11785 if (LookupDC->isFileContext()) break;
11786 }
11787 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011788 }
11789
John McCallccbc0322010-10-13 06:22:15 +000011790 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011791
John McCallde3fd222010-10-12 23:13:28 +000011792 // - There's a non-dependent scope specifier, in which case we
11793 // compute it and do a previous lookup there for a function
11794 // or function template.
11795 } else if (!SS.getScopeRep()->isDependent()) {
11796 DC = computeDeclContext(SS);
11797 if (!DC) return 0;
11798
11799 if (RequireCompleteDeclContext(SS, DC)) return 0;
11800
11801 LookupQualifiedName(Previous, DC);
11802
11803 // Ignore things found implicitly in the wrong scope.
11804 // TODO: better diagnostics for this case. Suggesting the right
11805 // qualified scope would be nice...
11806 LookupResult::Filter F = Previous.makeFilter();
11807 while (F.hasNext()) {
11808 NamedDecl *D = F.next();
11809 if (!DC->InEnclosingNamespaceSetOf(
11810 D->getDeclContext()->getRedeclContext()))
11811 F.erase();
11812 }
11813 F.done();
11814
11815 if (Previous.empty()) {
11816 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011817 Diag(Loc, diag::err_qualified_friend_not_found)
11818 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011819 return 0;
11820 }
11821
11822 // C++ [class.friend]p1: A friend of a class is a function or
11823 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011824 if (DC->Equals(CurContext))
11825 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011826 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011827 diag::warn_cxx98_compat_friend_is_member :
11828 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011829
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011830 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011831 // C++ [class.friend]p6:
11832 // A function can be defined in a friend declaration of a class if and
11833 // only if the class is a non-local class (9.8), the function name is
11834 // unqualified, and the function has namespace scope.
11835 SemaDiagnosticBuilder DB
11836 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11837
11838 DB << SS.getScopeRep();
11839 if (DC->isFileContext())
11840 DB << FixItHint::CreateRemoval(SS.getRange());
11841 SS.clear();
11842 }
John McCallde3fd222010-10-12 23:13:28 +000011843
11844 // - There's a scope specifier that does not match any template
11845 // parameter lists, in which case we use some arbitrary context,
11846 // create a method or method template, and wait for instantiation.
11847 // - There's a scope specifier that does match some template
11848 // parameter lists, which we don't handle right now.
11849 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011850 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011851 // C++ [class.friend]p6:
11852 // A function can be defined in a friend declaration of a class if and
11853 // only if the class is a non-local class (9.8), the function name is
11854 // unqualified, and the function has namespace scope.
11855 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11856 << SS.getScopeRep();
11857 }
11858
John McCallde3fd222010-10-12 23:13:28 +000011859 DC = CurContext;
11860 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011861 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011862
John McCallf7cfb222010-10-13 05:45:15 +000011863 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011864 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011865 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11866 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11867 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011868 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011869 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11870 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011871 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011872 }
John McCall07e91c02009-08-06 02:15:43 +000011873 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011874
Douglas Gregordd847ba2011-11-03 16:37:14 +000011875 // FIXME: This is an egregious hack to cope with cases where the scope stack
11876 // does not contain the declaration context, i.e., in an out-of-line
11877 // definition of a class.
11878 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11879 if (!DCScope) {
11880 FakeDCScope.setEntity(DC);
11881 DCScope = &FakeDCScope;
11882 }
Richard Smith114394f2013-08-09 04:35:01 +000011883
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011884 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011885 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011886 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011887 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011888
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011889 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011890
Richard Smith114394f2013-08-09 04:35:01 +000011891 // If we performed typo correction, we might have added a scope specifier
11892 // and changed the decl context.
11893 DC = ND->getDeclContext();
11894
John McCall759e32b2009-08-31 22:39:49 +000011895 // Add the function declaration to the appropriate lookup tables,
11896 // adjusting the redeclarations list as necessary. We don't
11897 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011898 //
John McCall759e32b2009-08-31 22:39:49 +000011899 // Also update the scope-based lookup if the target context's
11900 // lookup context is in lexical scope.
11901 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011902 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011903 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011904 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011905 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011906 }
John McCallaa74a0c2009-08-28 07:59:38 +000011907
11908 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011909 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011910 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011911 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011912 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011913
John McCalla0a96892012-08-10 03:15:35 +000011914 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011915 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011916 } else {
11917 if (DC->isRecord()) CheckFriendAccess(ND);
11918
John McCall2c2eb122010-10-16 06:59:13 +000011919 FunctionDecl *FD;
11920 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11921 FD = FTD->getTemplatedDecl();
11922 else
11923 FD = cast<FunctionDecl>(ND);
11924
David Majnemer502b0ed2013-06-25 23:09:30 +000011925 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11926 // default argument expression, that declaration shall be a definition
11927 // and shall be the only declaration of the function or function
11928 // template in the translation unit.
11929 if (functionDeclHasDefaultArgument(FD)) {
11930 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11931 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11932 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11933 } else if (!D.isFunctionDefinition())
11934 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11935 }
11936
John McCall2c2eb122010-10-16 06:59:13 +000011937 // Mark templated-scope function declarations as unsupported.
11938 if (FD->getNumTemplateParameterLists())
11939 FrD->setUnsupportedFriend(true);
11940 }
John McCallde3fd222010-10-12 23:13:28 +000011941
John McCall48871652010-08-21 09:40:31 +000011942 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011943}
11944
John McCall48871652010-08-21 09:40:31 +000011945void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11946 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011947
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011948 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011949 if (!Fn) {
11950 Diag(DelLoc, diag::err_deleted_non_function);
11951 return;
11952 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011953
Douglas Gregorec9fd132012-01-14 16:38:05 +000011954 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011955 // Don't consider the implicit declaration we generate for explicit
11956 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011957 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11958 Prev->getPreviousDecl()) &&
11959 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011960 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011961 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11962 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11963 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011964 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011965 // If the declaration wasn't the first, we delete the function anyway for
11966 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011967 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011968 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011969
11970 if (Fn->isDeleted())
11971 return;
11972
11973 // See if we're deleting a function which is already known to override a
11974 // non-deleted virtual function.
11975 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11976 bool IssuedDiagnostic = false;
11977 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11978 E = MD->end_overridden_methods();
11979 I != E; ++I) {
11980 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11981 if (!IssuedDiagnostic) {
11982 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11983 IssuedDiagnostic = true;
11984 }
11985 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11986 }
11987 }
11988 }
11989
Richard Smithb63b6ee2014-01-22 01:43:19 +000011990 // C++11 [basic.start.main]p3:
11991 // A program that defines main as deleted [...] is ill-formed.
11992 if (Fn->isMain())
11993 Diag(DelLoc, diag::err_deleted_main);
11994
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011995 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011996}
Sebastian Redl4c018662009-04-27 21:33:24 +000011997
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011998void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011999 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012000
12001 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012002 if (MD->getParent()->isDependentType()) {
12003 MD->setDefaulted();
12004 MD->setExplicitlyDefaulted();
12005 return;
12006 }
12007
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012008 CXXSpecialMember Member = getSpecialMember(MD);
12009 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012010 if (!MD->isInvalidDecl())
12011 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012012 return;
12013 }
12014
12015 MD->setDefaulted();
12016 MD->setExplicitlyDefaulted();
12017
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012018 // If this definition appears within the record, do the checking when
12019 // the record is complete.
12020 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012021 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012022 // Find the uninstantiated declaration that actually had the '= default'
12023 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012024 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012025
Richard Smith3901dfe2013-03-27 00:22:47 +000012026 // If the method was defaulted on its first declaration, we will have
12027 // already performed the checking in CheckCompletedCXXClass. Such a
12028 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012029 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012030 return;
12031
Richard Smithd3b5c9082012-07-27 04:22:15 +000012032 CheckExplicitlyDefaultedSpecialMember(MD);
12033
Richard Smithbd305122012-12-11 01:14:52 +000012034 // The exception specification is needed because we are defining the
12035 // function.
12036 ResolveExceptionSpec(DefaultLoc,
12037 MD->getType()->castAs<FunctionProtoType>());
12038
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012039 if (MD->isInvalidDecl())
12040 return;
12041
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012042 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012043 case CXXDefaultConstructor:
12044 DefineImplicitDefaultConstructor(DefaultLoc,
12045 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012046 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012047 case CXXCopyConstructor:
12048 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012049 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012050 case CXXCopyAssignment:
12051 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012052 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012053 case CXXDestructor:
12054 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012055 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012056 case CXXMoveConstructor:
12057 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012058 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012059 case CXXMoveAssignment:
12060 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012061 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012062 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012063 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012064 }
12065 } else {
12066 Diag(DefaultLoc, diag::err_default_special_members);
12067 }
12068}
12069
Sebastian Redl4c018662009-04-27 21:33:24 +000012070static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012071 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012072 Stmt *SubStmt = *CI;
12073 if (!SubStmt)
12074 continue;
12075 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012076 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012077 diag::err_return_in_constructor_handler);
12078 if (!isa<Expr>(SubStmt))
12079 SearchForReturnInStmt(Self, SubStmt);
12080 }
12081}
12082
12083void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12084 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12085 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12086 SearchForReturnInStmt(*this, Handler);
12087 }
12088}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012089
David Blaikie68f71a32013-01-18 23:03:15 +000012090bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012091 const CXXMethodDecl *Old) {
12092 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12093 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12094
12095 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12096
12097 // If the calling conventions match, everything is fine
12098 if (NewCC == OldCC)
12099 return false;
12100
Hans Wennborg2545efe2013-12-11 17:42:11 +000012101 // If the calling conventions mismatch because the new function is static,
12102 // suppress the calling convention mismatch error; the error about static
12103 // function override (err_static_overrides_virtual from
12104 // Sema::CheckFunctionDeclaration) is more clear.
12105 if (New->getStorageClass() == SC_Static)
12106 return false;
12107
Reid Kleckner78af0702013-08-27 23:08:25 +000012108 Diag(New->getLocation(),
12109 diag::err_conflicting_overriding_cc_attributes)
12110 << New->getDeclName() << New->getType() << Old->getType();
12111 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12112 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012113}
12114
Mike Stump11289f42009-09-09 15:08:12 +000012115bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012116 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012117 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12118 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012119
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012120 if (Context.hasSameType(NewTy, OldTy) ||
12121 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012122 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012123
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012124 // Check if the return types are covariant
12125 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012126
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012127 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012128 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12129 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012130 NewClassTy = NewPT->getPointeeType();
12131 OldClassTy = OldPT->getPointeeType();
12132 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012133 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12134 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12135 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12136 NewClassTy = NewRT->getPointeeType();
12137 OldClassTy = OldRT->getPointeeType();
12138 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012139 }
12140 }
Mike Stump11289f42009-09-09 15:08:12 +000012141
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012142 // The return types aren't either both pointers or references to a class type.
12143 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012144 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012145 diag::err_different_return_type_for_overriding_virtual_function)
12146 << New->getDeclName() << NewTy << OldTy;
12147 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012148
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012149 return true;
12150 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012151
Anders Carlssone60365b2009-12-31 18:34:24 +000012152 // C++ [class.virtual]p6:
12153 // If the return type of D::f differs from the return type of B::f, the
12154 // class type in the return type of D::f shall be complete at the point of
12155 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012156 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12157 if (!RT->isBeingDefined() &&
12158 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012159 diag::err_covariant_return_incomplete,
12160 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012161 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012162 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012163
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012164 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012165 // Check if the new class derives from the old class.
12166 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12167 Diag(New->getLocation(),
12168 diag::err_covariant_return_not_derived)
12169 << New->getDeclName() << NewTy << OldTy;
12170 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12171 return true;
12172 }
Mike Stump11289f42009-09-09 15:08:12 +000012173
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012174 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012175 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012176 diag::err_covariant_return_inaccessible_base,
12177 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12178 // FIXME: Should this point to the return type?
12179 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012180 // FIXME: this note won't trigger for delayed access control
12181 // diagnostics, and it's impossible to get an undelayed error
12182 // here from access control during the original parse because
12183 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012184 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12185 return true;
12186 }
12187 }
Mike Stump11289f42009-09-09 15:08:12 +000012188
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012189 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012190 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012191 Diag(New->getLocation(),
12192 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012193 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012194 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12195 return true;
12196 };
Mike Stump11289f42009-09-09 15:08:12 +000012197
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012198
12199 // The new class type must have the same or less qualifiers as the old type.
12200 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12201 Diag(New->getLocation(),
12202 diag::err_covariant_return_type_class_type_more_qualified)
12203 << New->getDeclName() << NewTy << OldTy;
12204 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12205 return true;
12206 };
Mike Stump11289f42009-09-09 15:08:12 +000012207
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012208 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012209}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012210
Douglas Gregor21920e372009-12-01 17:24:26 +000012211/// \brief Mark the given method pure.
12212///
12213/// \param Method the method to be marked pure.
12214///
12215/// \param InitRange the source range that covers the "0" initializer.
12216bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012217 SourceLocation EndLoc = InitRange.getEnd();
12218 if (EndLoc.isValid())
12219 Method->setRangeEnd(EndLoc);
12220
Douglas Gregor21920e372009-12-01 17:24:26 +000012221 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12222 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012223 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012224 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012225
12226 if (!Method->isInvalidDecl())
12227 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12228 << Method->getDeclName() << InitRange;
12229 return true;
12230}
12231
Douglas Gregor926410d2012-02-21 02:22:07 +000012232/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012233static bool isStaticDataMember(const Decl *D) {
12234 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12235 return Var->isStaticDataMember();
12236
12237 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012238}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012239
John McCall1f4ee7b2009-12-19 09:28:58 +000012240/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12241/// an initializer for the out-of-line declaration 'Dcl'. The scope
12242/// is a fresh scope pushed for just this purpose.
12243///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012244/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12245/// static data member of class X, names should be looked up in the scope of
12246/// class X.
John McCall48871652010-08-21 09:40:31 +000012247void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012248 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012249 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012250
Richard Smitha2302242013-12-05 07:51:02 +000012251 // We will always have a nested name specifier here, but this declaration
12252 // might not be out of line if the specifier names the current namespace:
12253 // extern int n;
12254 // int ::n = 0;
12255 if (D->isOutOfLine())
12256 EnterDeclaratorContext(S, D->getDeclContext());
12257
Douglas Gregor926410d2012-02-21 02:22:07 +000012258 // If we are parsing the initializer for a static data member, push a
12259 // new expression evaluation context that is associated with this static
12260 // data member.
12261 if (isStaticDataMember(D))
12262 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012263}
12264
12265/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012266/// initializer for the out-of-line declaration 'D'.
12267void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012268 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012269 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012270
Douglas Gregor926410d2012-02-21 02:22:07 +000012271 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012272 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012273
Richard Smitha2302242013-12-05 07:51:02 +000012274 if (D->isOutOfLine())
12275 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012276}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012277
12278/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12279/// C++ if/switch/while/for statement.
12280/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012281DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012282 // C++ 6.4p2:
12283 // The declarator shall not specify a function or an array.
12284 // The type-specifier-seq shall not contain typedef and shall not declare a
12285 // new class or enumeration.
12286 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12287 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012288
12289 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012290 if (!Dcl)
12291 return true;
12292
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012293 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12294 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012295 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012296 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012297 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012298
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012299 return Dcl;
12300}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012301
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012302void Sema::LoadExternalVTableUses() {
12303 if (!ExternalSource)
12304 return;
12305
12306 SmallVector<ExternalVTableUse, 4> VTables;
12307 ExternalSource->ReadUsedVTables(VTables);
12308 SmallVector<VTableUse, 4> NewUses;
12309 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12310 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12311 = VTablesUsed.find(VTables[I].Record);
12312 // Even if a definition wasn't required before, it may be required now.
12313 if (Pos != VTablesUsed.end()) {
12314 if (!Pos->second && VTables[I].DefinitionRequired)
12315 Pos->second = true;
12316 continue;
12317 }
12318
12319 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12320 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12321 }
12322
12323 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12324}
12325
Douglas Gregor88d292c2010-05-13 16:44:06 +000012326void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12327 bool DefinitionRequired) {
12328 // Ignore any vtable uses in unevaluated operands or for classes that do
12329 // not have a vtable.
12330 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012331 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012332 return;
12333
Douglas Gregor88d292c2010-05-13 16:44:06 +000012334 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012335 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012336 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12337 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12338 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12339 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012340 // If we already had an entry, check to see if we are promoting this vtable
12341 // to required a definition. If so, we need to reappend to the VTableUses
12342 // list, since we may have already processed the first entry.
12343 if (DefinitionRequired && !Pos.first->second) {
12344 Pos.first->second = true;
12345 } else {
12346 // Otherwise, we can early exit.
12347 return;
12348 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012349 } else {
12350 // The Microsoft ABI requires that we perform the destructor body
12351 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12352 // the deleting destructor is emitted with the vtable, not with the
12353 // destructor definition as in the Itanium ABI.
12354 // If it has a definition, we do the check at that point instead.
12355 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12356 Class->hasUserDeclaredDestructor() &&
12357 !Class->getDestructor()->isDefined() &&
12358 !Class->getDestructor()->isDeleted()) {
12359 CheckDestructor(Class->getDestructor());
12360 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012361 }
12362
12363 // Local classes need to have their virtual members marked
12364 // immediately. For all other classes, we mark their virtual members
12365 // at the end of the translation unit.
12366 if (Class->isLocalClass())
12367 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012368 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012369 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012370}
12371
Douglas Gregor88d292c2010-05-13 16:44:06 +000012372bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012373 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012374 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012375 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012376
Douglas Gregor88d292c2010-05-13 16:44:06 +000012377 // Note: The VTableUses vector could grow as a result of marking
12378 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012379 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012380 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012381 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012382 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012383 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012384 if (!Class)
12385 continue;
12386
12387 SourceLocation Loc = VTableUses[I].second;
12388
Richard Smithd3b5c9082012-07-27 04:22:15 +000012389 bool DefineVTable = true;
12390
Douglas Gregor88d292c2010-05-13 16:44:06 +000012391 // If this class has a key function, but that key function is
12392 // defined in another translation unit, we don't need to emit the
12393 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012394 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012395 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012396 // The key function is in another translation unit.
12397 DefineVTable = false;
12398 TemplateSpecializationKind TSK =
12399 KeyFunction->getTemplateSpecializationKind();
12400 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12401 TSK != TSK_ImplicitInstantiation &&
12402 "Instantiations don't have key functions");
12403 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012404 } else if (!KeyFunction) {
12405 // If we have a class with no key function that is the subject
12406 // of an explicit instantiation declaration, suppress the
12407 // vtable; it will live with the explicit instantiation
12408 // definition.
12409 bool IsExplicitInstantiationDeclaration
12410 = Class->getTemplateSpecializationKind()
12411 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012412 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012413 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012414 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012415 if (TSK == TSK_ExplicitInstantiationDeclaration)
12416 IsExplicitInstantiationDeclaration = true;
12417 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12418 IsExplicitInstantiationDeclaration = false;
12419 break;
12420 }
12421 }
12422
12423 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012424 DefineVTable = false;
12425 }
12426
12427 // The exception specifications for all virtual members may be needed even
12428 // if we are not providing an authoritative form of the vtable in this TU.
12429 // We may choose to emit it available_externally anyway.
12430 if (!DefineVTable) {
12431 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12432 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012433 }
12434
12435 // Mark all of the virtual members of this class as referenced, so
12436 // that we can build a vtable. Then, tell the AST consumer that a
12437 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012438 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012439 MarkVirtualMembersReferenced(Loc, Class);
12440 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12441 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12442
12443 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012444 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012445 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012446 const FunctionDecl *KeyFunctionDef = 0;
12447 if (!KeyFunction ||
12448 (KeyFunction->hasBody(KeyFunctionDef) &&
12449 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012450 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12451 TSK_ExplicitInstantiationDefinition
12452 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12453 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012454 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012455 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012456 VTableUses.clear();
12457
Douglas Gregor97509692011-04-22 22:25:37 +000012458 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012459}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012460
Richard Smithd3b5c9082012-07-27 04:22:15 +000012461void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12462 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012463 for (const auto *I : RD->methods())
12464 if (I->isVirtual() && !I->isPure())
12465 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012466}
12467
Rafael Espindola5b334082010-03-26 00:36:59 +000012468void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12469 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012470 // Mark all functions which will appear in RD's vtable as used.
12471 CXXFinalOverriderMap FinalOverriders;
12472 RD->getFinalOverriders(FinalOverriders);
12473 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12474 E = FinalOverriders.end();
12475 I != E; ++I) {
12476 for (OverridingMethods::const_iterator OI = I->second.begin(),
12477 OE = I->second.end();
12478 OI != OE; ++OI) {
12479 assert(OI->second.size() > 0 && "no final overrider");
12480 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012481
Richard Smith4ff9ff92012-07-07 06:59:51 +000012482 // C++ [basic.def.odr]p2:
12483 // [...] A virtual member function is used if it is not pure. [...]
12484 if (!Overrider->isPure())
12485 MarkFunctionReferenced(Loc, Overrider);
12486 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012487 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012488
12489 // Only classes that have virtual bases need a VTT.
12490 if (RD->getNumVBases() == 0)
12491 return;
12492
Aaron Ballman574705e2014-03-13 15:41:46 +000012493 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012494 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012495 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012496 if (Base->getNumVBases() == 0)
12497 continue;
12498 MarkVirtualMembersReferenced(Loc, Base);
12499 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012500}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012501
12502/// SetIvarInitializers - This routine builds initialization ASTs for the
12503/// Objective-C implementation whose ivars need be initialized.
12504void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012505 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012506 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012507 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012508 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012509 CollectIvarsToConstructOrDestruct(OID, ivars);
12510 if (ivars.empty())
12511 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012512 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012513 for (unsigned i = 0; i < ivars.size(); i++) {
12514 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012515 if (Field->isInvalidDecl())
12516 continue;
12517
Alexis Hunt1d792652011-01-08 20:30:50 +000012518 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012519 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12520 InitializationKind InitKind =
12521 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012522
12523 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12524 ExprResult MemberInit =
12525 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012526 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012527 // Note, MemberInit could actually come back empty if no initialization
12528 // is required (e.g., because it would call a trivial default constructor)
12529 if (!MemberInit.get() || MemberInit.isInvalid())
12530 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012531
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012532 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012533 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12534 SourceLocation(),
12535 MemberInit.takeAs<Expr>(),
12536 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012537 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012538
12539 // Be sure that the destructor is accessible and is marked as referenced.
12540 if (const RecordType *RecordTy
12541 = Context.getBaseElementType(Field->getType())
12542 ->getAs<RecordType>()) {
12543 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012544 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012545 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012546 CheckDestructorAccess(Field->getLocation(), Destructor,
12547 PDiag(diag::err_access_dtor_ivar)
12548 << Context.getBaseElementType(Field->getType()));
12549 }
12550 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012551 }
12552 ObjCImplementation->setIvarInitializers(Context,
12553 AllToInit.data(), AllToInit.size());
12554 }
12555}
Alexis Hunt6118d662011-05-04 05:57:24 +000012556
Alexis Hunt27a761d2011-05-04 23:29:54 +000012557static
12558void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12559 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12560 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12561 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12562 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012563 if (Ctor->isInvalidDecl())
12564 return;
12565
Richard Smith802c4b72012-08-23 06:16:52 +000012566 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12567
12568 // Target may not be determinable yet, for instance if this is a dependent
12569 // call in an uninstantiated template.
12570 if (Target) {
12571 const FunctionDecl *FNTarget = 0;
12572 (void)Target->hasBody(FNTarget);
12573 Target = const_cast<CXXConstructorDecl*>(
12574 cast_or_null<CXXConstructorDecl>(FNTarget));
12575 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012576
12577 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12578 // Avoid dereferencing a null pointer here.
12579 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12580
12581 if (!Current.insert(Canonical))
12582 return;
12583
12584 // We know that beyond here, we aren't chaining into a cycle.
12585 if (!Target || !Target->isDelegatingConstructor() ||
12586 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012587 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012588 Current.clear();
12589 // We've hit a cycle.
12590 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12591 Current.count(TCanonical)) {
12592 // If we haven't diagnosed this cycle yet, do so now.
12593 if (!Invalid.count(TCanonical)) {
12594 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012595 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012596 << Ctor;
12597
Richard Smith802c4b72012-08-23 06:16:52 +000012598 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012599 if (TCanonical != Canonical)
12600 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12601
12602 CXXConstructorDecl *C = Target;
12603 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012604 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012605 (void)C->getTargetConstructor()->hasBody(FNTarget);
12606 assert(FNTarget && "Ctor cycle through bodiless function");
12607
Richard Smith802c4b72012-08-23 06:16:52 +000012608 C = const_cast<CXXConstructorDecl*>(
12609 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012610 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12611 }
12612 }
12613
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012614 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012615 Current.clear();
12616 } else {
12617 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12618 }
12619}
12620
12621
Alexis Hunt6118d662011-05-04 05:57:24 +000012622void Sema::CheckDelegatingCtorCycles() {
12623 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12624
Douglas Gregorbae31202011-07-27 21:57:17 +000012625 for (DelegatingCtorDeclsType::iterator
12626 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012627 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012628 I != E; ++I)
12629 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012630
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012631 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12632 CE = Invalid.end();
12633 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012634 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012635}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012636
Douglas Gregor3024f072012-04-16 07:05:22 +000012637namespace {
12638 /// \brief AST visitor that finds references to the 'this' expression.
12639 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12640 Sema &S;
12641
12642 public:
12643 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12644
12645 bool VisitCXXThisExpr(CXXThisExpr *E) {
12646 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12647 << E->isImplicit();
12648 return false;
12649 }
12650 };
12651}
12652
12653bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12654 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12655 if (!TSInfo)
12656 return false;
12657
12658 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012659 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012660 if (!ProtoTL)
12661 return false;
12662
12663 // C++11 [expr.prim.general]p3:
12664 // [The expression this] shall not appear before the optional
12665 // cv-qualifier-seq and it shall not appear within the declaration of a
12666 // static member function (although its type and value category are defined
12667 // within a static member function as they are within a non-static member
12668 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012669 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012670 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012671 FindCXXThisExpr Finder(*this);
12672
12673 // If the return type came after the cv-qualifier-seq, check it now.
12674 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012675 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012676 return true;
12677
12678 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012679 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12680 return true;
12681
12682 return checkThisInStaticMemberFunctionAttributes(Method);
12683}
12684
12685bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12686 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12687 if (!TSInfo)
12688 return false;
12689
12690 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012691 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012692 if (!ProtoTL)
12693 return false;
12694
David Blaikie6adc78e2013-02-18 22:06:02 +000012695 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012696 FindCXXThisExpr Finder(*this);
12697
Douglas Gregor3024f072012-04-16 07:05:22 +000012698 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012699 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012700 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012701 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012702 case EST_DynamicNone:
12703 case EST_MSAny:
12704 case EST_None:
12705 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012706
Douglas Gregor3024f072012-04-16 07:05:22 +000012707 case EST_ComputedNoexcept:
12708 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12709 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012710
Douglas Gregor3024f072012-04-16 07:05:22 +000012711 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012712 for (const auto &E : Proto->exceptions()) {
12713 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012714 return true;
12715 }
12716 break;
12717 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012718
12719 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012720}
12721
12722bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12723 FindCXXThisExpr Finder(*this);
12724
12725 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012726 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012727 // FIXME: This should be emitted by tblgen.
12728 Expr *Arg = 0;
12729 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012730 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012731 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012732 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012733 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012734 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012735 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012736 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012737 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012738 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012739 Arg = ETLF->getSuccessValue();
12740 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012741 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012742 Arg = STLF->getSuccessValue();
12743 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012744 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012745 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012746 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012747 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012748 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012749 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012750 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012751 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012752 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12753 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12754 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012755 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012756
12757 if (Arg && !Finder.TraverseStmt(Arg))
12758 return true;
12759
12760 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12761 if (!Finder.TraverseStmt(Args[I]))
12762 return true;
12763 }
12764 }
12765
12766 return false;
12767}
12768
Douglas Gregor433e0532012-04-16 18:27:27 +000012769void
12770Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12771 ArrayRef<ParsedType> DynamicExceptions,
12772 ArrayRef<SourceRange> DynamicExceptionRanges,
12773 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012774 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012775 FunctionProtoType::ExtProtoInfo &EPI) {
12776 Exceptions.clear();
12777 EPI.ExceptionSpecType = EST;
12778 if (EST == EST_Dynamic) {
12779 Exceptions.reserve(DynamicExceptions.size());
12780 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12781 // FIXME: Preserve type source info.
12782 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12783
12784 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12785 collectUnexpandedParameterPacks(ET, Unexpanded);
12786 if (!Unexpanded.empty()) {
12787 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12788 UPPC_ExceptionType,
12789 Unexpanded);
12790 continue;
12791 }
12792
12793 // Check that the type is valid for an exception spec, and
12794 // drop it if not.
12795 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12796 Exceptions.push_back(ET);
12797 }
12798 EPI.NumExceptions = Exceptions.size();
12799 EPI.Exceptions = Exceptions.data();
12800 return;
12801 }
12802
12803 if (EST == EST_ComputedNoexcept) {
12804 // If an error occurred, there's no expression here.
12805 if (NoexceptExpr) {
12806 assert((NoexceptExpr->isTypeDependent() ||
12807 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12808 Context.BoolTy) &&
12809 "Parser should have made sure that the expression is boolean");
12810 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12811 EPI.ExceptionSpecType = EST_BasicNoexcept;
12812 return;
12813 }
12814
12815 if (!NoexceptExpr->isValueDependent())
12816 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012817 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012818 /*AllowFold*/ false).take();
12819 EPI.NoexceptExpr = NoexceptExpr;
12820 }
12821 return;
12822 }
12823}
12824
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012825/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12826Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12827 // Implicitly declared functions (e.g. copy constructors) are
12828 // __host__ __device__
12829 if (D->isImplicit())
12830 return CFT_HostDevice;
12831
12832 if (D->hasAttr<CUDAGlobalAttr>())
12833 return CFT_Global;
12834
12835 if (D->hasAttr<CUDADeviceAttr>()) {
12836 if (D->hasAttr<CUDAHostAttr>())
12837 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012838 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012839 }
12840
12841 return CFT_Host;
12842}
12843
12844bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12845 CUDAFunctionTarget CalleeTarget) {
12846 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12847 // Callable from the device only."
12848 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12849 return true;
12850
12851 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12852 // Callable from the host only."
12853 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12854 // Callable from the host only."
12855 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12856 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12857 return true;
12858
12859 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12860 return true;
12861
12862 return false;
12863}
John McCall5e77d762013-04-16 07:28:30 +000012864
12865/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12866///
12867MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12868 SourceLocation DeclStart,
12869 Declarator &D, Expr *BitWidth,
12870 InClassInitStyle InitStyle,
12871 AccessSpecifier AS,
12872 AttributeList *MSPropertyAttr) {
12873 IdentifierInfo *II = D.getIdentifier();
12874 if (!II) {
12875 Diag(DeclStart, diag::err_anonymous_property);
12876 return NULL;
12877 }
12878 SourceLocation Loc = D.getIdentifierLoc();
12879
12880 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12881 QualType T = TInfo->getType();
12882 if (getLangOpts().CPlusPlus) {
12883 CheckExtraCXXDefaultArguments(D);
12884
12885 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12886 UPPC_DataMemberType)) {
12887 D.setInvalidType();
12888 T = Context.IntTy;
12889 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12890 }
12891 }
12892
12893 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12894
12895 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12896 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12897 diag::err_invalid_thread)
12898 << DeclSpec::getSpecifierName(TSCS);
12899
12900 // Check to see if this name was declared as a member previously
12901 NamedDecl *PrevDecl = 0;
12902 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12903 LookupName(Previous, S);
12904 switch (Previous.getResultKind()) {
12905 case LookupResult::Found:
12906 case LookupResult::FoundUnresolvedValue:
12907 PrevDecl = Previous.getAsSingle<NamedDecl>();
12908 break;
12909
12910 case LookupResult::FoundOverloaded:
12911 PrevDecl = Previous.getRepresentativeDecl();
12912 break;
12913
12914 case LookupResult::NotFound:
12915 case LookupResult::NotFoundInCurrentInstantiation:
12916 case LookupResult::Ambiguous:
12917 break;
12918 }
12919
12920 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12921 // Maybe we will complain about the shadowed template parameter.
12922 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12923 // Just pretend that we didn't see the previous declaration.
12924 PrevDecl = 0;
12925 }
12926
12927 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12928 PrevDecl = 0;
12929
12930 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012931 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012932 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12933 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012934 ProcessDeclAttributes(TUScope, NewPD, D);
12935 NewPD->setAccess(AS);
12936
12937 if (NewPD->isInvalidDecl())
12938 Record->setInvalidDecl();
12939
12940 if (D.getDeclSpec().isModulePrivateSpecified())
12941 NewPD->setModulePrivate();
12942
12943 if (NewPD->isInvalidDecl() && PrevDecl) {
12944 // Don't introduce NewFD into scope; there's already something
12945 // with the same name in the same scope.
12946 } else if (II) {
12947 PushOnScopeChains(NewPD, S);
12948 } else
12949 Record->addDecl(NewPD);
12950
12951 return NewPD;
12952}